node.js 操作 Redis 总结

一. 基本功能

  • 缓存数据
  • 数据存储
  • 消息中介

二. 安装命令

$ npm install redis

三. 基本操作

  1. 连接 redis
    // 导入redis
    var redis = require('redis');
    // 连接redis
    var client = redis.createClient(6379,'localhost');
    
  2. string 字符串
    // 增加
    client.set('key', 'value');
    // 获取
    client.get('key', function(err, value) {
        console.log(value);
    });
    // 删除
    client.del('key');
    
  3. hash 散列
    // 在散列里面关联起给定的键值对
    client.hset('hash-key', 'sub-key', 'value');
    // 获取指定散列键的值
    client.hget('hash-key', 'sub-key' function(err, value) {
        console.log(value);
    });
    // 获取散列包含的键值对
    client.hgetall('hash-key', function(err, value) {
        console.log(value);
    });
    // 如果给定键存在于散列里面,则移除这个键
    client.hdel('hash-key', 'sub-key');
    
  4. 其他命令
    // 查询一个key是否存在
    client.exists('key');
    // 设置一个key的过期的秒数
    client.expire('key', 'seconds');
    // 设置一个key的过期的毫秒数
    client.pexpire('key', milliseconds)
    // 设置一个UNIX时间戳的过期时间
    client.expireat('key', timestamp)
    // 设置一个UNIX时间戳的过期时间(毫秒)
    client.pexpireat('key', milliseconds-timestamp)
    // 移除key的过期时间
    client.persist('key');
    

四. 重点知识

node.js 默认操作 redis 都是异步操作, 为了方便对返回值的一系列操作:, 可以使用以下实例 (同步读取数据):

redis.js

// 导入redis
var redis = require('redis');
// 连接redis
var client = redis.createClient(6379,'localhost');

async function get(dbNum) {
    return new Promise((success, error) => {
        client.get("key", (err, value) => {
            if (err) { throw err };
            success(value);
        })
    })
};

module.exports = {
    get,
};

main.js

const redis = require('./redis')

async function main() {
	var value = await redis.get('key');
	console.log(value);
};

main()
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值