springboot整合 redisTemplate工具类 (含完整的单元测试+简单集成) 您所在的位置:网站首页 java单元测试类 springboot整合 redisTemplate工具类 (含完整的单元测试+简单集成)

springboot整合 redisTemplate工具类 (含完整的单元测试+简单集成)

2024-06-26 17:32| 来源: 网络整理| 查看: 265

目录

sprongboot集成redisTemplate

1.增加maven依赖

2.增加redis配置

3.写一个redis配置类

4.redis工具类大全(最全的工具类,没有之一)

5.单元测试

sprongboot集成redisTemplate 1.增加maven依赖 org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 2.增加redis配置 ##=====================redis ======== # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) 默认 8 spring.redis.lettuce.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 spring.redis.lettuce.pool.max-wait=-1 # 连接池中的最大空闲连接 默认 8 spring.redis.lettuce.pool.max-idle=8 # 连接池中的最小空闲连接 默认 0 spring.redis.lettuce.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=1000 3.写一个redis配置类

edisTemplate的自动配置

        其实现在就可以在代码中注入RedisTemplate,为啥可以直接注入呢?先看下源码吧。下图为 RedisAutoConfiguration类中的截图

@Configuration @ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class }) @EnableConfigurationProperties(RedisProperties.class) public class RedisAutoConfiguration { @Configuration protected static class RedisConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate redisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean @ConditionalOnMissingBean(StringRedisTemplate.class) public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } } }

通过源码可以看出,SpringBoot自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为形式的RedisTemplate。并且,这个RedisTemplate没有设置数据存在Redis时,key及value的序列化方式。

        看到这个@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate对象了,这个自动配置的RedisTemplate不会实例化。因此我们可以直接自己写个配置类,配置RedisTemplate。

