1.Redis简介

​ Redis(全称:Remote Dictionary Server远程字典服务)是一个开源的使用c语音编写、支持网络、可基于内存的key-value型数据库。

  • 性能极高 读的速度11万次/s 写的速度 8.1万次/s
  • 丰富的数据类型 String List Set Hash Sorted Set(ZSet)
  • 原子性 所有的操作都是原子性的
  • 支持数据的持久化,可将内存中的数据保存到磁盘中,重启时再次加载
  • 支持分布式,主从及发布订阅等

2.Redis与memocached的区别

在这里插入图片描述

3.基本操作

1)String常用操作

相当于Java中的Map<String,Object>。key为字符串,value支持字符串、数值等类型。

//新增key
localhost:0>set name yf
"OK"
//获取key的value
localhost:0>get name
"yf"
//删除key
localhost:0>del name
"1"

localhost:0>set count 1
"OK"
//对指定key的值 自增。但该值必须为数值型
localhost:0>incr count
"2"
//对指定key的值 自增指定的数值
localhost:0>incrby count 2
"4"

2)Hash哈希常见操作

是一个string类型feild和value的映射表,相当于Java中的Map<String,Map<String,Object>>。适用于存储对象数据。

//添加键值对
localhost:0>hset user name yf
"1"

localhost:0>hset user age 26
"1"
//获取键值对的值
localhost:0>hget user name
"yf"

localhost:0>hget user age
"26"
//批量添加
localhost:0>hmset user1 name yf age 18
"OK"

//获取所有的feild-value
localhost:0>hgetall user1
 1)  "name"
 2)  "yf"
 3)  "age"
 4)  "18"
 //删除指定的feild
localhost:0>hdel user1 name
"1"

localhost:0>hgetall user1
 1)  "age"
 2)  "18"

3)List常见操作

按照插入顺序排序,相当于Java中的Map<String,List>,但redis中的list是双向链表实现,支持双向操作。可以当做队列使用。

//给链表尾部添加元素
localhost:0>rpush list-key a b c
"3"
//获取所有元素
localhost:0>lrange list-key 0 -1
 1)  "a"
 2)  "b"
 3)  "c"
 //获取指定索引的元素
localhost:0>lindex list-key 0
"a"
//给链表头部添加元素
localhost:0>lpush list-key z
"4"

localhost:0>lrange list-key 0 -1
 1)  "z"
 2)  "a"
 3)  "b"
 4)  "c"
//从链表头部取出一个元素
localhost:0>lpop list-key
"z"
//从链表尾部取出一个元素
localhost:0>rpop list-key
"c"

localhost:0>lrange list-key 0 -1
 1)  "a"
 2)  "b"

4)Set集合常见操作

是一个无序的,具有去重效果的集合,相当于Java中的Map<String,Set>,也是通过hash表实现的。

//添加元素到集合中
localhost:0>sadd set-key 1 2 3
"3"
//添加元素到集合中
localhost:0>sadd set-key 1
"0"
//获取集合中的所有元素
localhost:0>smembers set-key
 1)  "1"
 2)  "2"
 3)  "3"
 
//判断是否是集合中的成员
localhost:0>sismember set-key 1
"1"

localhost:0>sismember set-key 5
"0"
//返回集合中的size
localhost:0>scard set-key
"3"
//从集合中移除元素
localhost:0>srem set-key 1
"1"

localhost:0>smembers set-key
 1)  "2"
 2)  "3"

5)Sorted Set(ZSET)有序集合常见操作

和set一样,元素不可重复。不同的是sorted set 每个元素都有一个double类型的分数(score),但分数可重复,redis通过元素分数进行升序排序的。适用于排行榜,优先级队列等场景。

//增加元素及分数
localhost:0>zadd zset-key 1 a
"1"
localhost:0>zadd zset-key 2 b
"1"
localhost:0>zadd zset-key 10 g
"1"

//返回集合size
localhost:0>zcard zset-key
"3"

//返回指定元素的分数
localhost:0>zscore zset-key g
"10"

//返回指定分数区间内的元素数
localhost:0>zcount zset-key 1 10
"3"

//对指定元素的分数增加指定数值
localhost:0>zincrby zset-key 2 a
"3"

//通过分数排序 返回指定索引区间的元素
localhost:0>zrange zset-key 0 -1 withscores
 1)  "b"
 2)  "2"
 3)  "a"
 4)  "3"
 5)  "g"
 6)  "10"
 
 //返回指定分数区间的元素
localhost:0>zrangebyscore zset-key 0 5
 1)  "b"
 2)  "a" 
 
 //返回指定分数区间的元素及分数
localhost:0>zrangebyscore zset-key 0 5 withscores
 1)  "b"
 2)  "2"
 3)  "a"
 4)  "3"
 

4.总结

Redis数据结构丰富,性能优越,并可持久化,防止数据丢失,可满足各种使用场景。

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