1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- var Redis = require('ioredis'); //导入 安装好的 redis. npm i ioredis --save
- var { db_config } = require('../config/config.js') // 导入位置文件
- //redis 服务启动 /usr/local/bin/redis-server /usr/local/etc/redis.conf
- var port = db_config.redis.PORT
- var host = db_config.redis.HOST
- var username = db_config.redis.USERNAME
- var password = db_config.redis.PASSWORD
- var REDIS_INSTANCE
- // username: username,
- // password: password,
- console.log('host , post', host, port, process.env.NODE_ENV)
- var opts;
- if (process.env.NODE_ENV == 'test') {
- opts = {
- port: port,
- host: host,
- connectTimeout: 10000,
- }
- } else if (process.env.NODE_ENV == 'dev') {
- opts = {
- port: port,
- host: host,
- username: username,
- password: password,
- connectTimeout: 10000,
- }
- } else if (process.env.NODE_ENV == 'prd') {
- opts = {
- port: port,
- host: host,
- username: username,
- password: password,
- connectTimeout: 10000,
- }
- }
- REDIS_INSTANCE = new Redis(opts);
- REDIS_INSTANCE.on('connect', () => {
- console.log('connected to redis')
- })
- REDIS_INSTANCE.on('error', function (err) {
- console.log('redis Error ', err);
- });
- function redis_set(key, value) {
- REDIS_INSTANCE.set(key, value);
- }
- async function redis_get(key) {
- console.log("redis get=", key);
- return await REDIS_INSTANCE.get(key);
- }
- /**
- * 同步
- *
- * @param {*} key
- * @returns
- */
- function readRedis(key) {
- return new Promise((resolve) => {
- redis_get(key).then(result => {
- console.log("redis_get=", result); // Prints "value"
- resolve(result);
- });
- })
- }
- module.exports = {
- redis_set,
- redis_get,
- readRedis,
- }
|