Koa2-CJS/examples/dbs/mysql/db/redis.js

50 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 连接池
//! unusable
/* 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'
});
}); */