springboot2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了,倍爽!

Easter79
• 阅读 495

springboot2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了,倍爽!

Redis介绍及Mencached对比

Redis全称是远程字典服务,是一个Key-Value的存储系统,相比于很早之前一直使用的mencached,不单单提供了更多的类型支持。

数据类型上:mencached只支持简单的key-value存储,不支持持久化,不支持复制,不支持枚举,但是redis在数据结构上支持list、set、sorted set、hash,同时提供持久化与复制的功能。

内存机制上:mencached是进行全内存存储,就是所有的数据一直在内存中,但是redis并不是,它在进行内存存储的时候,根据swappability = age*log(size_in_memory)进行计算,计算出哪些值超过阈值,从而确定哪些值需要存储到磁盘,然后清除掉内存中的值。所以很多时候,Redis的存储是可以超过机器内存的值。

性能上:并不是说Redis性能一定比mencached更好,这里有个区间,在100k以上的数据中,mencached的性能高于Redis。

高可用上:mencached是全内存的缓存机制的,并不支持集群拓展,需要自己在客户端通过一致性哈希来实现,不过现在很少人这么做了,现在一般都是采用Redis Cluster来实现。

springboot2.2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了

Jedis与Lettuce对比

这两个都是用于提供连接Redis的客户端。

Jedis是直接连接Redis,非线程安全,在性能上,每个线程都去拿自己的 Jedis 实例,当连接数量增多时,资源消耗阶梯式增大,连接成本就较高了。

Lettuce的连接是基于Netty的,Netty 是一个多线程、事件驱动的 I/O 框架。连接实例可以在多个线程间共享,当多线程使用同一连接实例时,是线程安全的。

springboot2.2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了

引入包

<!-- redis核心包 -->   <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis</artifactId>   </dependency>   <!-- 需要引入redis依赖包commons-pool -->   <dependency>    <groupId>org.apache.commons</groupId>    <artifactId>commons-pool2</artifactId>   </dependency>

编写配置类

