700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Redis学习篇3_事务及其监控(锁) Jedis SpringBoot整合Redis RedisTemplate的json序列化 RedisUtil工具类

Redis学习篇3_事务及其监控(锁) Jedis SpringBoot整合Redis RedisTemplate的json序列化 RedisUtil工具类

时间:2023-03-02 17:06:01

相关推荐

Redis学习篇3_事务及其监控(锁) Jedis SpringBoot整合Redis RedisTemplate的json序列化 RedisUtil工具类

目录

事务及其监控(锁)JedisSpringBoot整合RedisRedisTemplate 默认RedisTemplate来源关于中文序列化问题RedisUtil工具类

一、事务及其监控(锁)

1. 事务

说明

事务的本质:一组命令的集合,传统的关系型数据库事务有ACID特性。Redis一个事务中的所有命令都会被序列化,也就是开启事务之后的命令会被放到队列中,等到执行事务命令的时候,一次执行队列中全部命令,在事务的执行过程中,语句会按照循序执行。(一次性、顺序性、排他性)Redis单条命令是有原子性的,但是事务不保证原子性(事务中存在运行期异常的语句不能执行成功,但是其他的语句依旧执行)Redis事务没有隔离级别的概念,也就是不会出现脏读、幻读、不可重复读。

正常事务执行

开启事务 multi命令入队执行事务 exec

127.0.0.1:6379> multi # 1. 开启事务OK127.0.0.1:6379(TX)> set name xiaosi # 2. 命令入队QUEUED127.0.0.1:6379(TX)> get nameQUEUED127.0.0.1:6379(TX)> set age 20QUEUED127.0.0.1:6379(TX)> get ageQUEUED127.0.0.1:6379(TX)> set sex manQUEUED127.0.0.1:6379(TX)> exec # 3. 执行事务1) OK2) "xiaosi"3) OK4) "20"5) OK127.0.0.1:6379>

取消事务执行 discard

127.0.0.1:6379> multi # 1. 开启事务OK127.0.0.1:6379(TX)> 127.0.0.1:6379(TX)> set heigth 176QUEUED127.0.0.1:6379(TX)> discard # 2. 取消事务OK127.0.0.1:6379> get height # 3. 验证,获得为null证明取消事务(nil)127.0.0.1:6379>

注意

编译时异常(执行语句错误,编译出错),会报错但是事务不会停止,事务不被执行。运行时异常(类似1\0,语法错误),其他命令可以正常执行,没有原子性,会抛出异常

127.0.0.1:6379> multiOK127.0.0.1:6379(TX)> lset mylist 0 xiaosi 1 si 2 s # 1. 编译时异常,会报错,但是事务不停止(error) ERR wrong number of arguments for 'lset' command127.0.0.1:6379(TX)> lset mylist 0 xiaosi # 正确的语句入队列QUEUED127.0.0.1:6379(TX)> exec # 2. 事务执行失败(error) EXECABORT Transaction discarded because of previous errors.127.0.0.1:6379> lrange mylist 0 -1 # 3. 验证事务执行失败,为空证明事务没执行(empty array)127.0.0.1:6379> 127.0.0.1:6379> flushdbOK127.0.0.1:6379> keys *(empty array)127.0.0.1:6379> set k1 'xiaosi' # 1. 开始设置字符串,设置执行incr运行期报错异常OK127.0.0.1:6379> multiOK127.0.0.1:6379(TX)> incr k1 # 2. 运行期异常QUEUED127.0.0.1:6379(TX)> set k2 2 # 正常语句QUEUED127.0.0.1:6379(TX)> get k2QUEUED127.0.0.1:6379(TX)> set k3 3QUEUED127.0.0.1:6379(TX)> exec1) (error) ERR value is not an integer or out of range # 3. 运行期异常会报错,但是事务还是执行了2) OK # 正常执行的语句3) "2"4) OK127.0.0.1:6379>

2. 监控

说明

锁:常见的并发场景下,需要对事务处理字段数据加锁,常见的有 悲观锁:认为什么时候都会出现破坏ACID的情况,都会加锁乐观锁:认为什么时候都不会出现破坏ACID的情况,不会加锁,在更新数据的时候判断一下,在此期间是否有人修改过这个数据,比较version。使用watch xxx相当于redis的乐观锁。

