redis_db.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /**
  50. * 同步
  51. *
  52. * @param {*} key
  53. * @returns
  54. */
  55. function readRedis(key) {
  56. return new Promise((resolve) => {
  57. redis_get(key).then(result => {
  58. console.log("redis_get=", result); // Prints "value"
  59. resolve(result);
  60. });
  61. })
  62. }
  63. module.exports = {
  64. redis_set,
  65. redis_get,
  66. readRedis,
  67. }