1. Redis operation-linux
①, key key
keyword (format) | meaning | example |
---|---|---|
keys pattern | View all keys in the current library (in the database). | keys * |
scan | View all keys in the current library (outside the database). | redis-cli --scan |
exists key | Determine whether a key exists, return 1 for existence, and 0 for non-existence. | exists k1 |
type key | View the type of value stored by the current key. | type k1 |
del key | Delete the existing key, and the non-existing key will be ignored. | of the k1 |
expire key time | Set an expiration time of time seconds for the key. 1: success; 0: does not exist. | expire k1 10 |
ttl key | Returns the remaining expiration time in seconds. -2: Not stored; -1: No expiration time is set. | ttl k1 |
persist key | Remove the expiration time so that the key never expires. 1: Removed successfully. | persist key |
- keys
View all keys in the current library.
wildcard | meaning | example |
---|---|---|
* | Wildcard any number of characters | keys * |
? | wildcard a single character | keys ?k |
[] | 1 character within wildcard brackets |
# 格式
keys 通配符
# 示例
keys *
Notice:
Production has been banned. Because redis is blocked for a long time, the command requests of other clients are always blocked. A safer approach is to use scan.
redis-cli --scan "u*" "user1" "user"
- exists
Determine whether a key exists, return 1 for existence, and 0 for non-existence.
# 格式
exists key
# 示例
exists k1
- type
View the type of value stored by the current key. Returns the type of value stored by the current key, such as string, list, etc.
# 格式
type key
# 示例
type k1
- of the
Delete the existing key, and the non-existing key will be ignored. You can set multiple keys and return the number of successful deletions
# 格式
del key
# 示例
del k1 k2 k3
- expire
Set an expiration time of time seconds for the key. Set returns 1 successfully. Returns 0 when the key does not exist.
# 格式
expire key time
# 示例
expire k1 10
- ttl
Returns the key's remaining expiration time in seconds. Returns -2 when key does not exist. Returns -1 when the key exists but no remaining lifetime is set. Otherwise, returns the remaining lifetime of the key in seconds.
# 格式
ttl key
# 示例
ttl k1
- persist
Removes the expiration time for the given key, making the key never expire. Returns 1 when the expiration time is removed successfully. Returns 0 if the key does not exist or the key does not have an expiration time set.
# 格式
persist key
# 示例
persist key
- example
persist k1
②、String
String is the most basic type of Redis, and a key corresponds to a value. String is binary safe, which means that String can contain any data, such as a serialized object or an image. String can hold up to 512M data. value can be a number in addition to a string.
scenes to be used
- counter
- Count the number of multiple units
- Number of fans
- object cache storage
- distributed lock
string set operation
keywords | meaning | example |
---|---|---|
set | Set the value for the given key. The old value can be overwritten regardless of type. | set k1 12 |
get | Used to get the value of the specified key. Returns nil if key does not exist. | get k1 |
append | Append the given value to the end of the original value of key. | append k1 str |
setnx | Only set the value of the key if the key does not exist. | setnx k2 22 |
anxious | get \textcolor{red}{get}Get the value within the specified range, similar to the relationship between...and | narrowed k1 2 -1 |
setrange | replace \textcolor{red}{replace}Replace the value within the specified range, similar to the relationship between...and | setrange k1 2 test |
mset | Set one or more key-value at the same time. | mset k3 test1 k4 test2 |
getset | First get and then immediately set. | getset k1 java |
- set
Used to set the value of the given key. If the key already stores another value, set overwrites the old value, regardless of the type.
# 格式
set key value
# 示例
set k1 12
- get
Used to get the value of the specified key. Returns nil if key does not exist.
# 格式
get key
# 示例
get k1
- append
Append the given value to the end of the original value of key.
# 格式
append key value
# 示例
append k1 str
- setnx
Only set the value of the key if the key does not exist
# 格式
setnx key value
# 示例
setnx k2 22
- anxious
Get the value within the specified range, similar to the relationship between...and
# 格式
getrange key start end
# 示例
getrange k1 2 -1
- setrange
Replace the value within the specified range, similar to the relationship between...and
# 格式
setrange key offset value
# 示例
setrange k1 2 test
- mset
Set one or more key-value at the same time.
# 格式
mset key1 value1 key2 value2
# 示例
mset k3 test1 k4 test2
- getset
Set the given key value as value, and return the old value of the key (old value), in a simple sentence (get first and then set immediately).
# 格式
getset key value
# 示例
getset k1 java
string manipulation
keywords | meaning | example |
---|---|---|
strlen | Gets the length of a string value. Returns an error when something other than a string value is stored. | strlen k1 |
sevenx | Set the key value expiration time. If the key exists, the old value will be replaced and the expiration time will be set. | setex k1 10 test |
increase/decrease | Increment/decrement the numeric value stored in key by one. | incr k2 |
incrby/decrby | Increase or decrease the digital value stored in the key according to the step. | incrby k2 10 |
- strlen
Get the length of the string value stored by the specified key. Returns an error when the key does not store a string value.
# 格式
strlen key
# 示例
strlen k1
- sevenx
Set a value and an expiration time in time seconds for the specified key. If the key already exists, the setex command will replace the old value and set the expiration time.
# 格式
setex key time value
# 示例
setex k1 10 test
- incr
Increment the numeric value stored in key by one.
# 格式
incr key
# 示例
incr k2
- Dec
Decrements the numeric value stored in key by one.
# 格式
decr key
# 示例
decr k2
- incrby/decrby
Increase or decrease the digital value stored in the key according to the step.
# 格式
incrby/decrby key step
# 示例
incrby k2 10
③、List
List is simply a list of strings, sorted by insertion order. You can add an element to the head (left) or tail (right) of the list. The bottom layer is a doubly linked list, which has extremely high performance for two-stage operations, and the performance of nodes in the middle through index operations is poor. A List can contain up to 2 32 − 1 2^{32}-1232−1 element (over 4 billion elements per list).
scenes to be used
- message queue
- leaderboard
- latest list
Add list element
keywords | meaning | example |
---|---|---|
lpush/rpush | Insert one or more values from left (head)/right (tail). | lpush list 333 |
lensed | Insert a new value before/after the specified value (starting from the left). | linsert list before 44 test |
- lpush/rpush
Insert one or more values from left (head)/right (tail)
# 格式
lpush/rpush key1 value1 value2 value3……
# 示例
lpush list 333
- lensed
Insert a new value before/after value in the list (starting from the left).
# 格式
linsert key before/after value newvalue
# 示例
linsert list before 44 test
Query list elements
keywords | meaning | example |
---|---|---|
lrange | Returns the elements between start and end in the key list (including start and end). | lrange list 0 -1 |
lindex | Get the value at index position of the list (starting from the left). | index list -1 |
curtain | Get the length of the list. | llen list |
- lrange
Returns the elements between start and end in the key list (including start and end). Where 0 represents the first element of the list and -1 represents the last element.
# 格式
lrange key start end
# 示例
lrange list 0 -1
- lindex
Take the value at index position of the list (starting from the left).
# 格式
lindex key index
# 示例
lindex list -1
- curtain
Get the length of the list.
# 格式
llen key
# 示例
llen list
删除list元素
关键字 | 含义 | 示例 |
---|---|---|
lpop/rpop | 移除并返回第一个值或最后一个值。 | lpop list |
lrem | 从左边开始删除与value相同的count个元素。 | lrem list 123 |
- lpop/rpop
移除并返回第一个值或最后一个值。
# 格式
lpop/rpop key
# 示例
lpop list
- lrem
从左边开始删除与value相同的count个元素。
# 格式
lrem key count value
# 示例
lrem list 123
修改list元素
关键字 | 含义 | 示例 |
---|---|---|
lset | 将索引为index的值设置为value | lset list 2 test1 |
- lset
将索引为index的值设置为value
# 格式
lset key index value
# 示例
lset list 2 test1
④、Set
与List类似是一个列表功能,但Set是自动排重的,当需要存储一个列表数据,又不希望出现重复数据时,Set是一个很好的选择。Set是String类型的无序集合,它底层其实是一个value为null的hash表,所以添加、删除、查找的时间复杂度都是O(1)。
使用场景
- 黑白名单
- 随机展示
- 好友
- 关注人
- 粉丝
- 感兴趣的人集合
增加set元素
关键字 | 含义 | 示例 |
---|---|---|
sadd | 将一个或多个元素添加到集合key中,已经存在的元素将被忽略。 | sadd setlist test1 test2 |
smove | 将value元素从sourcekey集合移动到destinationkey集合中。 | smove setlist2 setlist tt1 |
- sadd
将一个或多个元素添加到集合key中,已经存在的元素将被忽略。
# 格式
sadd key value1 value2……
# 示例
sadd setlist test1 test2 test3
- smove
将value元素从sourcekey集合移动到destinationkey集合中。如果 sourcekey集合不存在或不包含指定的 value元素,则smove 命令不执行任何操作,仅返回 0 。
# 格式
smove sourcekey destinationkey value
# 示例
smove setlist2 setlist tt1
查询set元素
关键字 | 含义 | 示例 |
---|---|---|
smembers | 取出该集合的所有元素。 | smembers setlist |
sismember | 判断集合key中是否含有value元素,如有返回1,否则返回0。 | sismember setlist tt1 |
scard | 返回该集合的元素个数。 | scard setlist |
srandmember | 随机取出集合中count个元素,但不会删除。 | srandmember setlist 2 |
- smembers
取出该集合的所有元素。
# 格式
smembers key
# 示例
smembers setlist
- sismember
判断集合key中是否含有value元素,如有返回1,否则返回0。
# 格式
sismember key value
# 示例
sismember setlist tt1
- scard
返回该集合的元素个数。
# 格式
scard key
# 示例
scard setlist
- srandmember
随机取出集合中count个元素,但不会删除。
# 格式
srandmember key count
# 示例
srandmember setlist 2
删除set元素
关键字 | 含义 | 示例 |
---|---|---|
srem | 删除集合中的一个或多个成员元素,不存在的成员元素会被忽略。 | srem setlist test1 |
spop | 随机删除集合中一个元素并返回该元素。 | spop setlist |
- srem
删除集合中的一个或多个成员元素,不存在的成员元素会被忽略。
# 格式
srem key value1 value2……
# 示例
srem setlist test1
- spop
随机删除集合中一个元素并返回该元素。
# 格式
spop key
# 示例
spop setlist
交集并集差集
关键字 | 含义 | 示例 |
---|---|---|
sinter | 返回两个集合的交集元素。 | sinter setlist setlist2 |
sunion | 返回两个集合的并集元素。 | sunion setlist setlist2 |
sdiff | 返回两个集合的差集元素(key1中的,不包含key2) | sdiff setlist setlist2 |
- sinter
返回两个集合的交集元素。
# 格式
sinter key1 key2
# 示例
sinter setlist setlist2
- sunion
返回两个集合的并集元素。
# 格式
sunion key1 key2
# 示例
sunion setlist setlist2
- sdiff
返回两个集合的差集元素(key1中的,不包含key2)
# 格式
sdiff key1 key2
# 示例
sdiff setlist setlist2
⑤、Hash
Hash是一个键值对的集合。Hash 是一个 String 类型的 field(字段) 和 value(值) 的映射表,hash 特别适合用于存储对象。
使用场景
- 购物车
- 存储对象
设置hset的值
关键字 | 含义 | 示例 |
---|---|---|
hset | 给key集合中的field赋值value。 | hset user name test age 12 sex “男” |
hget | 从key哈希中,取出field字段的值。 | hget user name |
hmset | 批量设置哈希的字段及值。 | hmset user name java age 22 sex nan |
hsetnx | 给key哈希表中不存在的的字段赋值 。 | hsetnx user h 115 |
- hset
给key集合中的field赋值value。
# 格式
hset key field value
# 示例
hset user name test age 12 sex "男"
- hget
从key哈希中,取出field字段的值。
# 格式
hget key field
# 示例
hget user name
- hmset
批量设置哈希的字段及值。
# 格式
hmset key field1 value1 field2 value2……
# 示例
hmset user name java age 22 sex nan
- hsetnx
给key哈希表中不存在的的字段赋值 。
# 格式
hsetnx key field value
# 示例
hsetnx user h 115
查询hset信息
关键字 | 含义 | 示例 |
---|---|---|
hexists | 判断指定key中是否存在field。1:含有 ;0:不含/不存在 。 | hexists user name |
hkeys | 获取该哈希中所有的field。 | hkeys user |
hvals | 获取该哈希中所有的value。 | hvals user |
- hexists
判断指定key中是否存在field,如果哈希表含有给定字段,返回 1 。 如果哈希表不含有给定字段,或 key 不存在,返回 0 。
# 格式
hexists key field
# 示例
hexists user name
- hkeys
获取该哈希中所有的field。
# 格式
hkeys key
# 示例
hkeys user
- hvals
获取该哈希中所有的value。
# 格式
hvals key
# 示例
hvals user
修改hset中的值
关键字 | 含义 | 示例 |
---|---|---|
hincrby | 为哈希表key中的field字段的值加上增量increment。 | hincrby user age 5 |
- hincrby
为哈希表key中的field字段的值加上增量increment。
# 格式
hincrby key field increment
# 示例
hincrby user age 5
删除hset中的值
关键字 | 含义 | 示例 |
---|---|---|
hdel | 删除哈希表 key 中的一个或多个指定字段,不存在的字段将被忽略。 | hdel user h |
- hdel
删除哈希表 key 中的一个或多个指定字段,不存在的字段将被忽略。
# 格式
hdel key field1 field2……
# 示例
hdel user h
⑥、Zset
Zset与Set非常相似,是一个没有重复元素的String集合。不同之处是Zset的每个元素都关联了一个分数(score),这个分数被用来按照从低分到高分的方式排序集合中的元素。集合的元素是唯一的,但分数可以重复。
增加zset的元素
关键字 | 含义 | 示例 |
---|---|---|
zadd | 将一个或多个元素(value)及分数(score)加入到有序集key中。 | zadd clazz 99 math |
- zadd
将一个或多个元素(value)及分数(score)加入到有序集key中。
# 格式
zadd key score1 value1 score2 value2……
# 示例
zadd clazz 99 math
查询zset的元素
关键字 | 含义 | 示例 |
---|---|---|
zrange | 返回key集合中的索引start和索引end之间的元素。 | zrange clazz 0 -1 |
zrangebyscore | 返回key集合中的分数1和分数2 之间的元素。 | zrangebyscore clazz 0 100 |
zcount | 统计该集合在分数1到分数2区间中元素的个数。 | zcount clazz 0 100 |
zrank | 返回value在集合中的排名,从0开始。 | zrank clazz math |
- zrange
返回key集合中的索引start和索引end之间的元素(包含start和end)。
# 格式
zrange key start end [withscores]
# 示例
zrange clazz 0 -1
- zrangebyscore
返回key集合中的分数minscore 和分数maxscore 之间的元素(包含minscore 和maxscore )。其中元素的位置按分数值递增(从小到大)来排序。
# 格式
zrangebyscore key minscore maxscore [withscores]
# 示例
zrangebyscore clazz 0 100
- zcount
统计该集合在minscore 到maxscore分数区间中元素的个数。
# 格式
zcount key minscore maxscore
# 示例
zcount clazz 0 100
- zrank
返回value在集合中的排名,从0开始。
# 格式
zrank key value
# 示例
zrank clazz math
修改zset元素
关键字 | 含义 | 示例 |
---|---|---|
zincrby | 为元素value的score加上increment的值。 | zincrby clazz 10 english |
- zincrby
为元素value的score加上increment的值。
# 格式
zincrby key increment value
# 示例
zincrby clazz 10 english
删除zset的元素
关键字 | 含义 | 示例 |
---|---|---|
zrem | 删除该集合下value的元素。 | zrem clazz english |
- zrem
删除该集合下value的元素。
# 格式
zrem key value
# 示例
zrem clazz english
⑦、Bitmaps
在计算机中,用二进制(位)作为存储信息的基本单位,1个字节等于8位。
例如 “abc” 字符串是由 3 个字节组成,计算机存储时使用其二进制表示,"abc"分别对应的ASCII码是97、98、99,对应的二进制是01100001、01100010、01100011,在内存中表示如下:
Redis提供了Bitmaps这个 “数据结构” 可以实现对位的操作:
使用场景
- 活跃天数
- 打卡天数
- 登录天数
- 用户签到
- 统计活跃用户
- 统计用户是否在线
- 实现布隆过滤器
新增Bitmaps元素
关键字 | 含义 | 示例 |
---|---|---|
setbit | 设置Bitmaps中某个偏移量的值。 | setbit zk:1 0 1 |
- setbit
设置Bitmaps中某个偏移量的值。
# 格式
setbit key offset value
# 示例
setbit zk:1 0 1
查询Bitmaps元素
关键字 | 含义 | 示例 |
---|---|---|
getbit | 获取Bitmaps中某个偏移量的值。 | getbit zk:1 0 |
bitcount | 统计字符串被设置为1的bit数量。 | bitcount zk:1 |
- getbit
获取Bitmaps中某个偏移量的值。
# 格式
getbit key offset
# 示例
getbit zk:1 0
- bitcount
统计字符串被设置为1的bit数量。一般情况下,给定的整个字符串都会被进行统计,可以选择通过额外的start和end参数,指定字节组范围内进行统计(包括start和end),0表示第一个元素,-1表示最后一个元素。
# 格式
bitcount key [start end]
# 示例
bitcount zk:1
交集并集
关键字 | 含义 | 示例 |
---|---|---|
bitop | 将多个bitmaps通过求交集/并集方式合并成一个新的bitmaps。 | bitop and test zk:1 zk:2 |
- bitop
将多个bitmaps通过求交集/并集方式合并成一个新的bitmaps。
# 格式
bitop and/or destkey sourcekey1 sourcekey2……
# 示例
bitop and test zk:1 zk:2
⑧、Geospatia
GEO,Geographic,地理信息的缩写。该类型就是元素的二维坐标,在地图上就是经纬度。Redis基于该类型,提供了经纬度设置、查询、范围查询、距离查询、经纬度Hash等常见操作。
使用场景
- 附近的电影院
- 附近的好友
- 离最近的火锅店
关键字 | 含义 | 示例 |
---|---|---|
geoadd | 用于存储指定的地理空间位置。 | geoadd china 116.407143 39.916042 beijin |
geopos | 返回所有指定名称的地理空间位置。 | geopos china beijin |
geodist | 用于返回两个给定位置之间的距离。 | geodist china beijin chengdu |
georadius | 指定半径的所有位置元素。 | georadius china 116.407143 39.916042 1000 km |
- geoadd
坐标拾取器:https://api.map.baidu.com/lbsapi/getpoint/index.html
用于存储指定的地理空间位置,可以将一个或多个经度(longitude)、纬度(latitude)、位置名称(member)添加到指定的 key中。
# 格式
geoadd key longitude latitude member
# 示例
geoadd china 116.407143 39.916042 beijin
- geopos
从给定的 key 里返回所有指定名称(member)的位置(经度和纬度),不存在的返回 nil。
# 格式
geopos key member [member ……]
# 示例
geopos china beijin
- geodist
用于返回两个给定位置之间的距离。
# 格式
geodist key member1 member2 [m|km|ft|mi]
# 示例
geodist china beijin chengdu
- georadius
以给定的经纬度(longitude latitude)为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离(radius )的所有位置元素。
# 格式
georadius key longitude latitude radius m|km|ft|mi
# 示例
georadius china 116.407143 39.916042 1000 km
⑨、Hyperloglog
在我们做站点流量统计的时候一般会统计页面UV(独立访客:uniquevisitor)和PV(即页面浏览量:page view)。redis HyperLogLog是用来做基数统计的算法,HyperLogLog的优点是:在输入元素的数量或者体积非常非常大时,计算基数所需的空间总是固定的、并且使很小的。
使用场景
- 网站PV统计
- 网站UV统计
- 统计访问量(IP数)
- 统计在线用户数
- 统计每天搜索不同词条的个数
- 统计文章真实阅读数
关键字 | 含义 | 示例 |
---|---|---|
pfadd | 将所有元素参数添加到 数据结构中。 | pfadd java user1 user2 user3 xiaoming |
pfcount | 统计基数总数。 | pfcount java python |
pfmerge | 将一个或多个合并成一个。 | pfmerge clazz java python |
- pfadd
将所有元素参数添加到 Hyperloglog 数据结构中。如果至少有个元素被添加返回 1, 否则返回 0。
# 格式
pfadd key element1 element2……
# 示例
pfadd java user1 user2 user3 xiaoming
- pfcount
计算Hyperloglog 近似基数,可以计算多个Hyperloglog ,统计基数总数。
# 格式
pfcount key1 key2……
# 示例
pfcount java python
- pfmerge
将一个或多个Hyperloglog(sourcekey1) 合并成一个Hyperloglog (destkey )。
# 格式
pfmerge destkey sourcekey1 sourcekey2……
# 示例
pfmerge clazz java python
# 二、JAVA整合Redis
version1.0
导入依赖
Jedis是Redis官方推荐的Java连接开发工具
<dependencies>
<!-- redis 依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
配置文件
①、单机配置
public static void main(String[] args) {
/**
* 参数一:ip地址
* 参数二:端口
*/
Jedis jedis = new Jedis("192.168.66.11",6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// end : jedis使用完毕需要关闭
jedis.close();
}
②、集群配置
public static void main(String[] args) throws IOException {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(20);
config.setMaxIdle(10);
config.setMinIdle(5);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("192.168.66.101", 8001));
jedisClusterNode.add(new HostAndPort("192.168.66.102", 8002));
jedisClusterNode.add(new HostAndPort("192.168.66.103", 8003));
JedisCluster jedisCluster = null;
try {
/**
* 参数一:Redis 集群地址
* 参数二:指的是连接一个url的连接等待时间
* 参数三:指的是连接上一个url,获取response的返回等待时间
* 参数四:最大尝试次数
* 参数五:连接密码
* 参数六:Redis 配置
*/
jedisCluster = new JedisCluster(jedisClusterNode, 6000, 5000, 10, "redis-pw", config);
System.out.println(jedisCluster.set("name", "zhangsan"));
System.out.println(jedisCluster.get("name"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedisCluster != null) {
jedisCluster.close();
}
}
}
操作redis
①、String
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11",6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 设置一个key
jedis.set("k1","v1");
// 3. 获取一个key
String res = jedis.get("k1");
// 4. 对某一个key自增
Long ires = jedis.incr("k2");
// end : jedis使用完毕需要关闭
jedis.close();
}
②、List
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11", 6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 向list中添加数据
jedis.lpush("list1", "v1", "v2", "v3");
// 3. 返回list全部数据
List<String> list = jedis.lrange("list1", 0, -1);
// end : jedis使用完毕需要关闭
jedis.close();
}
③、set
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11", 6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 向set中添加数据
jedis.sadd("set1" ,"v1","v2","v2","v3");
// 3. 查看该集合中有多少个元素
jedis.smembers("set1");
// end : jedis使用完毕需要关闭
jedis.close();
}
④、hash
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11", 6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 设置一个hash
jedis.hset("user","age","25");
// 3. 获取该key的所有value
jedis.hvals("user");
// end : jedis使用完毕需要关闭
jedis.close();
}
⑤、zset
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11", 6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 向zset中添加一条数据
jedis.zadd("zset1",100,"java");
// 3. 获取所有的值
jedis.zrange("zset1",0,-1);
// end : jedis使用完毕需要关闭
jedis.close();
}
⑥、Bitmaps
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11", 6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 将b1偏移量为0的位设置为1
jedis.setbit("b1",0, "1");
// 3. 获取b1偏移量为0的位
jedis.getbit("b1",0);
// end : jedis使用完毕需要关闭
jedis.close();
}
⑦、Geospatia
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11", 6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 添加一条地理信息数据
jedis.geoadd("chinacity",116.412318,39.999664,"beijing");
// end : jedis使用完毕需要关闭
jedis.close();
}
⑧、Hyperloglog
类似Linux中操作Redis
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.66.11", 6379);
// 1. 验证是否链接成功
System.out.println(jedis.ping());
// 2. 将所有元素参数添加到 Hyperloglog 数据结构中。
jedis.pfadd("book","c++","java","php");
// end : jedis使用完毕需要关闭
jedis.close();
}
二、SpringBoot整合Redis
Spring-Data-Redis是spring大家族的一部分,通过简单的配置访问Redis服务,对Reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了Redis各种操作、异常处理及序列化,支持发布订阅。
- RedisTemplate介绍
Spring封装了RedisTemplate对象来进行对Redis的各种操作,它支持所有的Redis原生的api。
org.springframework.data.redis.core
Class RedisTemplate<K,V>
注意:
- K:模板中的Redis key的类型,模板中的Redis key的类型(通常为String)如:RedisTemplate<String, Object>。
- V:模板中的Redis value的类型
- RedisTemplate中定义了对5种数据结构操作
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
- StringRedisTemplate与RedisTemplate
- 两者的关系是StringRedisTemplate继承RedisTemplate。
- 两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。
- SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。
version1.0
导入依赖
<dependencies>
<!-- 添加redis 集成依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
</dependencies>
配置文件
①、yml配置文件
- application.yml
# redis 配置
spring:
redis:
#Redis服务器连接地址
# host: 192.168.66.11
cluster:
nodes: 192.168.66.101:8001,192.168.66.8002:8002
#Redis服务器连接端口
port: 6379
jedis:
pool:
#连接池最大连接数(使用负值表示没有限制)
max-active: 8
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
#连接池中的最大空闲连接
max-idle: 8
#连接池中的最小空闲连接
min-idle: 0
#连接超时时间(毫秒)
timeout: 30000
# mysql数据库配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&&useSSL=false
username: root
password: root
# jpa配置
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
# 日志格式
logging:
pattern:
console: '[%yellow(%date{yyyy-MM-dd HH:mm:ss.SSS}) %highlight(%-5level)] [%cyan(%X{traceid}) %magenta(%-15thread)] [%green(%-50logger){50}] : %.4000m%n'
②、redis序列化配置
- class
@Configuration
public class RedisConfig {
/**
* 数据存储 序列化修改
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//添加序列化机制
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
// 添加
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
操作redis
基础操作
通过RedisTemplate对象操作
①、opsForValue(string)
方法 | 含义 | 示例 |
---|---|---|
set | 添加元素 | redisTemplate.opsForValue().set(“k1”,“testk1”); |
添加元素并设置过期时间 | set(“k2”,“test2”,10, TimeUnit.SECONDS); | |
get | 获取元素 | redisTemplate.opsForValue().get(“k1”); |
@Autowired
private RedisTemplate redisTemplate;
@Test
public void addString(){
redisTemplate.opsForValue().set("k1","testk1");
}
②、opsForList(list )
方法 | 含义 | 示例 |
---|---|---|
rightPush | 添加元素 | redisTemplate.opsForList().rightPush(“list”,“test1”); |
range | 获取元素 | redisTemplate.opsForList().range(“list”, 0, -1); |
@Test
public void testList(){
redisTemplate.opsForList().rightPush("list","test1");
}
③、opsForHash(hash)
方法 | 含义 | 示例 |
---|---|---|
put | 添加元素 | redisTemplate.opsForHash().put(“user”,“name”,“xiaoming”); |
get | 获取数据 | redisTemplate.opsForHash().get(“user”, “name”); |
@Test
public void testHash(){
redisTemplate.opsForHash().put("user","name","xiaoming");
}
④、opsForSet(set)
方法 | 含义 | 示例 |
---|---|---|
add | 添加元素 | redisTemplate.opsForSet().add(“k1”,“test2”); |
size | 获取set的长度 | redisTemplate.opsForSet().size(“k1”); |
members | 获取元素 | redisTemplate.opsForSet().members(“k1”); |
@Test
public void testSet(){
redisTemplate.opsForSet().add("k1","test2");
}
⑤、opsForZSet(zset )
方法 | 含义 | 示例 |
---|---|---|
add | 添加元素 | redisTemplate.opsForZSet().add(“clazz”,“math”,99); |
range | 获取元素 | redisTemplate.opsForZSet().range(“clazz”, 0, 100); |
@Test
public void testZset(){
redisTemplate.opsForZSet().add("clazz","math",99);
}
web应用redis
Lombok、spring mvc、spring data redis、spring data jpa
导入依赖
<dependencies>
<!-- redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<!-- jpa 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- spring mvc 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql依赖 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- fast json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- junit -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
配置文件
# redis 配置
spring:
redis:
#Redis服务器连接地址
host: 192.168.66.66
#Redis服务器连接端口
port: 6379
jedis:
pool:
#连接池最大连接数(使用负值表示没有限制)
max-active: 8
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
#连接池中的最大空闲连接
max-idle: 8
#连接池中的最小空闲连接
min-idle: 0
#连接超时时间(毫秒)
timeout: 30000
# mysql数据库配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&&useSSL=false
username: root
password: root
# jpa配置
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
# 日志格式
logging:
pattern:
console: '[%yellow(%date{yyyy-MM-dd HH:mm:ss.SSS}) %highlight(%-5level)] [%cyan(%X{traceid}) %magenta(%-15thread)] [%green(%-50logger){50}] : %.4000m%n'
使用缓存
service
@Service
public class GoodsService {
//商品
@Autowired
private GoodsRepository goodsRepository;
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 根据id获取商品信息
*
* @param id
* @return
*/
public GoodsEntity getId(Long id) {
// 从Redis中获取缓存
String goodsStr = redisTemplate.opsForValue().get("goods:id:" + id);
// 判断是否有缓存
if (StringUtils.isEmpty(goodsStr)) {
//根据id查询商品信息
GoodsEntity goodsEntity = goodsRepository.getById(id);
//添加缓存
redisTemplate.opsForValue().set("goods:id:" + id, JSON.toJSONString(goodsEntity));
return goodsEntity;
} else {
// 把json数据转为goods对象
return JSON.parseObject(goodsStr, GoodsEntity.class);
}
}
}