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.js 操作 redis #21

Open
zenglinan opened this issue Sep 14, 2019 · 0 comments
Open

随手笔记之 Node.js 操作 redis #21

zenglinan opened this issue Sep 14, 2019 · 0 comments

Comments

@zenglinan
Copy link
Owner

Redis 是高性能的 key-value 形式的数据库, 相比起一般的数据库, 操作简单, 且数据存放在内存中, 响应速度快, 下面记录了一些 Node.js 对 redis 的基本操作

首先当然要先启动 redis 服务
4D}F7P48VKWO4% L4O6@HZ9

1. 连接 redis 数据库

const redis = require('redis')

const redisClient = redis.createClient(6379, '127.0.0.1')  // 指定端口和主机号
redisClient.on('error', err => {
  console.error(err)
})

2. 存取普通数据

读取 redis 是异步操作, 这里我们用 promise 封装一层

function setRedis(key, value){
  redisClient.set(key, value, redis.print)
}

function getRedis(key){
  return new Promise((resolve, reject) => {
    redisClient.get(key, (err, value) => {
      if (err) {
        reject(err)
        return
      }
      resolve(value)
    })
  })
}

3. 存取对象

当然, 对象的存取也可以用上面方法, 只要存的时候用 JSON.stringify 序列化一下, 取的时候反序列化一下。不过, redis 也提供了相关的 api

function setRedis(key, obj){
  redisClient.hmset(key, obj, redis.print)
}
async function getRedis(obj, field){  // 获取 obj[field]
  await redisClient.hget(obj, field, (err, value) => {
    // ...
  })
}
async function getRedis(obj, field){  // 获取 obj[field]
  await redisClient.hkeys(obj, (err, keys) => {  // 获取 obj 的所有键值
    // ...
  })
}
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