The Redis database adopts a minimalist design concept, and the latest version of the source code package is less than 2Mb. Its use is also different from ordinary databases. The following article will introduce to you how node.js uses the redis database to cache data. Friends in need can refer to it. Let’s take a look together.
1. Run redis
The Redis server uses port 6379 by default
redis-server
Custom port
redis-server –port 6390
Client
redis-cli
Specify ip and port Connection
redis-cli -h 127.0.0.1 -p 6390
Test whether the client and server are connected
ping
2. Nodejs connects to redis
Connect to the redis server through redis.createClient(port,host,options)
var redis = require("redis") var client = redis.createClient();
/*client.HMSET 保存哈希键值*/ client.HMSET(key,val,function(err,result){ if(err){ return callback({code:0,msg:err}); } callback({code:1,msg:result}); /*设置过期时间为1天*/ client.EXPIRE(bottleId,86400); });
/*随机返回当前数据库的一个键*/ client.RANDOMKEY(function(err,key){ if(!key){ return callback({code:0,msg:'没有数据'}); } /*根据key返回哈希对象*/ client.HGETALL(key,function(err,val){ if(err){ return callback({code:0,msg:err}); } callback({code:1,msg:val}); /*根据key删除键值*/ client.DEL(key); }); });
##3. Redis Common Commands
Redis Command Reference Manual
Clear the databaseFLUSHALL
DEL key
EXISTS key //字符串 HEXISTS key field //查看哈希表 key 中,指定的字段是否存在。
TYPE key
GET key
HGETALL key //获取在哈希表中指定 key 的所有字段和值