Home >Web Front-end >JS Tutorial >node.js uses redis database to cache data

node.js uses redis database to cache data

高洛峰
高洛峰Original
2017-03-01 15:56:531532browse

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

node.js redis数据库 缓存数据

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 database

FLUSHALL

Delete key

DEL key

Check whether the key exists.

EXISTS key //字符串
HEXISTS key field //查看哈希表 key 中,指定的字段是否存在。

Returns the type of value stored in key.

TYPE key

Get the value stored by key

String


GET key

Hash


HGETALL key //获取在哈希表中指定 key 的所有字段和值

For more node.js using redis database to cache data related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn