Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster
Redis是一个开源(BSD许可),内存中的数据结构存储,用作数据库、缓存和消息代理。它支持数据结构,如字符串、哈希、列表、集合、带范围查询的排序集、位图、超日志、带有radius查询和流的地理空间索引。通过Redislu脚本和Redislu在不同级别上提供了高可用性,并通过Redislu提供了不同级别的事务自动分区和重新分发
优点:
1.性能极高
2.数据类型丰富
3.原子性,即成功就执行,失败就完全不执行
在node中使用redis
npm install redis
初始化
const redis = require('redis');
const client = redis.createClient( 6379, '127.0.0.1');
const password = "123456";
client.auth(password,()=>{
console.log("启动成功");
})
存储获取键值对
get/set
client.set('color', 'red', redis.print);
client.get('color', function(err, value) {
if (err) throw err;
console.log('Got: ' + value)
client.quit();
})
hash
类似ES6中的Map
client.hmset('kitty', {
'age': '2-year-old',
'sex': 'male'
}, redis.print);
client.hget('kitty', 'age', function(err, value) {
if (err) throw err;
console.log('kitty is ' + value);
});
client.hkeys('kitty', function(err, keys) {
if (err) throw err;
keys.forEach(function(key, i) {
console.log(key, i);
});
client.quit();
});
result:
Reply: OK
kitty is 2-year-old
age 0
sex 1
链表
Redis链表类似js中的数组
lpush向链表中添加值,lrange获取参数start和end范围内的链表元素, 参数end为-1,表明到链表中最后一个元素
client.lpush('tasks', 'Paint the house red.', redis.print);
client.lpush('tasks', 'Paint the house green.', redis.print);
client.lrange('tasks', 0, -1, function(err, items) {
if (err) throw err;
items.forEach(function(item, i) {
console.log(' ' + item);
});
client.quit();
});
result:
Reply: 1
Reply: 2
Paint the house green.
Paint the house red.
集合
类似js中的Set,集合中元素必须唯一
client.sadd('ip', '192.168.3.7', redis.print);
client.sadd('ip', '192.168.3.7', redis.print);
client.sadd('ip', '192.168.3.9', redis.print);
client.smembers('ip', function(err, members) {
if (err) throw err;
console.log(members);
client.quit();
});