执行场景

监控watch正常乐观锁执行情况

127.0.0.1:6379> flushdbOK127.0.0.1:6379> keys *(empty array)127.0.0.1:6379> set money 100OK127.0.0.1:6379> watch money # 监控OK127.0.0.1:6379> multiOK127.0.0.1:6379(TX)> decrby money 66QUEUED127.0.0.1:6379(TX)> incrby money 88QUEUED127.0.0.1:6379(TX)> exec1) (integer) 342) (integer) 122127.0.0.1:6379> get money"122"

监控watch 出错乐观锁执行情况

开启两个redis客户端模拟多线程,第一个线程开启事务还未执行执行的时候,第二个线程直接修改值,然后执行事务返回null,事务未执行。如需从新执行事务,需要unwatch xxx释放锁,在watch xxx加上乐观锁执行事务

# 客户端一、模拟开启事务的线程127.0.0.1:6379> watch moneyOK127.0.0.1:6379> multiOK127.0.0.1:6379(TX)> decrby money 2 # 为执行事务的时候,有线程直接修改了值QUEUED127.0.0.1:6379(TX)> exec(nil) # 事务执行失败127.0.0.1:6379> # 客户端二、模拟插队的修改值的线程127.0.0.1:6379> keys *1) "money"127.0.0.1:6379> get money"122"127.0.0.1:6379> incrby money 10000 # 在客户端一开启事务未执行的实时,修改值(integer) 10122127.0.0.1:6379> get money"10122"127.0.0.1:6379>

二、Jedis

概述

Jedis是Redis官方推荐的Java连接开发工具。要在Java开发中使用好Redis中间件,必须对Jedis熟悉才能写成漂亮的代码。通过导依赖后使用Jedis对象调用方法完成操作Redis.参考:/p/a1038eed6d44

使用步骤

导依赖

<!-- /artifact/redis.clients/jedis --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.6.1</version></dependency><!-- /artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency>

连接数据库、操作、断开连接

Jedis jedis = new Jedis("localhost", 6379); //指定Redis服务Host和portjedis.auth("xxxx"); //如果Redis服务连接需要密码,制定密码String value = jedis.get("key"); //访问Redis服务jedis.close(); //使用完关闭连接

常用API(基本操作指令对应的方法,参考:/fanbaodan/article/details/89047909)

三、SpringBoot整合Redis

说明

SpringBoot可以通过SpringData操作jpa、jdbc、mongoddb、redis等spring-data是和springboot齐名的项目在springboot 2.x之后,原来使用的Jedis被替换成了lettuce,因为 jedis采用的直连,多个线程操作的话会不安全,因此需要使用jedis 连接池。BIO模式lettuce采用netty,实例可以在多个线程中共享,不存在线程不安全的情况,可以减少线程数据,更像NIO模式

步骤

导依赖

<!-- /artifact/org.springframework.boot/spring-boot-starter-data-redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>2.5.2</version></dependency>

配置(properties文件对应一个配置类和自动装配类,从依赖中找到autoconfig的包,文件spring.factories文件找redis相关的RedisAutoConfiguration自动装配类,该类顶部注解绑定了RedisPropertiesl配置类,点进去查看字段即为配置的字段)

spring.redis.hostName: 192.168.174.128spring.redis.port: 6379spring.redis.password: xuan123456spring.redis.database: 2 #默认使用db0spring.redis.timeout: 0# 连接池技术推荐使用lettce的配置spring.redis.pool.max-active: 8spring.redis.pool.max-wait: -1spring.redis.pool.max-idle: 8spring.redis.pool.min-idle: 0

连接池推荐使用lettce的配置(RedisTemplate构造参数需要RedisConnectFactory接口,该接口实现实现JedisConnectFactoryLettceConnectionFactory,可以看到2.0版本后默认生效的是lettce的配置)

操作:注入RedisTemplate操作

基本操作,首先调用opsForXxx确定操作的数据结构,接着调用对应方法完成操作除了基本的增删改查,需要其他的操作就需要redisTemplate.getConnectionFactory().getConnection()获取connection对象调用对应方法完成操作。

Git仓库:/GitHubSi/study-redis_demo1

四、RedisTemplate

