use_redis.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const redis = require("redis");
  2. const config = require('../etc/config.json')
  3. const redis_help ={}
  4. const redis_config = config.redis_config
  5. const client = redis.createClient();
  6. client.on('error', (err) => {
  7. console.error('Redis Client Error', err);
  8. });
  9. redis_help.isInit = false
  10. redis_help.setKeyValue = function(key, value) {
  11. return client.set(key, value+"").then((status)=>{
  12. if(status=="OK"){
  13. // console.log("写入成功!",status,key,value)
  14. }else{
  15. console.error("redis_help.setKeyValue 失败",status,key,value)
  16. }
  17. }).catch((e)=>{
  18. console.error("redis_help.setKeyValue 失败",e,key,value)
  19. });
  20. }
  21. redis_help.getKeyValue = function(key) {
  22. return client.get(key).then((value)=>{
  23. if(value!=undefined&&value!=null){
  24. // console.log("获取成功",value)
  25. }else{
  26. // console.error("redis_help.getKeyValue 失败",value,key)
  27. return null
  28. }
  29. return value
  30. }).catch((e)=>{
  31. // console.error("redis_help.getKeyValue error 失败",e,key)
  32. return null
  33. });
  34. }
  35. redis_help.setKeyWithExpiry = function(key, value, expiryInSeconds) {
  36. return new Promise((resolve, reject) => {
  37. client.setex(key, expiryInSeconds, value, (err, reply) => {
  38. if (err) reject(err);
  39. resolve(reply);
  40. });
  41. });
  42. }
  43. redis_help.deleteKey = function(key) {
  44. return client.del(key).then(()=>{}).catch(()=>{});
  45. }
  46. redis_help.connect = function(call_back){
  47. if(redis_help.isInit){
  48. call_back(true)
  49. }else{
  50. client.connect(redis_config).then(async () => {
  51. console.log('Connected to Redis');
  52. redis_help.isInit = true
  53. call_back(true)
  54. }).catch((err) => {
  55. call_back(false)
  56. console.error('Failed to connect to Redis', err);
  57. }
  58. );
  59. }
  60. }
  61. module.exports = redis_help;