使用多节点来部署 WebSocket 时,多节点之间可以借助 Redis 进行通信,这时可以设置 adapter 来实现。
import redis from 'socket.io-redis';
return redis({ host: 'localhost', port: 6379 });
如果 redis 需要设置密码,那么需要稍微改动一下配置。
import adapter from "socket.io-redis";
import redis from "redis";
const pub = redis.createClient(port, host, { auth_pass: pwd });
const sub = redis.createClient(port, host, { return_buffers: true, auth_pass: pwd });
在项目中,合理使用缓存对性能有很大的帮助。ThinkJS 提供了多种的缓存方式,包括:内存缓存、文件缓存、Memcache 缓存、Redis 缓存等。
* `redis` Redis 缓存
如果使用 `redis` 缓存,需要设置 Redis 配置信息,见 [配置](./config.html#redis)。
redis: {
其中 `prefix` 在 `memcache` 和 `redis` 类型中使用,存储时会将缓存 key + prefix 作为新的 key 来存储,用于防止跟其他地方使用的缓存 key 冲突。如果不想设置 prefix,可以将 prefix 设置为空字符串,如:
需要用户登录的网站基本上都离不开 Session,ThinkJS 里默认支持多种类型的 Session,如:`file`,`db`,`redis` 等。
* `redis` Redis 类型
##### redis Session
使用 `redis` 类型的 Session 需要配置 Redis,具体见 [配置](./config.html#redis)。
存放具体某个独立功能的配置,如:`db.js` 为数据库配置,`redis` 为 redis 配置。
redis: {
#### redis
redis 配置,`config/redis.js`。
//指定缓存类型获取,从 redis 里获取缓存
think.cache('name', undefined, {type: 'redis'});
//设置缓存,缓存类型使用redis
type: 'redis'