既然自动配置不好用,就重新配置一个RedisTemplate package com.cisc.service.ecftrade.business.zdy; 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 com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; /** * redis配置类 * * @author 陈振东 * @date 2019年12月24日 */ @Configuration public class RedisConfig { @Bean @SuppressWarnings("all") public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate template = new RedisTemplate(); 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; } } 4.redis工具类大全(最全的工具类,没有之一) package com.cisc.service.ecftrade.business.zdy; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import lombok.extern.slf4j.Slf4j; /** * @author 陈振东 * 基于spring和redis的redisTemplate工具类 针对所有的hash 都是以h开头的方法 针对所有的Set 都是以s开头的方法 不含通用方法 针对所有的List 都是以l开头的方法 */ @Component @Slf4j public class RedisUtil { @Autowired private RedisTemplate redisTemplate; // =============================1-common============================ /** * 指定缓存失效时间 * * @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) { log.error(key, e); 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) { log.error(key, e); 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)); } } } // ============================2-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.error(key, 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) { log.error(key, e); return false; } } /** * 递增 适用场景: https://blog.csdn.net/y_y_y_k_k_k_k/article/details/79218254 高并发生成订单号,秒杀类的业务逻辑等。。 * * @param key 键 * @param by 要增加几(大于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 by 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================3-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 hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { log.error(key, e); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { log.error(key, e); 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) { log.error(key, e); 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) { log.error(key, e); 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); } // ============================4-set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { log.error(key, e); 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) { log.error(key, e); 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) { log.error(key, e); 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) { log.error(key, e); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { log.error(key, e); 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) { log.error(key, e); return 0; } } // ============================5-zset============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set zSGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { log.error(key, e); return null; } } /** * 根据value从一个set中查询,是否存在 * * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public boolean zSHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { log.error(key, e); return false; } } public Boolean zSSet(String key, Object value, double score) { try { return redisTemplate.opsForZSet().add(key, value, 2); } catch (Exception e) { log.error(key, e); return false; } } /** * 将set数据放入缓存 * * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */ public long zSSetAndTime(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) { log.error(key, e); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public long zSGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { log.error(key, e); return 0; } } /** * 移除值为value的 * * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public long zSetRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { log.error(key, e); return 0; } } // ===============================6-list================================= /** * 获取list缓存的内容 * * @param key 键 * @param start 开始 0 是第一个元素 * @param end 结束 -1代表所有值 * @return * @取出来的元素 总数 end-start+1 */ public List lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { log.error(key, e); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { log.error(key, e); return 0; } } /** * 通过索引 获取list中的值 * * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index 0) expire(key, time); return true; } catch (Exception e) { log.error(key, e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { log.error(key, e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { log.error(key, e); 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) { log.error(key, e); 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) { log.error(key, e); return 0; } } } 5.单元测试 package com.fanfan.utils.redis; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import lombok.Data; /** * 工具栏类进行单元测试 * * */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisUtilTest { @Autowired private RedisUtil redisUtil; @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } /** * 设置缓存过期时间 * * @Title testExpire * @author 于国帅 * @date 2019年3月7日 上午8:35:24 * @throws Exception * void */ @Test public void testExpire() throws Exception { redisUtil.set("aaaKey", "aaaValue"); redisUtil.expire("aaaKey", 100); Assert.assertEquals(redisUtil.get("aaaKey"), "aaaValue"); TimeUnit.SECONDS.sleep(100); Assert.assertNotEquals(redisUtil.get("aaaKey"), "aaaValue"); } @Test public void testGetExpire() throws Exception { redisUtil.set("aaaKey", "aaaValue"); redisUtil.expire("aaaKey", 100); // 设置了缓存就会及时的生效,所以缓存时间小于最初设置的时间 Assert.assertTrue(redisUtil.getExpire("aaaKey") < 100L); } @Test public void testHasKey() throws Exception { redisUtil.set("aaaKey", "aaaValue"); // 存在的 Assert.assertTrue(redisUtil.hasKey("aaaKey")); // 不存在的 Assert.assertFalse(redisUtil.hasKey("bbbKey")); } @Test public void testDel() throws Exception { redisUtil.set("aaaKey", "aaaValue"); // 存在的 Assert.assertTrue(redisUtil.hasKey("aaaKey")); redisUtil.del("aaaKey"); Assert.assertFalse(redisUtil.hasKey("bbbKey")); } @Test public void testGet() throws Exception { redisUtil.set("aaaKey", "aaaValue"); Assert.assertEquals(redisUtil.get("aaaKey"), "aaaValue"); } @Test public void testSetStringObject() throws Exception { Assert.assertTrue(redisUtil.set("aaaKey", "aaaValue")); } @Test public void testSetStringObjectLong() throws Exception { Assert.assertTrue(redisUtil.set("aaaKeyLong", 100L)); } @Test public void testSetObject() { // 测试对象 TestModel testModel = new TestModel(); testModel.setId(System.currentTimeMillis()); testModel.setName("测试"); redisUtil.set("testModel", testModel); TestModel testModel2 = (TestModel) redisUtil.get("testModel"); System.err.println(testModel2); System.err.println(testModel2.getName()); System.err.println(testModel2.getId()); } @Test @Ignore public void testIncr() throws Exception { String key = "testIncr"; redisUtil.incr(key, 1); redisUtil.expire(key, 10); // 缓存失效10s Assert.assertEquals(redisUtil.get(key), 1); } // 高并发下 递增 测试 @Test @Ignore public void testIncr2() throws Exception { // 模拟发送短信的并发 // 首先开启一个线程池,创建一个专门消费短信的线程 // 一次性放入多个线程实例 ,实例 都是2秒请求一次 ,而10s内的只能允许一条。 也就是说我测试100个线程,只能10s一条 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 6, 30, TimeUnit.SECONDS, new LinkedBlockingQueue(100)); Thread[] threads = new Thread[100]; for (int i = 0; i < 100; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } // String key = "testIncr2_17353620612"; long count = redisUtil.incr(key, 1); if (count == 1L) { redisUtil.expire(key, 10); // 缓存失效10s System.err.println("短信发送成功===" + new Date()); } else { System.err.println("访问次数快===" + new Date()); } } }); threadPoolExecutor.submit(threads[i]); } while (threadPoolExecutor.getQueue().isEmpty()) { threadPoolExecutor.shutdown(); System.err.println("所有线程执行完毕"); } System.in.read();// 加入该代码,让主线程不挂掉 // // 启动线程 // for (int i = 0; i < 100; i++) { // threads[i].start(); // } } long count = 0L; // 高并发下 错误的测试 递增 测试 @Test @Ignore public void testIncr3() throws Exception { // 模拟发送短信的并发 // 首先开启一个线程池,创建一个专门消费短信的线程 // 一次性放入多个线程实例 ,实例 都是2秒请求一次 ,而10s内的只能允许一条。 也就是说我测试100个线程,只能10s一条 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 6, 30, TimeUnit.SECONDS, new LinkedBlockingQueue(100)); Thread[] threads = new Thread[100]; for (int i = 0; i < 100; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { // try { // TimeUnit.SECONDS.sleep(2); // } catch (InterruptedException e) { // e.printStackTrace(); // } // pool-3-thread-1count===1 // pool-3-thread-5count===1 String key = "testIncr2_17353620612"; count = count + 1; System.err.println(Thread.currentThread().getName() + "count===" + count); // 督导的count // if (count == 1L) { // count = count - 1; // System.err.println("短信发送成功===" + new Date()); // } else { // System.err.println("访问次数快===" + new Date()); // } } }); threadPoolExecutor.submit(threads[i]); } while (threadPoolExecutor.getQueue().isEmpty()) { threadPoolExecutor.shutdown(); System.err.println("所有线程执行完毕"); } // System.in.read();// 加入该代码,让主线程不挂掉 } @Test @Ignore public void testDecr() throws Exception { String key = "Decr_17353620612"; redisUtil.decr(key, 1); redisUtil.expire(key, 10); // 缓存失效10s Assert.assertEquals(redisUtil.get(key), 1); } @Test public void testHget() throws Exception { redisUtil.hset("testHget", "testHget", "testHget"); Assert.assertEquals("testHget", redisUtil.hget("testHget", "testHget")); } @Test public void testHmget() throws Exception { redisUtil.hset("testHmget", "testHmget1", "testHmget1"); redisUtil.hset("testHmget", "testHmget2", "testHmget2"); Map map = redisUtil.hmget("testHmget"); if (MapUtils.isNotEmpty(map)) { for (Entry e : map.entrySet()) { System.err.println(e.getKey() + "===" + e.getValue()); } } } @Test public void testHsetStringStringObject() throws Exception { redisUtil.hset("map", "testHsetStringStringObject", "testHsetStringStringObject"); } // 测试放在hash 里面的对象 @Test public void testHsetObject() { // 测试对象 TestModel testModel = new TestModel(); testModel.setId(System.currentTimeMillis()); testModel.setName("测试"); redisUtil.hset("hash", "testModel", testModel); TestModel testModel2 = (TestModel) redisUtil.hget("hash", "testModel"); System.err.println(testModel2); System.err.println(testModel2.getName()); System.err.println(testModel2.getId()); } // 太奇妙了 放进去Long 取出来会根据大小变为相应的数据类型 @Test public void testHsetStringStringObjectLong() throws Exception { redisUtil.hset("testHsetStringStringObjectLong", "int", 100); // java.lang.Integer 读取来是inter System.err.println(redisUtil.hget("testHsetStringStringObjectLong", "int").getClass().getTypeName()); // Assert.assertEquals(redisUtil.hget("map", "testHsetStringStringObject"), 100L); redisUtil.hset("testHsetStringStringObjectLong", "long", System.currentTimeMillis()); // java.lang.Integer 读取来是inter System.err.println(redisUtil.hget("testHsetStringStringObjectLong", "long").getClass().getTypeName()); } @Test public void testHdel() throws Exception { redisUtil.hset("testHdel", "int", 100); Assert.assertEquals(redisUtil.hget("testHdel", "int"), 100); redisUtil.hdel("testHdel", "int"); Assert.assertEquals(redisUtil.hget("testHdel", "int"), null); } @Test public void testHHasKey() throws Exception { redisUtil.hset("testHHasKey", "int", 100); Assert.assertTrue(redisUtil.hHasKey("testHHasKey", "int")); } @Test public void testHincr() throws Exception { System.err.println(redisUtil.hincr("testHincr", "testHincr", 1)); } @Test public void testHdecr() throws Exception { System.err.println(redisUtil.hincr("testHincr", "testHincr", 1)); } @Test public void testSGet() throws Exception { redisUtil.sSet("testSGet", "testSGet1"); redisUtil.sSet("testSGet", "testSGet2"); System.err.println(StringUtils.join(redisUtil.sGet("testSGet"), ",")); } @Test public void testSHasKey() throws Exception { redisUtil.sSet("testSHasKey", "testSHasKey"); Assert.assertTrue(redisUtil.sHasKey("testSHasKey", "testSHasKey")); } @Test public void testSSet() throws Exception { redisUtil.sSet("testSSet", "testSSet"); } @Test public void testSSetAndTime() throws Exception { redisUtil.sSetAndTime("testSSetAndTime", 20, "testSSetAndTime1"); redisUtil.sSetAndTime("testSSetAndTime", 5, "testSSetAndTime2"); System.err.println(StringUtils.join(redisUtil.sGet("testSSetAndTime"), ",")); TimeUnit.SECONDS.sleep(5); System.err.println(StringUtils.join(redisUtil.sGet("testSSetAndTime"), ",")); TimeUnit.SECONDS.sleep(20); System.err.println(StringUtils.join(redisUtil.sGet("testSSetAndTime"), ",")); } @Test public void testSGetSetSize() throws Exception { redisUtil.sSetAndTime("testSGetSetSize", 20, "testSGetSetSize1"); redisUtil.sSetAndTime("testSGetSetSize", 5, "testSGetSetSize"); Assert.assertEquals(redisUtil.sGetSetSize("testSGetSetSize"), 2); } @Test public void testSetRemove() throws Exception { redisUtil.sSetAndTime("testSetRemove", 20, "testSetRemove1"); redisUtil.sSetAndTime("testSetRemove", 5, "testSetRemove"); Assert.assertEquals(redisUtil.sGetSetSize("testSetRemove"), 2); redisUtil.setRemove("testSetRemove", "testSetRemove"); Assert.assertEquals(redisUtil.sGetSetSize("testSetRemove"), 1); } @Test public void testLGet() throws Exception { redisUtil.lSet("testLGet", "testLGet0", 10); // 10秒过期 redisUtil.lSet("testLGet", "testLGet1", 10); // 查询三个元素 2-0+1 List list = redisUtil.lGet("testLGet", 0, 2); System.err.println("list===" + list); // 查询两个 List list2 = redisUtil.lGet("testLGet", 0, 1); System.err.println("list2===" + list2); // 查询全部 List list3 = redisUtil.lGet("testLGet", 0, -1); System.err.println("list3===" + list3); } @Test public void testLGetListSize() throws Exception { // 看看重复元素会怎么处理 long size = 0; redisUtil.lSet("testLGetListSize", "testLGetListSize0", 10); // 10秒过期 size = redisUtil.lGetListSize("testLGetListSize"); System.err.println(size); redisUtil.lSet("testLGetListSize", "testLGetListSize0", 10); size = redisUtil.lGetListSize("testLGetListSize"); System.err.println(size); } // @Test public void testLGetIndex() throws Exception { redisUtil.lSet("testLGetIndex", "testLGetIndex0", 10); // 10秒过期 redisUtil.lSet("testLGetIndex", "testLGetIndex1", 10); Object obj = redisUtil.lGetIndex("testLGetIndex", 0); Assert.assertEquals(obj, "testLGetIndex0"); } @Test public void testLSetStringObject() throws Exception { redisUtil.lSet("testLSetStringObject", "testLSetStringObject0"); redisUtil.lSet("testLSetStringObject", "testLSetStringObject1"); redisUtil.lSet("testLSetStringObject", "testLSetStringObject2"); } @Test public void testLSetStringObjectLong() throws Exception { } @Test public void testLUpdateIndex() throws Exception { redisUtil.lSet("testLUpdateIndex", "testLUpdateIndex0"); redisUtil.lSet("testLUpdateIndex", "testLUpdateIndex1"); redisUtil.lSet("testLUpdateIndex", "testLUpdateIndex2"); Object obj = redisUtil.lUpdateIndex("testLUpdateIndex", 0, "更新的"); Assert.assertEquals("更新的", obj); } @Test public void testLRemove() throws Exception { redisUtil.lSet("testLRemove", "testLRemove0"); redisUtil.lSet("testLRemove", "testLRemove1"); redisUtil.lSet("testLRemove", "testLRemove2"); Object obj = redisUtil.lRemove("testLRemove", 1, "testLRemove2"); } } @Data class TestModel implements Serializable { /** * @Fields serialVersionUID : (用一句话描述这个变量表示什么) */ private static final long serialVersionUID = 1L; private Long id; private String name; }

参考 博客 SpringBoot整合Redis及Redis工具类撰写 https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html redis整合spring(redisTemplate工具类) https://blog.csdn.net/qq_34021712/article/details/75949706https://blog.csdn.net/mengxiangxingdong/article/details/88419976

 

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有