1.默认RedisTemplate来源

//// Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler)//package org.springframework.boot.autoconfigure.data.redis;import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;@Configuration(proxyBeanMethods = false)@ConditionalOnClass({RedisOperations.class})@EnableConfigurationProperties({RedisProperties.class})@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})public class RedisAutoConfiguration {public RedisAutoConfiguration() {}@Bean@ConditionalOnMissingBean(name = {"redisTemplate"})@ConditionalOnSingleCandidate(RedisConnectionFactory.class)public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean@ConditionalOnSingleCandidate(RedisConnectionFactory.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}}

默认:在redis自动装配类,发现默认的RedisTemplate,可以自己进行拓展。因为@ConditionOnMissingBean,因此可以自己拓展RedisTemplate

2.关于中文序列化问题
不序列化直接存储对象,会抛出异常,需要实现Serializable接口(默认JDK序列化),这样不在抛异常,但是redis-cli还是会中文乱码不序列化传递json对象字符串,会产生乱码,控制台输出没问题,但是redis-cli会乱码默认的序列化是JDK序列化,字符串会转意,因此需要自己编写RedisConfig和自定义RedisTemplate来自定义序列化方式

@Testvoid test2() throws JsonProcessingException {User user = new User("亚索",20);// 一般使用json传递数据String jsonUser = new ObjectMapper().writeValueAsString(user);// 现在传递的是json字符串redisTemplate.opsForValue().set("user",jsonUser);System.out.println(redisTemplate.opsForValue().get("user")); // {"name":"亚索","age":20}}# redis-cli乱码redis 127.0.0.1:6379> keys *1) "\xac\xed\x00\x05t\x00\x04name"2) "shiro:session:a4ea7686-d2e8-491c-bb10-efaa8cb480cc"3) "\xac\xed\x00\x05t\x00\x04user"redis 127.0.0.1:6379>

自定义RedisTemplate的json序列化格式

package henu.soft.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;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;@Configurationpublic class RedisConfig {// 自定义redisTemplate@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate();template.setConnectionFactory(redisConnectionFactory);// 进行序列化配置// 1. json序列化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);// 2. String序列化StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();// key采用String的方式序列化,value采用json格式template.setKeySerializer(stringRedisSerializer);template.setValueSerializer(jackson2JsonRedisSerializer);// hash的key也采用String的方式序列化,value采用json格式template.setHashKeySerializer(stringRedisSerializer);template.setHashValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}}

再次测试

@Testvoid test1(){redisTemplate.opsForValue().set("name","xiaosi");Object name = redisTemplate.opsForValue().get("name");System.out.println(name);}@Testvoid test2() throws JsonProcessingException {User user = new User("亚索",20);// 一般使用json传递数据String jsonUser = new ObjectMapper().writeValueAsString(user);redisTemplate.opsForValue().set("jsonUser",jsonUser);redisTemplate.opsForValue().set("User",user);System.out.println(redisTemplate.opsForValue().get("user"));}# redis-cliS不在乱码redis 127.0.0.1:6379> clearredis 127.0.0.1:6379> keys *1) "name"redis 127.0.0.1:6379> keys *1) "User"2) "jsonUser"3) "name"redis 127.0.0.1:6379>

3.RedisUtil工具类

package henu.soft.demo.utils;import org.assertj.core.util.Lists;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.connection.RedisStringCommands;import org.springframework.data.redis.connection.ReturnType;import org.springframework.data.redis.core.*;import org.springframework.data.redis.core.types.Expiration;import org.ponent;import org.springframework.util.CollectionUtils;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;import java.util.function.Consumer;/*** author:Johny***/@Component//@Slf4jpublic final class RedisUtil {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate StringRedisTemplate stringRedisTemplate;// =============================common============================/*** 尝试获取分布式锁** @param key* @param requestId* @param expire* @author: Johny* @Date: -06-04 17:21* @return: boolean*/public synchronized boolean lock(String key, String requestId, long expire) {return (Boolean) redisTemplate.execute((RedisCallback) connection -> {Boolean result = connection.set(key.getBytes(), requestId.getBytes(),Expiration.from(expire, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);return result;});}/*** 释放分布式锁** @param key* @param requestId* @author: Johny* @Date: -06-04 17:21* @return: boolean*/public synchronized boolean releaseLock(String key, String requestId) {return (Boolean) redisTemplate.execute((RedisCallback) connection -> {String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";Boolean result = connection.eval(script.getBytes(), ReturnType.BOOLEAN, 1, key.getBytes(),requestId.getBytes());return result;});}/*** 指定缓存失效时间** @param key 键* @param time 时间(秒)* @return*/public boolean expire(String key, long time) {try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据key 获取过期时间** @param key 键 不能为null* @return 时间(秒) 返回0代表为永久有效*/public long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}/*** 判断key是否存在** @param key 键* @return true 存在 false不存在*/public boolean hasKey(String key) {try {return redisTemplate.hasKey(key);} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除缓存** @param key 可以传一个值 或多个*/@SuppressWarnings("unchecked")public void del(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {redisTemplate.delete(key[0]);} else {redisTemplate.delete(CollectionUtils.arrayToList(key));}}}// ============================String=============================/*** 普通缓存获取** @param key 键* @return 值*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 普通缓存放入** @param key 键* @param value 值* @return true成功 false失败*/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {// log.warn("保存缓存异常", e);return false;}}/*** 普通缓存放入并设置时间** @param key 键* @param value 值* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 递增** @param key 键* @param delta 要增加几(大于0)* @return*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减** @param key 键* @param delta 要减少几(小于0)* @return*/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}// ================================Map=================================/*** HashGet** @param key 键 不能为null* @param item 项 不能为null* @return 值*/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/*** 获取hashKey对应的所有键值** @param key 键* @return 对应的多个键值*/public Map<Object, Object> hmget(String key) {return redisTemplate.opsForHash().entries(key);}/*** HashSet** @param key 键* @param map 对应多个键值* @return true 成功 false 失败*/public boolean hmset(String key, Map<String, Object> map) {try {redisTemplate.opsForHash().putAll(key, map);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** HashSet 并设置时间** @param key 键* @param map 对应多个键值* @param time 时间(秒)* @return true成功 false失败*/public boolean hmset(String key, Map<String, Object> map, long time) {try {redisTemplate.opsForHash().putAll(key, map);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key 键* @param item 项* @param value 值* @return true 成功 false失败*/public boolean hset(String key, String item, Object value) {try {redisTemplate.opsForHash().put(key, item, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key 键* @param item 项* @param value 值* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间* @return true 成功 false失败*/public boolean hset(String key, String item, Object value, long time) {try {redisTemplate.opsForHash().put(key, item, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除hash表中的值** @param key 键 不能为null* @param item 项 可以使多个 不能为null*/public void hdel(String key, Object... item) {redisTemplate.opsForHash().delete(key, item);}/*** 判断hash表中是否有该项的值** @param key 键 不能为null* @param item 项 不能为null* @return true 存在 false不存在*/public boolean hHasKey(String key, String item) {return redisTemplate.opsForHash().hasKey(key, item);}/*** hash递增 如果不存在,就会创建一个 并把新增后的值返回** @param key 键* @param item 项* @param by 要增加几(大于0)* @return*/public double hincr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, by);}/*** hash递减** @param key 键* @param item 项* @param by 要减少记(小于0)* @return*/public double hdecr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, -by);}// ============================zset=============================/*** 根据key获取ZSet中排名值** @param key* @param start* @param end* @author: Johny* @Date: -06-05 18:03* @return: java.util.Set<java.lang.Object>*/public Set<Object> zrange(String key, long start, long end) {try {return redisTemplate.opsForZSet().range(key, start, end);} catch (Exception e) {e.printStackTrace();return null;}}/*** 将一个或多个 member 元素及其 score 值加入到有序集 key 当中。** @param key* @author: Johny* @Date: -06-05 18:03* @return: java.util.Set<java.lang.Object>*/public boolean zAdd(String key, Object value, double score) {try {return redisTemplate.opsForZSet().add(key, value, score);} catch (Exception e) {e.printStackTrace();return false;}}// ============================set=============================/*** 根据key获取Set中的所有值** @param key 键* @return*/public Set<Object> sGet(String key) {try {return redisTemplate.opsForSet().members(key);} catch (Exception e) {e.printStackTrace();return null;}}/*** 根据value从一个set中查询,是否存在** @param key 键* @param value 值* @return true 存在 false不存在*/public boolean sHasKey(String key, Object value) {try {return redisTemplate.opsForSet().isMember(key, value);} catch (Exception e) {e.printStackTrace();return false;}}/*** 将数据放入set缓存** @param key 键* @param values 值 可以是多个* @return 成功个数*/public long sSet(String key, Object... values) {try {return redisTemplate.opsForSet().add(key, values);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 将set数据放入缓存** @param key 键* @param time 时间(秒)* @param values 值 可以是多个* @return 成功个数*/public long sSetAndTime(String key, long time, Object... values) {try {Long count = redisTemplate.opsForSet().add(key, values);if (time > 0) {expire(key, time);}return count;} catch (Exception e) {e.printStackTrace();return 0;}}/*** 获取set缓存的长度** @param key 键* @return*/public long sGetSetSize(String key) {try {return redisTemplate.opsForSet().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 移除值为value的** @param key 键* @param values 值 可以是多个* @return 移除的个数*/public long setRemove(String key, Object... values) {try {Long count = redisTemplate.opsForSet().remove(key, values);return count;} catch (Exception e) {e.printStackTrace();return 0;}}// ===============================list=================================/*** 获取list缓存的内容** @param key 键* @param start 开始* @param end 结束 0 到 -1代表所有值* @return*/public List<Object> lGet(String key, long start, long end) {try {return redisTemplate.opsForList().range(key, start, end);} catch (Exception e) {e.printStackTrace();return null;}}/*** 获取list缓存的长度** @param key 键* @return*/public long lGetListSize(String key) {try {return redisTemplate.opsForList().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 通过索引 获取list中的值** @param key 键* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推* @return*/public Object lGetIndex(String key, long index) {try {return redisTemplate.opsForList().index(key, index);} catch (Exception e) {e.printStackTrace();return null;}}/*** 将list放入缓存** @param key 键* @param value 值* @return*/public boolean lPush(String key, Object value) {try {redisTemplate.opsForList().leftPush(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key 键* @param value 值* @return*/public boolean rPush(String key, Object value) {try {redisTemplate.opsForList().rightPush(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key 键* @return*/public boolean trim(String key, long start, long end) {try {redisTemplate.opsForList().trim(key, start, end);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key 键* @param value 值* @param time 时间(秒)* @return*/public boolean rPush(String key, Object value, long time) {try {redisTemplate.opsForList().rightPush(key, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key 键* @param value 值* @return*/public boolean lSetList(String key, List<Object> value) {try {redisTemplate.opsForList().rightPushAll(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key 键* @param value 值* @param time 时间(秒)* @return*/public boolean lSet(String key, List<Object> value, long time) {try {redisTemplate.opsForList().rightPushAll(key, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据索引修改list中的某条数据** @param key 键* @param index 索引* @param value 值* @return*/public boolean lUpdateIndex(String key, long index, Object value) {try {redisTemplate.opsForList().set(key, index, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 移除N个值为value** @param key 键* @param count 移除多少个* @param value 值* @return 移除的个数*/public long lRemove(String key, long count, Object value) {try {Long remove = redisTemplate.opsForList().remove(key, count, value);return remove;} catch (Exception e) {e.printStackTrace();return 0;}}/*** scan 实现** @param pattern 表达式* @param consumer 对迭代到的key进行操作*/public void scan(String pattern, Consumer<byte[]> consumer) {this.stringRedisTemplate.execute((RedisConnection connection) -> {try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(Long.MAX_VALUE).match(pattern).build())) {cursor.forEachRemaining(consumer);return null;}});}/*** 获取符合条件的key** @param pattern 表达式* @return*/public List<String> keys(String pattern) {// 先解决bug,cluster模式不支持scanSet<String> keys = stringRedisTemplate.keys(pattern);if (!CollectionUtils.isEmpty(keys)) {// new ArrayList<String>(keys);return Lists.newArrayList(keys);}return new ArrayList<>();// List<String> keys = new ArrayList<>();// this.scan(pattern, item -> {// //符合条件的key// String key = new String(item, StandardCharsets.UTF_8);// keys.add(key);// });// return keys;}}

Git地址:/GitHubSi/study-redis_demo1

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。