Redis安装
- 在centOS里通过wget下载redis
[root@localhost ~]# yum -y install wget
[root@localhost ~]# wget http://download.redis.io/releases/redis-4.0.9.tar.gz
[root@localhost ~]# mv redis-4.0.9.tar.gz /opt/software/
[root@localhost ~]# cd /opt/software/
[root@localhost software]# ll
- 在/opt/install里面创建redis目录(这个是安装目录,自己随意放)
[root@localhost install]# cd /opt/install
[root@localhost install]# mkdir redis
[root@localhost install]# cd ../software/
[root@localhost software]# tar -xzvf redis-4.0.9.tar.gz -C /opt/install/redis/
[root@localhost redis]# cd /opt/install/redis
[root@localhost redis]# ll
- 进入目录编译一下,用make命令编译一下
[root@localhost redis]# cd redis-4.0.9/
[root@localhost redis]# make
注意:make命令执行完成编译后,会在src目录下生成6个可执行文件,
分别是redis-server、redis-cli、redis-benchmark、redis-check-aof、redis-check-rdb、redis-sentinel。
- 编译生成的可执行文件拷贝到/usr/local/bin目录下(这个后期可以直接使用命令)
[root@localhost src]# cd /opt/install/redis/redis-4.0.9/src/
[root@localhost src]# cp {redis-server,redis-cli,redis-benchmark,redis-check-aof,redis-check-rdb,redis-sentinel} /usr/local/bin
- 进入redis-4.0.9执行安装命令make install
[root@localhost redis-4.0.9]# make install
cd src && make install
make[1]: Entering directory `/opt/install/redis/redis-4.0.9/src'
CC Makefile.dep
make[1]: Leaving directory `/opt/install/redis/redis-4.0.9/src'
make[1]: Entering directory `/opt/install/redis/redis-4.0.9/src'
Hint: It's a good idea to run 'make test' ;)
INSTALL install
INSTALL install
INSTALL install
INSTALL install
INSTALL install
make[1]: Leaving directory `/opt/install/redis/redis-4.0.9/src'
- 执行基本配置
[root@localhost redis-4.0.9]# ./utils/install_server.sh
一阵回车就可以了,红圈就是默认配置的路径!!!
- 查看开机启动列表
[root@localhost redis-4.0.9]# chkconfig --list
- 开启Redis服务操作通过/etc/init.d/redis_6379 start命令,也可通过(service redis_6379 start);
关闭Redis服务操作通过/etc/init.d/redis_6379 stop命令,也可通过(service redis_6379 stop);
- 远程登陆redis
[root@localhost redis-4.0.9]# cd /etc/redis/
[root@localhost redis]# vim 6379.conf
-
在bind 127.0.0.1前加“#”将其注释掉
-
默认为保护模式,把 protected-mode yes 改为 protected-mode no
-
默认为不守护进程模式,把daemonize no 改为daemonize yes
-
将 requirepass foobared前的“#”去掉,密码改为你想要设置的密码
-
最后就可以在客户端登陆了
-
这是虽然连接成功了,但是会有一个问题,就是在服务器你使用关闭命令时会出现
(error) NOAUTH Authentication required.错误
这是由于配置了密码以后,关闭的时候没有密码,所以会关闭不了。百度了一下,各种杀死进程什么的,感觉很麻烦,最后找到/etc/init.d/redis_6379文件,修改一下代码
$CLIEXEC -a “password” -p $REDISPORT shutdown
然后你就可以运行service redis_6379 stop关闭redis了。
Redis集成SpringBoot
- pom坐标依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
- application.properties
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.163.124.3
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=1qaz@4321
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
- Redis配置类
package com.szq.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig {
/**
* RedisTemplate配置
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
- Redis测试类
package com.szq;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
@SpringBootTest
public class RedisApiApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
//String类型API使用
@Test
public void stringRedisTest() throws Exception{
final String key = "Redis:Study:Order:10011";
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set(key,10011);
valueOperations.increment(key,10011);
System.out.println(valueOperations.get(key));//20022
Map<String,Integer> redisTestMap = new HashMap<>();
redisTestMap.put("order:10012",10012);
redisTestMap.put("order:10013",10013);
valueOperations.multiSet(redisTestMap);
List<String> mList = new ArrayList<>();
mList.add("order:10012");
mList.add("order:10013");
System.out.println(valueOperations.multiGet(mList));//[10012, 10013]
}
}
Redis命令以及使用Java API
- 连接redis客户端
[root@localhost redis]# redis-cli -h 127.0.0.1 -p 6379 a 1qaz@4321
- Redis之String数据类型
1)SET key value
设置指定 key 的值
2)GET key
获取指定 key 的值
[root@localhost redis]# redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> auth 1qaz@4321
OK
127.0.0.1:6379> set myname szq
OK
127.0.0.1:6379> get myname
"szq"
127.0.0.1:6379> set Order:OrderItem:10010 order10010
OK
127.0.0.1:6379> keys Order.*
(empty list or set)
127.0.0.1:6379> keys Order*
1) "Order:OrderItem:10010"
127.0.0.1:6379> get Order:OrderItem:10010
"order10010"
3)MSET key value [key value …]
同时设置一个或多个 key-value 对
4)MGET key1 [key2…]
获取所有(一个或多个)给定 key 的值
127.0.0.1:6379> mset key1 value1 key2 value2 key3 values
OK
127.0.0.1:6379> mget key1 key2 key3
1) "value1"
2) "value2"
3) "values"
127.0.0.1:6379> STRLEN key1
(integer) 6
127.0.0.1:6379> set key4 1
OK
127.0.0.1:6379> get key4
"1"
127.0.0.1:6379> incr key4
(integer) 2
127.0.0.1:6379> incrby key4 10
(integer) 12
- Redis之List数据类型
127.0.0.1:6379> lpush Redis:Study:OrderId:List 10010 10011 10012
(integer) 3
127.0.0.1:6379> lrange Redis:Study:OrderId:List 0 2
1) "10012"
2) "10011"
3) "10010"
127.0.0.1:6379> lindex Redis:Study:OrderId:List 2
"10010"
127.0.0.1:6379> llen Redis:Study:OrderId:List
(integer) 3
127.0.0.1:6379> lpop Redis:Study:OrderId:List
"10012"
127.0.0.1:6379> lrange Redis:Study:OrderId:List 0 2
1) "10011"
2) "10010"
127.0.0.1:6379> lset Redis:Study:OrderId:List 0 10013
OK
127.0.0.1:6379> lrange Redis:Study:OrderId:List 0 2
1) "10013"
2) "10010"
127.0.0.1:6379> rpop Redis:Study:OrderId:List
"10010"
127.0.0.1:6379> rpop Redis:Study:OrderId:List
127.0.0.1:6379> rpush Redis:Study:OrderItem:List 10010 10011 10012
(integer) 3
127.0.0.1:6379> lrange Redis:Study:OrderItem:List 0 2
1) "10010"
2) "10011"
3) "10012"
lpush是从链表头部添加,数据结构类似于栈,从栈顶压栈,从栈顶弹栈,后进先出
rpush是从链表尾部添加,数据结构类似于队列,先进先出
- lpush
将一个或多个值插入到列表头部 - lindex
通过索引获取列表中的元素 - lrange
获取列表指定范围内的元素 - lset
通过索引设置列表元素的值 - rpop
移除列表的最后一个元素,返回值为移除的元素 - rpush
在列表尾部添加一个或多个值
//List类型API使用 [10019, 10018, 10017, 10016, 10015, 10014, 10010, 10011, 10012]
@Test
public void listRedisTest() throws Exception{
final String key = "Redis:Study:OrderItem:List";
ListOperations<String,Integer> listOperations = redisTemplate.opsForList();
listOperations.leftPush(key,10014);
listOperations.leftPush(key,10015);
listOperations.leftPush(key,10016);
ArrayList<Integer> redisCol = Lists.newArrayList(10017, 10018, 10019);
listOperations.leftPushAll(key,redisCol);
System.out.println(listOperations.range(key,0,9));
}
- Redis之List数据类型典型业务场景~队列广播消息通知
临时拓展,在项目中使用定时任务,会存在定时任务之间抢占资源问题,因此可以使用多线程配置定时任务,配合多线程去通知用户发送邮件,不使用传统的遍历阻塞式的发送
package com.szq.config;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 多线程配置
* @Date: 2019/10/30 15:15
**/
public class ThreadConfig {
@Bean("threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor(){
ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
//核心线程数,电脑如果是8核,则配置4
executor.setCorePoolSize(4);
//线程池最大线程数量
executor.setMaxPoolSize(8);
//每个线程存活时间
executor.setKeepAliveSeconds(10);
//线程等待队列大小
executor.setQueueCapacity(8);
//线程等待队列满,则进行等待
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
package com.szq.scheduler;/**
* Created by Administrator on 2019/10/30.
*/
import com.boot.debug.redis.model.entity.Notice;
import com.boot.debug.redis.model.entity.User;
import com.boot.debug.redis.model.mapper.UserMapper;
import com.boot.debug.redis.server.enums.Constant;
import com.boot.debug.redis.server.service.EmailService;
import com.boot.debug.redis.server.thread.NoticeThread;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Redis列表-队列的消费者监听器
* @Author:debug (SteadyJack)
* @Link: weixin-> debug0868 qq-> 1948831260
* @Date: 2019/10/30 14:51
**/
@Component
@EnableScheduling
public class ListListenerScheduler {
private static final Logger log= LoggerFactory.getLogger(ListListenerScheduler.class);
private static final String listenKey= Constant.RedisListNoticeKey;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private UserMapper userMapper;
@Autowired
private EmailService emailService;
//TODO:近实时的定时任务检测
//@Scheduled(cron = "0/10 * * * * ?")
@Scheduled(cron = "0/59 * * * * ?")
public void schedulerListenNotice(){
log.info("----定时任务调度队列监听、检测通告消息,监听list中的数据");
ListOperations<String,Notice> listOperations=redisTemplate.opsForList();
Notice notice=listOperations.rightPop(listenKey);
while (notice!=null){
//TODO:发送给到所有的商户的邮箱
this.noticeUser(notice);
notice=listOperations.rightPop(listenKey);
}
}
//TODO:发送通知给到不同的商户,在这里体现了多线程配置多个定时任务
@Async("threadPoolTaskExecutor")
private void noticeUser(Notice notice){
if (notice!=null){
List<User> list=userMapper.selectList();
//TODO:写法一-java8 stream api触发
/*if (list!=null && !list.isEmpty()){
list.forEach(user -> emailService.emailUserNotice(notice,user));
}*/
//TODO:写法二-线程池/多线程触发
try {
if (list!=null && !list.isEmpty()){
ExecutorService executorService=Executors.newFixedThreadPool(4);
List<NoticeThread> threads= Lists.newLinkedList();
list.forEach(user -> {
threads.add(new NoticeThread(user,notice,emailService));
});
executorService.invokeAll(threads);
}
}catch (Exception e){
log.error("近实时的定时任务检测-发送通知给到不同的商户-法二-线程池/多线程触发-发生异常:",e.fillInStackTrace());
}
}
}
}
package com.szq.thread;
import com.boot.debug.redis.model.entity.Notice;
import com.boot.debug.redis.model.entity.User;
import com.boot.debug.redis.server.service.EmailService;
import java.io.Serializable;
import java.util.concurrent.Callable;
/**
* 发送通告到商户的thread
**/
public class NoticeThread implements Callable<Boolean>{
private User user;
private Notice notice;
private EmailService emailService;
public NoticeThread(User user, Notice notice, EmailService emailService) {
this.user = user;
this.notice = notice;
this.emailService = emailService;
}
@Override
public Boolean call() throws Exception {
emailService.emailUserNotice(notice,user);
return true;
}
}
- Redis之集合Set
127.0.0.1:6379> sadd Redis:Study:OrderItem:Set2 "e" "f" "g" "h" "i" "j"
(integer) 6
127.0.0.1:6379> smembers Redis:Study:OrderItem:Set1
1) "b"
2) "a"
3) "c"
4) "e"
5) "f"
6) "d"
127.0.0.1:6379> smembers Redis:Study:OrderItem:Set2
1) "e"
2) "h"
3) "g"
4) "i"
5) "j"
6) "f"
127.0.0.1:6379> scard Redis:Study:OrderItem:Set1
(integer) 6
127.0.0.1:6379> sdiff Redis:Study:OrderItem:Set1 Redis:Study:OrderItem:Set2
1) "d"
2) "c"
3) "a"
4) "b"
127.0.0.1:6379> sinter Redis:Study:OrderItem:Set1 Redis:Study:OrderItem:Set2
1) "e"
2) "f"
127.0.0.1:6379> sunion Redis:Study:OrderItem:Set1 Redis:Study:OrderItem:Set2
1) "f"
2) "d"
3) "b"
4) "a"
5) "i"
6) "c"
7) "h"
8) "g"
9) "e"
10) "j"
127.0.0.1:6379> spop Redis:Study:OrderItem:Set1
"c"
127.0.0.1:6379> srem Redis:Study:OrderItem:Set1 a b d
(integer) 3
1 SADD key member1 [member2]
向集合添加一个或多个成员
2 SCARD key
获取集合的成员数
3 SDIFF key1 [key2]
返回第一个集合与其他集合之间的差异。
4 SDIFFSTORE destination key1 [key2]
返回给定所有集合的差集并存储在 destination 中
5 SINTER key1 [key2]
返回给定所有集合的交集
6 SINTERSTORE destination key1 [key2]
返回给定所有集合的交集并存储在 destination 中
7 SISMEMBER key member
判断 member 元素是否是集合 key 的成员
8 SMEMBERS key
返回集合中的所有成员
9 SMOVE source destination member
将 member 元素从 source 集合移动到 destination 集合
10 SPOP key
移除并返回集合中的一个随机元素
11 SRANDMEMBER key [count]
返回集合中一个或多个随机数
12 SREM key member1 [member2]
移除集合中一个或多个成员
13 SUNION key1 [key2]
返回所有给定集合的并集
14 SUNIONSTORE destination key1 [key2]
所有给定集合的并集存储在 destination 集合中
15 SSCAN key cursor [MATCH pattern] [COUNT count]
迭代集合中的元素
//set集合API使用
@Test
public void setRedisTest() throws Exception{
final String key1 = "Redis:Study:OrderItem:Set3";
final String key2 = "Redis:Study:OrderItem:Set3";
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.add(key1,new String[]{"a", "b", "c"});
setOperations.add(key2,new String[]{"c", "d", "e"});
setOperations.members(key1);//查询集合所有元素
setOperations.members(key2);
setOperations.randomMember(key1);//随机展示集合元素
setOperations.randomMembers(key2,2L);//随机展示集合两个元素
setOperations.size(key1);
setOperations.isMember(key1,"a");//用于判断集合中是否存在某个元素,可以用于重复判断逻辑
setOperations.difference(key1,key2);//差集
setOperations.intersect(key1,key1);//交集
setOperations.union(key1,key2);//并集
setOperations.pop(key1);//随机弹出
setOperations.remove(key1,"c");//删除指定的元素
setOperations.distinctRandomMembers(key2,3);//从set中随机取出不会重复的3个元素,使用于生成随机的考试答卷场景
setOperations.randomMembers(key2,3);//随机取出三个随机元素,可能会出现重复元素
Collections.shuffle(new ArrayList<> ());//这也是一种乱序的集合列表方式
}
1、数据类型值集合set~业务场景:用户注册重复提交
内容:元素过滤、去重、大数集合中判重!SEMBERS SISMBER命令
2、随机问题列表:
- Redis 有序集合(sorted set)
Java中set是不重复且无序的,list是可重复有序的,而Redis的sorted set则是不重复且有序的数据结构。Redis 有序集合和集合一样也是string类型元素的集合,且不允许重复的成员。
不同的是每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。有序集合的成员是唯一的,但分数(score)却可以重复。集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。 集合中最大的成员数为 232 - 1 (4294967295, 每个集合可存储40多亿个成员)。
127.0.0.1:6379> zadd Redis:Study:ZSet1 1 redis
(integer) 1
127.0.0.1:6379> zadd Redis:Study:ZSet1 2 mysql
(integer) 1
127.0.0.1:6379> zadd Redis:Study:ZSet1 3 elasticsearch
(integer) 1
127.0.0.1:6379> zadd Redis:Study:ZSet1 3 elasticsearch
(integer) 0
127.0.0.1:6379> zrange Redis:Study:ZSet1 0 2 withscores
1) "redis"
2) "1"
3) "mysql"
4) "2"
5) "elasticsearch"
6) "3"
127.0.0.1:6379> zrange Redis:Study:ZSet1 0 2
1) "redis"
2) "mysql"
3) "elasticsearch"
127.0.0.1:6379> zcard Redis:Study:ZSet1
(integer) 3
127.0.0.1:6379> zincrby Redis:Study:ZSet1 10 mysql
"12"
127.0.0.1:6379> zrank Redis:Study:ZSet1 mysql
(integer) 2
127.0.0.1:6379> zrem Redis:Study:ZSet1 mysql
(integer) 1
127.0.0.1:6379> zrange Redis:Study:ZSet1 0 10 withscores
1) "redis"
2) "1"
3) "elasticsearch"
4) "3"
127.0.0.1:6379> zrevrange Redis:Study:ZSet1 0 10
1) "elasticsearch"
2) "redis"
127.0.0.1:6379> zscore Redis:Study:ZSet1 redis
"1"
127.0.0.1:6379> zscore Redis:Study:ZSet1 elasticsearch
"3"
1 ZADD key score1 member1 [score2 member2]
向有序集合添加一个或多个成员,或者更新已存在成员的分数
2 ZCARD key
获取有序集合的成员数
3 ZCOUNT key min max
计算在有序集合中指定区间分数的成员数
4 ZINCRBY key increment member
有序集合中对指定成员的分数加上增量 increment
5 ZINTERSTORE destination numkeys key [key …]
计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中
6 ZLEXCOUNT key min max
在有序集合中计算指定字典区间内成员数量
7 ZRANGE key start stop [WITHSCORES]
通过索引区间返回有序集合指定区间内的成员
8 ZRANGEBYLEX key min max [LIMIT offset count]
通过字典区间返回有序集合的成员
9 ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT]
通过分数返回有序集合指定区间内的成员
10 ZRANK key member
返回有序集合中指定成员的索引
11 ZREM key member [member …]
移除有序集合中的一个或多个成员
12 ZREMRANGEBYLEX key min max
移除有序集合中给定的字典区间的所有成员
13 ZREMRANGEBYRANK key start stop
移除有序集合中给定的排名区间的所有成员
14 ZREMRANGEBYSCORE key min max
移除有序集合中给定的分数区间的所有成员
15 ZREVRANGE key start stop [WITHSCORES]
返回有序集中指定区间内的成员,通过索引,分数从高到低
16 ZREVRANGEBYSCORE key max min [WITHSCORES]
返回有序集中指定分数区间内的成员,分数从高到低排序
17 ZREVRANK key member
返回有序集合中指定成员的排名,有序集成员按分数值递减(从大到小)排序
18 ZSCORE key member
返回有序集中,成员的分数值
19 ZUNIONSTORE destination numkeys key [key …]
计算给定的一个或多个有序集的并集,并存储在新的 key 中
20 ZSCAN key cursor [MATCH pattern] [COUNT count]
迭代有序集合中的元素(包括元素成员和元素分值)
//sorted set集合API使用
@Test
public void sortSetRedisTest() throws Exception{
final String key1 = "Redis:Study:SortedSet";
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
zSetOperations.add(key1,"java",1);
zSetOperations.add(key1,"vue",2);
zSetOperations.add(key1,"linux",3);
zSetOperations.add(key1,"大数据",4);
Long size = zSetOperations.size(key1);
System.out.println("获取zset列表"+zSetOperations.range(key1, 0,size));
System.out.println("获取zset倒序列表"+zSetOperations.reverseRange(key1, 0,size));
System.out.println("获取zset元素分值"+zSetOperations.score(key1, "大数据"));
System.out.println("获取zset元素排名"+zSetOperations.rank(key1, "大数据"));
System.out.println("获取zset元素倒序排名"+zSetOperations.reverseRank(key1, "大数据"));
System.out.println("将Zset指定元素增加分数"+zSetOperations.incrementScore(key1,"java",4));
Set<ZSetOperations.TypedTuple> set = zSetOperations.rangeWithScores(key1, 0, size);
set.forEach(o -> {
System.out.println("set带分数的列表展示"+o.getValue()+": "+o.getScore());
});
System.out.println("删除zset集合中的元素"+zSetOperations.remove(key1));
}
- Redis 哈希(Hash)
Redis hash 是一个 string 类型的 field(字段) 和 value(值) 的映射表,hash 特别适合用于存储对象。
Redis 中每个 hash 可以存储 232 - 1 键值对(40多亿)。
类似与这种数据结构:Map<String,Map> 或者 Map<String,对象>
127.0.0.1:6379> hset Redis:Study:hset s10010 a
127.0.0.1:6379> hset Redis:Study:hset s10010 a
(integer) 1
127.0.0.1:6379> hset Redis:Study:hset s10011 b
(integer) 1
127.0.0.1:6379> hset Redis:Study:hset s10012 c
(integer) 1
127.0.0.1:6379> hmget Redis:Study:hset s10010
1) "a"
127.0.0.1:6379> hmget Redis:Study:hset s10010 s10011 s10012
1) "a"
2) "b"
3) "c"
127.0.0.1:6379> hget Redis:Study:hset s10011
"b"
127.0.0.1:6379> hgetall Redis:Study:hset
1) "s10010"
2) "a"
3) "s10011"
4) "b"
5) "s10012"
6) "c"
127.0.0.1:6379> hdel Redis:Study:hset s10010
(integer) 1
127.0.0.1:6379> hgetall Redis:Study:hset
1) "s10011"
2) "b"
3) "s10012"
4) "c"
1 HDEL key field1 [field2]
删除一个或多个哈希表字段
2 HEXISTS key field
查看哈希表 key 中,指定的字段是否存在。
3 HGET key field
获取存储在哈希表中指定字段的值。
4 HGETALL key
获取在哈希表中指定 key 的所有字段和值
5 HINCRBY key field increment
为哈希表 key 中的指定字段的整数值加上增量 increment 。
6 HINCRBYFLOAT key field increment
为哈希表 key 中的指定字段的浮点数值加上增量 increment 。
7 HKEYS key
获取所有哈希表中的字段
8 HLEN key
获取哈希表中字段的数量
9 HMGET key field1 [field2]
获取所有给定字段的值
10 HMSET key field1 value1 [field2 value2 ]
同时将多个 field-value (域-值)对设置到哈希表 key 中。
11 HSET key field value
将哈希表 key 中的字段 field 的值设为 value 。
12 HSETNX key field value
只有在字段 field 不存在时,设置哈希表字段的值。
13 HVALS key
获取哈希表中所有值。
14 HSCAN key cursor [MATCH pattern] [COUNT count]
迭代哈希表中的键值对。
//hash集合API使用
@Test
public void hashRedisTest() throws Exception{
final String key1 = "Redis:Study:hash";
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.put(key1,"s10010","a");
Map<String,String> dataMap = Maps.newHashMap();
dataMap.put("s10011","b");
dataMap.put("s10012","c");
dataMap.put("s10013","d");
hashOperations.putAll(key1,dataMap);
System.out.println("获取hash数据::"+hashOperations.entries(key1));
System.out.println("判断元素是否存在::"+hashOperations.hasKey(key1,"b"));
System.out.println("判断不存在则存入某个元素::"+hashOperations.putIfAbsent(key1,"s10014","e"));
System.out.println("判断不存在则存入某个元素::"+hashOperations.putIfAbsent(key1,"s10014","e"));
System.out.println("删除hash中某个元素::"+hashOperations.delete(key1,"s10011","s10012"));
System.out.println("获取hash长度::"+hashOperations.size(key1));
}
对于系统中使用数据字典,可以使用hash数据结构进行实时触发存储