redis-npm的设置中
detect_buffers 建议设置为 true,当传递二进制buffer的时候,再回调中这个buffer会返回回来,true则是将这个返回的二进制变为string
retry_strategy 替代 timeout,具体使用方法在 npm redis 页面有案例

实际操作

  1. // RedisConfig.js 先编写一个redis的配置文件
  2. import redis from 'redis'
  3. const options = {
  4. host: '你的主机地址',
  5. port: 14001,
  6. password: '鉴权密码',
  7. detect_buffers: true,
  8. retry_strategy: function(options) { // 这一段直接从官网复制
  9. if (options.error && options.error.code === "ECONNREFUSED") {
  10. return new Error("The server refused the connection");
  11. }
  12. if (options.total_retry_time > 1000 * 60 * 60) {
  13. return new Error("Retry time exhausted");
  14. }
  15. if (options.attempt > 10) {
  16. return undefined;
  17. }
  18. return Math.min(options.attempt * 100, 3000);
  19. }
  20. }
  21. // 设置client
  22. const client = redis.createClient(options)
  23. // 设置值的函数
  24. const setValue = (key, value) => {
  25. return client.set(key, value)
  26. }
  27. const { promisify } = require('util')
  28. const getAsync = promisify(client.get).bind(client)
  29. // 获取值的函数
  30. const getValue = key => {
  31. return getAsync(key)
  32. }
  33. // 将方法统一暴露出去
  34. export {
  35. client,
  36. getValue,
  37. setValue
  38. }
  1. // test.js 测试文件
  2. import { getValue, setValue } from './RedisConfig'
  3. setValue('imooc', 'imooc message from redis client')
  4. getValue('imooc').then(
  5. res => {
  6. console.log('结果是'+res)
  7. }
  8. )
  1. npx babel-node test.js
  2. 结果是imooc message from redis client