1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- const redis = require("redis");
- const config = require('../etc/config.json')
- const redis_help ={}
- const redis_config = config.redis_config
- const client = redis.createClient();
- client.on('error', (err) => {
- console.error('Redis Client Error', err);
- });
-
- redis_help.isInit = false
-
- redis_help.setKeyValue = function(key, value) {
- return client.set(key, value+"").then((status)=>{
- if(status=="OK"){
- // console.log("写入成功!",status,key,value)
- }else{
- console.error("redis_help.setKeyValue 失败",status,key,value)
- }
- }).catch((e)=>{
- console.error("redis_help.setKeyValue 失败",e,key,value)
- });
- }
- redis_help.getKeyValue = function(key) {
- return client.get(key).then((value)=>{
- if(value!=undefined&&value!=null){
- // console.log("获取成功",value)
- }else{
- // console.error("redis_help.getKeyValue 失败",value,key)
- return null
- }
- return value
- }).catch((e)=>{
- // console.error("redis_help.getKeyValue error 失败",e,key)
- return null
- });
- }
- redis_help.setKeyWithExpiry = function(key, value, expiryInSeconds) {
- return new Promise((resolve, reject) => {
- client.setex(key, expiryInSeconds, value, (err, reply) => {
- if (err) reject(err);
- resolve(reply);
- });
- });
- }
- redis_help.deleteKey = function(key) {
- return client.del(key).then(()=>{}).catch(()=>{});
- }
- redis_help.connect = function(call_back){
- if(redis_help.isInit){
- call_back(true)
- }else{
- client.connect(redis_config).then(async () => {
- console.log('Connected to Redis');
- redis_help.isInit = true
- call_back(true)
- }).catch((err) => {
- call_back(false)
- console.error('Failed to connect to Redis', err);
- }
- );
- }
-
- }
- module.exports = redis_help;
|