redis_db.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var Redis = require('ioredis'); //导入 安装好的 redis. npm i ioredis --save
  2. var { db_config } = require('../config/config.js') // 导入位置文件
  3. //redis 服务启动 /usr/local/bin/redis-server /usr/local/etc/redis.conf
  4. var port = db_config.redis.PORT
  5. var host = db_config.redis.HOST
  6. var username = db_config.redis.USERNAME
  7. var password = db_config.redis.PASSWORD
  8. var REDIS_INSTANCE;
  9. // username: username,
  10. // password: password,
  11. console.log('host , post', host, port, process.env.NODE_ENV)
  12. var opts;
  13. if (process.env.NODE_ENV == 'test') {
  14. opts = {
  15. port: port,
  16. host: host,
  17. connectTimeout: 10000,
  18. }
  19. REDIS_INSTANCE=new Redis.Cluster([opts]);
  20. } else if (process.env.NODE_ENV == 'dev') {
  21. opts = {
  22. port: port,
  23. host: host,
  24. username: username,
  25. password: password,
  26. connectTimeout: 10000,
  27. }
  28. REDIS_INSTANCE = new Redis(opts);
  29. } else if (process.env.NODE_ENV == 'prd') {
  30. opts = {
  31. port: port,
  32. host: host,
  33. username: username,
  34. password: password,
  35. connectTimeout: 10000,
  36. }
  37. REDIS_INSTANCE=new Redis.Cluster([opts]);
  38. }
  39. REDIS_INSTANCE.on('connect', () => {
  40. console.log('connected to redis')
  41. })
  42. REDIS_INSTANCE.on('error', function (err) {
  43. console.log('redis Error ', err);
  44. });
  45. function redis_set(key, value) {
  46. REDIS_INSTANCE.set(key, value);
  47. }
  48. async function redis_get(key) {
  49. console.log("redis get=", key);
  50. return await REDIS_INSTANCE.get(key);
  51. }
  52. /**
  53. * 同步
  54. *
  55. * @param {*} key
  56. * @returns
  57. */
  58. function readRedis(key) {
  59. return new Promise((resolve) => {
  60. redis_get(key).then(result => {
  61. console.log("redis_get=", result); // Prints "value"
  62. resolve(result);
  63. });
  64. })
  65. }
  66. module.exports = {
  67. redis_set,
  68. redis_get,
  69. readRedis,
  70. }