41 lines
1.3 KiB
TypeScript
41 lines
1.3 KiB
TypeScript
import Redis from "ioredis";
|
|
import { useConfig } from '@kevisual/use-config';
|
|
import { useContextKey } from "@kevisual/context";
|
|
|
|
export const config = useConfig()
|
|
// 首先从 process.env 读取环境变量
|
|
const redisConfig = {
|
|
host: process.env.REDIS_HOST || 'kevisual.cn',
|
|
port: parseInt(process.env.REDIS_PORT || '6379'),
|
|
password: process.env.REDIS_PASSWORD,
|
|
};
|
|
|
|
export const createRedisClient = (options = {}) => {
|
|
const redis = new Redis({
|
|
// host: 'localhost', // Redis 服务器的主机名或 IP 地址
|
|
// port: 6379, // Redis 服务器的端口号
|
|
// password: 'your_password', // Redis 的密码 (如果有)
|
|
db: 0, // 要使用的 Redis 数据库索引 (0-15)
|
|
keyPrefix: '', // key 前缀
|
|
retryStrategy(times) {
|
|
// 连接重试策略
|
|
return Math.min(times * 50, 2000); // 每次重试时延迟增加
|
|
},
|
|
maxRetriesPerRequest: null, // 允许请求重试的次数 (如果需要无限次重试)
|
|
...options,
|
|
});
|
|
// 监听连接事件
|
|
redis.on('connect', () => {
|
|
// console.log('Redis 连接成功');
|
|
});
|
|
|
|
redis.on('error', (err) => {
|
|
// console.error('Redis 连接错误', err);
|
|
});
|
|
redis.on('ready', () => {
|
|
// console.log('Redis 已准备好处理请求');
|
|
});
|
|
return redis;
|
|
};
|
|
const redis = useContextKey('redis', createRedisClient(redisConfig));
|
|
export { redis }; |