Home > Web Front-end > JS Tutorial > body text

node.js uses redis database to cache data

高洛峰
Release: 2017-03-01 15:56:53
Original
1472 people have browsed it

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
Copy after login

Custom port

redis-server –port 6390
Copy after login

Client

redis-cli
Copy after login

Specify ip and port Connection

redis-cli -h 127.0.0.1 -p 6390
Copy after login

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();
Copy after login

/*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);
});
Copy after login

/*随机返回当前数据库的一个键*/
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);
 });
});
Copy after login

##3. Redis Common Commands

Redis Command Reference Manual

Clear the database

FLUSHALL
Copy after login

Delete key

DEL key
Copy after login

Check whether the key exists.

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

Returns the type of value stored in key.

TYPE key
Copy after login

Get the value stored by key

String


GET key
Copy after login

Hash


HGETALL key //获取在哈希表中指定 key 的所有字段和值
Copy after login
For more node.js using redis database to cache data related articles, please pay attention to the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!