50 lines
1.6 KiB
JavaScript
50 lines
1.6 KiB
JavaScript
const redis = require("redis");
|
||
// require("../config/env.config");
|
||
|
||
const { REDIS_HOST, REDIS_PORT, REDIS_DBNAME, REDIS_USER, REDIS_PASSWD } =
|
||
process.env; // REDIS_USER 和 REDIS_PASSWD,需要服务器配置ACL用户名密码
|
||
const URL = `redis://${REDIS_USER}:${REDIS_PASSWD}@${REDIS_HOST}:${REDIS_PORT}/${REDIS_DBNAME}`;
|
||
|
||
// https://github.com/redis/node-redis/tree/master/docs
|
||
// module.exports = redis.createClient({URL});
|
||
const client = redis.createClient({
|
||
// url: URL,
|
||
socket: { host: REDIS_HOST, port: REDIS_PORT },
|
||
password: REDIS_PASSWD,
|
||
// database: REDIS_DBNAME,
|
||
// legacyMode: true, // 语法向后(v3)部分兼容
|
||
});
|
||
|
||
client.on("error", (err) => console.log(`redis client ~ Error ${err}`));
|
||
client.on("connect", () => console.log("redis client ~ connect"));
|
||
client.on("reconnecting", () => console.log("redis client ~ reconnecting"));
|
||
client.on("ready", () => console.log("redis client ~ ready"));
|
||
client.on("end", () => console.log("redis client ~ end"));
|
||
|
||
client.connect();
|
||
client.ping();
|
||
// try {
|
||
// } catch (error) {
|
||
// console.log(error);
|
||
// }
|
||
|
||
module.exports = client;
|
||
|
||
//* 方式二:redis 连接池
|
||
//! 报错,不可用
|
||
/* var redisPool = require("redis-connection-pool")("myRedisPool", {
|
||
host: REDIS_HOST, // default
|
||
port: REDIS_PORT, //default
|
||
max_clients: 30, // defalut
|
||
perform_checks: false, // checks for needed push/pop functionality
|
||
database: 0, // database number to use
|
||
options: {
|
||
auth_pass: REDIS_PASSWD,
|
||
}, //options for createClient of node-redis, optional
|
||
});
|
||
redisPool.set("test-key", "foobar", function (err) {
|
||
redisPool.get("test-key", function (err, reply) {
|
||
console.log(reply); // 'foobar'
|
||
});
|
||
}); */
|