redis_db.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. // username: username,
  9. // password: password,
  10. console.log('host , post', host, port, process.env.NODE_ENV)
  11. var opts;
  12. if (process.env.NODE_ENV == 'test') {
  13. opts = {
  14. port: port,
  15. host: host,
  16. connectTimeout: 10000,
  17. }
  18. } else if (process.env.NODE_ENV == 'dev') {
  19. opts = {
  20. port: port,
  21. host: host,
  22. username: username,
  23. password: password,
  24. connectTimeout: 10000,
  25. }
  26. } else if (process.env.NODE_ENV == 'prd') {
  27. opts = {
  28. port: port,
  29. host: host,
  30. username: username,
  31. password: password,
  32. connectTimeout: 10000,
  33. }
  34. }
  35. var REDIS_INSTANCE = new Redis(opts);
  36. REDIS_INSTANCE.on('connect', () => {
  37. console.log('connected to redis')
  38. })
  39. REDIS_INSTANCE.on('error', function (err) {
  40. console.log('redis Error ', err);
  41. });
  42. function redis_set(key, value) {
  43. REDIS_INSTANCE.set(key, value);
  44. }
  45. async function redis_get(key) {
  46. console.log("redis get=", key);
  47. return await REDIS_INSTANCE.get(key);
  48. }
  49. module.exports = {
  50. redis_set,
  51. redis_get,
  52. }