/**  * All rights Reserved, Designed By 溪云阁  * Copyright:    Copyright(C) 2016-2020  */ package com.module.boots.redis; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer; /**  * Redis配置  * @author:溪云阁  * @date:2020年5月24日  */ @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig {     /**      * 采用FastJson进行key/value序列化      * @author 溪云阁      * @param redisConnectionFactory      * @return RedisTemplate<String,Object>      */     @Bean     public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {         final RedisTemplate<String, Object> template = new RedisTemplate<>();         // 使用fastjson序列化         final FastJsonRedisSerializer<?> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);         // value值的序列化采用fastJsonRedisSerializer         template.setValueSerializer(fastJsonRedisSerializer);         template.setHashValueSerializer(fastJsonRedisSerializer);         // key的序列化采用StringRedisSerializer         template.setKeySerializer(new StringRedisSerializer());         template.setHashKeySerializer(new StringRedisSerializer());         // 开启事务         template.setEnableTransactionSupport(true);         template.setConnectionFactory(redisConnectionFactory);         return template;     } }

编写工具类

package com.module.boots.redis; 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;/**  * redis工具类  * @author:溪云阁  * @date:2020年5月24日  */ @Componentpublic class RedisUtils {     @Autowired     private RedisTemplate<String, Object> redisTemplate;     /**     * 指定缓存失效时间     * @param key 键     * @param time 时间(秒)     * @return     */     public boolean expire(String key, long time) {         if (time > 0) {             redisTemplate.expire(key, time, TimeUnit.SECONDS);             return true;         } else {             throw new RuntimeException("超时时间小于0");         }     }     /**      * 根据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) {         return redisTemplate.hasKey(key);     }     /**      * 删除缓存     * @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) {         redisTemplate.opsForValue().set(key, value);         return true;     }     /**      * 普通缓存放入并设置时间     * @param key 键     * @param value 值     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期      * @return true成功 false 失败      */     public boolean set(String key, Object value, long time) {         if (time > 0) {             redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);         } else {             this.set(key, value);         }         return true;     }     /**      * 递增     * @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);     }     // ================================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) {         redisTemplate.opsForHash().putAll(key, map);         return true;     }     /**      * HashSet 并设置时间     * @param key 键     * @param map 对应多个键值     * @param time 时间(秒)     * @return true成功 false失败      */     public boolean hmset(String key, Map<String, Object> map, long time) {         redisTemplate.opsForHash().putAll(key, map);         if (time > 0) {             expire(key, time);         }         return true;     }     /**      * 向一张hash表中放入数据,如果不存在将创建     * @param key 键     * @param item 项     * @param value 值     * @return true 成功 false失败      */     public boolean hset(String key, String item, Object value) {         redisTemplate.opsForHash().put(key, item, value);         return true;     }     /**      * 向一张hash表中放入数据,如果不存在将创建     * @param key 键     * @param item 项     * @param value 值     * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间      * @return true 成功 false失败      */     public boolean hset(String key, String item, Object value, long time) {         redisTemplate.opsForHash().put(key, item, value);         if (time > 0) {             expire(key, time);         }         return true;     }     /**      * 删除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);     }     // ============================set=============================     /**      * 根据key获取Set中的所有值     * @param key 键     * @return     */     public Set<Object> sGet(String key) {         return redisTemplate.opsForSet().members(key);     }     /**      * 根据value从一个set中查询,是否存在     * @param key 键     * @param value 值     * @return true 存在 false不存在      */     public boolean sHasKey(String key, Object value) {         return redisTemplate.opsForSet().isMember(key, value);     }     /**      * 将数据放入set缓存     * @param key 键     * @param values 值 可以是多个     * @return 成功个数     */     public long sSet(String key, Object... values) {         return redisTemplate.opsForSet().add(key, values);     }     /**      * 将set数据放入缓存     * @param key 键     * @param time 时间(秒)     * @param values 值 可以是多个     * @return 成功个数     */     public long sSetAndTime(String key, long time, Object... values) {         final Long count = redisTemplate.opsForSet().add(key, values);         if (time > 0)             expire(key, time);         return count;     }     /**      * 获取set缓存的长度     * @param key 键     * @return     */     public long sGetSetSize(String key) {         return redisTemplate.opsForSet().size(key);     }     /**      * 移除值为value的     * @param key 键     * @param values 值 可以是多个     * @return 移除的个数     */     public long setRemove(String key, Object... values) {         final Long count = redisTemplate.opsForSet().remove(key, values);         return count;     }     // ===============================list=================================     /**      * 获取list缓存的内容     * @param key 键     * @param start 开始     * @param end 结束  0 到 -1代表所有值      * @return     */     public List<Object> lGet(String key, long start, long end) {         return redisTemplate.opsForList().range(key, start, end);     }     /**      * 获取list缓存的长度     * @param key 键     * @return     */     public long lGetListSize(String key) {         return redisTemplate.opsForList().size(key);     }     /**      * 通过索引 获取list中的值     * @param key 键     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推      * @return     */     public Object lGetIndex(String key, long index) {         return redisTemplate.opsForList().index(key, index);     }     /**      * 将list放入缓存     * @param key 键     * @param value 值     * @param time 时间(秒)     * @return     */     public boolean lSet(String key, Object value) {         redisTemplate.opsForList().rightPush(key, value);         return true;     }     /**      * 将list放入缓存     * @param key 键     * @param value 值     * @param time 时间(秒)     * @return     */     public boolean lSet(String key, Object value, long time) {         redisTemplate.opsForList().rightPush(key, value);         if (time > 0) {             expire(key, time);         }         return true;     }     /**      * 将list放入缓存     * @param key 键     * @param value 值     * @param time 时间(秒)     * @return     */     public boolean lSet(String key, List<Object> value) {         redisTemplate.opsForList().rightPushAll(key, value);         return true;     }     /**      * 将list放入缓存     * @param key 键     * @param value 值     * @param time 时间(秒)     * @return     */     public boolean lSet(String key, List<Object> value, long time) {         redisTemplate.opsForList().rightPushAll(key, value);         if (time > 0) {             expire(key, time);         }         return true;     }     /**      * 根据索引修改list中的某条数据     * @param key 键     * @param index 索引     * @param value 值     * @return     */     public boolean lUpdateIndex(String key, long index, Object value) {         redisTemplate.opsForList().set(key, index, value);         return true;     } }

编写配置文件

#redis地址 spring.redis.host: 127.0.0.1 #redis端口号 spring.redis.port: 6379 #redis密码,如果没有不用填写,建议还是得有 spring.redis.password: 123456 #最大活跃连接数,默认是8spring.redis.lettuce.pool.maxActive: 100 #最大空闲连接数 ,默认是8spring.redis.lettuce.pool.maxIdle: 100 #最小空闲连接数 ,默认是0spring.redis.lettuce.pool.minIdle: 0

编写测试类

/**  * All rights Reserved, Designed By 溪云阁  * Copyright:    Copyright(C) 2016-2020  */ package com.boots.redis; import org.junit.Before; 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 com.module.boots.redis.RedisUtils; /**  * redis单元测试  * @author:溪云阁  * @date:2020年5月24日  */ @RunWith(SpringRunner.class) @SpringBootTest public class BootsRedisApplicationTest {     @Autowired     private RedisUtils redisUtils;    /**      * 执行前插入值      * @author 溪云阁      * @throws Exception void      */     @Before     public void setUp() throws Exception {        redisUtils.set("aaa", "121212");         System.out.println("插入值成功");     }    /**      * 执行获取值      * @author 溪云阁      * @throws Exception void      */     @Test     public void test() throws Exception {        System.out.println(redisUtils.get("aaa"));     }}

测试结果

springboot2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了,倍爽! springboot2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了,倍爽!

========

好文章,我在看

===============

本文分享自微信公众号 - 程序员闪充宝(cxyscb1024)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
5个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k