Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用node操作redis #12

Open
shen1992 opened this issue Feb 11, 2018 · 0 comments
Open

使用node操作redis #12

shen1992 opened this issue Feb 11, 2018 · 0 comments

Comments

@shen1992
Copy link
Owner

shen1992 commented Feb 11, 2018

1.前言

如果有数据需要临时缓存,并且数据过一段时间就过期,那么使用redis是比较合适的。尤其在性能优化方面,所需要的数据直接从redis里面拿,返回给调用者,这会缩短数据加载的时间。

2.redis的安装和客户端

  • 先安装redis
brew install redis
  • 在terminal中启动redis
redis-server
  • 使用redis客户端
  • 注意要启动redis-server才能使用
redis-cli 
  • 一些简单的操作
get http://yuedu.163.com/

3.在node中使用redis

由于是在node中操作redis,需要安装一个库

npm i redis --save
  • bluebird这个库可以方便的进行一些异步操作
npm i bluebird --save

下面举个栗子

var redis = require('redis')
var bluebird = require('bluebird')
var config = require('./config')

bluebird.promisifyAll(redis.RedisClient.prototype)

class Cache {
  constructor() {
    this._init()
  }

  _init() {
    this.client = redis.createClient(config.port, config.host, {no_ready_check: true})
    this.client.auth(config.password, function () {
      console.log('通过认证!')
    })
    this.client.on('ready', function (res) {
      console.log('ready')
    })
    this.client.on('error', function (err) {
      console.log('Error: ' + err)
    })
  }

  get(key) {
    return this.client.getAsync(key)
  }

  set(key, value) {
    return this.client.setAsync(key, value)
  }

  expire(key) {
    return this.client.expire(key, config.expireTime)
  }

  exit() {
    this.client.quit()
  }
}

module.exports = new Cache

createClient 的时候一定要加no_ready_check,否则连接远端的redis-server的时候会一直报错。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant