redis_db.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. } else if (process.env.NODE_ENV == 'dev') {
  20. opts = {
  21. port: port,
  22. host: host,
  23. username: username,
  24. password: password,
  25. connectTimeout: 10000,
  26. }
  27. } else if (process.env.NODE_ENV == 'prd') {
  28. opts = {
  29. port: port,
  30. host: host,
  31. username: username,
  32. password: password,
  33. connectTimeout: 10000,
  34. }
  35. }
  36. REDIS_INSTANCE = new Redis(opts);
  37. REDIS_INSTANCE.on('connect', () => {
  38. console.log('connected to redis')
  39. })
  40. REDIS_INSTANCE.on('error', function (err) {
  41. console.log('redis Error ', err);
  42. });
  43. function redis_set(key, value) {
  44. REDIS_INSTANCE.set(key, value);
  45. }
  46. async function redis_get(key) {
  47. console.log("redis get=", key);
  48. return await REDIS_INSTANCE.get(key);
  49. }
  50. /**
  51. * 同步
  52. *
  53. * @param {*} key
  54. * @returns
  55. */
  56. function readRedis(key) {
  57. return new Promise((resolve) => {
  58. redis_get(key).then(result => {
  59. console.log("redis_get=", result); // Prints "value"
  60. resolve(result);
  61. });
  62. })
  63. }
  64. module.exports = {
  65. redis_set,
  66. redis_get,
  67. readRedis,
  68. }