hapi js是否使用redis共享session?

Does hapi js uses redis to share session?

Redis 通常被 expressJS 用于跨多个节点 js 进程共享会话。 hapiJs 是否使用类似的技术?

在回答您的问题之前,我想先介绍一下背景知识。是的,您可以使用 Redis 来共享会话,但首先要确保它是您真正使用的 want/need 在会话方面,hapi 和 Express 有点不同。

如果您已经确定这是您想要的设置,请跳至第 2 部分。

1。背景

在 Express 中,唯一存储在您的 cookie 中的是您的会话 ID。 这意味着当您需要扩展到单个服务器之外时,您需要查看共享会话他们以某种方式。 Redis 是一种选择。

Note Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.

https://github.com/expressjs/session#sessionoptions

hapi 的官方会话插件 Yar, takes a slightly different approach than Express. As long as the data that you're trying to store in a session is below maxCookieSize, the entire session will be encrypted (via Iron) 并存储在 cookie 中。这意味着您不需要任何额外的服务器端机器来水平扩展,因为客户端会记住所有内容。

但是,如果这不符合您的要求或者您只是不喜欢它,您可以通过将 Yar 的 maxCookieSize 设置为 0 来强制服务器端存储。

maxCookieSize - maximum cookie size before using server-side storage. Defaults to 1K. Set to zero to always use server-side storage.

https://github.com/hapijs/yar/blob/master/API.md

2。将 Redis 与 Yar 和服务器端存储一起使用

将 Yar 与服务器端存储一起使用时,hapi 将使用其 cache 功能来存储您的数据。例如,要使用 Redis,只需将 Redis cache 配置传递给 Yar:

const Hapi = require('hapi');
const Hoek = require('hoek');

const server = new Hapi.Server({
    cache: {
        engine: require('catbox-redis'),
        name: 'session',                  // cache name
        host: '127.0.0.1',                // redis host
        port: 6379,                       // redis port
        database: 'my-db'                 // redis-db
    }
});

server.register({
    register: require('yar'),
    options: {
        maxCookieSize: 0,                 // force server-side storage
        cache: {
            cache: 'session'
        },
        cookieOptions: {
            password: 'U32KuiKPnVguRKM',  // cookie password
            isSecure: false               // allow non HTTPS
        }
    }
}, (err) => {

    Hoek.assert(!err, err);
    server.start((err) => {

        Hoek.assert(!err, err);
        console.log('Started server');
    });
});