node中使用redis缓存
# redis安装
CentOS 7 安装 Redis4.0.2 (opens new window)
# 连接redis
import * as IORedis from 'ioredis';
import { logger } from 'fd-framework';
const log = logger.get('framework');
const config = {
alias: 'app-redis',
port: 6379, // Redis port
host: '148.70.216.46', // Redis host
family: 4, // 4 (IPv4) or 6 (IPv6)
password: 'fang674123',
db: 0,
};
const init = () => {
const client = new IORedis(config);
client.on('connect', () => {
const msg = 'Connected';
log.info(`[${config.alias}]: ${msg}`);
});
client.on('ready', () => {
const msg = 'Ready';
log.info(`[${config.alias}]: ${msg}`);
});
client.on('reconnecting', () => {
const msg = 'Reconnecting';
log.info(`[${config.alias}]: ${msg}`);
});
client.on('end', () => {
const msg = 'Closed';
log.info(`[${config.alias}]: ${msg}`);
});
client.on('error', (err: Error) => {
log.error(`[${config.alias}]: ${err.message}`);
});
};
export default { init };
# redis 设置 取值
# 设置值
/**
* 设置redis
* @param session
* @param key
* @param value
*/
export async function setRedisData(
key: string,
value: Record<string, any> | string,
cacheTime?: number
): Promise<any> {
const redisClient = authRedis ? redis.get(authRedis) : null;
if (!redisClient || !redisClient.isReady) {
const msg = `redis ${redisClient ? redisClient.name : ''} connect failed`;
throw new ServiceError(
SERVICE_CODE.REDIS,
ERROR_CODE.INTERNAL_SERVER_ERROR,
msg
);
}
const cacheKey = `${key}`;
const cacheData = JSON.stringify(value);
log.info('cacheData', cacheData);
await redisClient.set(
cacheKey,
cacheData,
cacheTime ? cacheTime : CACHE_TIME
);
}
# 取值
/**
* redis取值
* @param session
* @param key
* @param value
*/
export async function getRedisData(key: string): Promise<any> {
const redisClient = authRedis ? redis.get(authRedis) : null;
if (!redisClient || !redisClient.isReady) {
const msg = `redis ${redisClient ? redisClient.name : ''} connect failed`;
throw new ServiceError(
SERVICE_CODE.REDIS,
ERROR_CODE.INTERNAL_SERVER_ERROR,
msg
);
}
const cacheKey = `${key}`;
log.info('cacheKey', cacheKey);
try {
const cacheData = await redisClient.get(cacheKey);
return cacheData ? JSON.parse(cacheData) : '';
} catch (e) {
log.error('get Redis data failed:', e);
return '';
}
}
# 总结
redis可简单缓存一些数据,如微信token,session等
上次更新: 2021/12/19, 18:05:42