springboot中Redis的Lettuce客户端和jedis客户端
1、引入客户端依赖
<!--jedis客户端依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency> <!--默认使用lettuce客户端-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
2、RedisTemplate 自定义对象定义
@Configuration
public class BackupRedisConfig { //Redis数据库索引
@Value("${spring.redis.database}")
Integer database;
//Redis服务器地址
@Value("${spring.backup.redis.host}")
String host;
// Redis服务器连接端口
@Value("${spring.redis.port}")
Integer port;
//Redis服务器连接密码
@Value("${spring.backup.redis.password}")
String password; //连接池最大连接数(使用负值表示没有限制)
@Value("${spring.redis.lettuce.pool.max-active}")
Integer maxActive;
//连接池最大阻塞等待时间(使用负值表示没有限制)
@Value("${spring.backup.redis.lettuce.pool.max-wait}")
Long maxWait;
//连接池中的最大空闲连接
@Value("${spring.redis.lettuce.pool.max-idle}")
Integer maxIdle;
//连接池中的最小空闲连接
@Value("${spring.redis.lettuce.pool.min-idle}")
Integer minIdle;
// 连接超时时间(毫秒)
@Value("${spring.backup.redis.timeout}")
String timeout; @Bean("backupRedisTemplate")
public RedisTemplate backupRedisTemplate() {
//lettuce 客户端连接池配置
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxWaitMillis(maxWait);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
//lettuce 客户端配置
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setDatabase(database);
config.setHostName(host);
config.setPort(port);
config.setPassword(password); // lettuce创建工厂
// LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build();
// LettuceConnectionFactory factory = new LettuceConnectionFactory(config, clientConfiguration);
// factory.afterPropertiesSet(); //jedis连接池配置
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWait);
jedisPoolConfig.setMaxTotal(maxActive); //创建jedis工厂
JedisConnectionFactory factory = new JedisConnectionFactory(config);
factory.setPoolConfig(jedisPoolConfig); //构建reids客户端,只能指定其中1个工厂
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer<>(Object.class));
redisTemplate.afterPropertiesSet();
return redisTemplate;
} }
3、RedisTemplate 默认链接对象,指定reids序列化方式,自定义缓存注解读写机制@Cacheable
a、实现RedisSerializer接口
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
// 解决fastJson autoType is not support错误
static {
ParserConfig.getGlobalInstance().addAccept("com.qingclass.yiban");
}
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Nullable
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Nullable
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
}
b、指定reids序列化方式,自定义缓存注解读写机制@Cacheable
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { /**
* 设置reids 链接序列化
* @param factory
* @return
*/
@Bean
public RedisTemplate redisTemplate(LettuceConnectionFactory factory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(getJsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
} /**
* 指定缓存管理器,读写机制
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(LettuceConnectionFactory factory) {
// 默认过期时间1小时
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().disableKeyPrefix()
.entryTtl(Duration.ofHours(CacheTtl.ONE_HOUR.getTime()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJsonRedisSerializer()));
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
.cacheDefaults(redisCacheConfiguration)
.withInitialCacheConfigurations(getRedisCacheConfigurationMap())
.build();
} private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(CacheTtl.values().length);
for (CacheTtl cacheTtl : CacheTtl.values()) {
redisCacheConfigurationMap.put(cacheTtl.getValue(), this.getRedisCacheConfigurationWithTtl(cacheTtl.getTime()));
}
return redisCacheConfigurationMap;
} private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer hours) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().disableKeyPrefix()
.entryTtl(Duration.ofHours(hours))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJsonRedisSerializer()));
return redisCacheConfiguration;
} private FastJsonRedisSerializer getJsonRedisSerializer() {
return new FastJsonRedisSerializer<>(Object.class);
} }
* spring boot在1.x.x的版本时默认使用的jedis客户端,
* 现在是2.x.x版本默认使用的lettuce客户端
* 详情链接 https://www.cnblogs.com/taiyonghai/p/9454764.html
springboot中Redis的Lettuce客户端和jedis客户端的更多相关文章
- SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍
今天给大家介绍一下SpringBoot中Redis的set.map.list.value等基本操作的具体使用方法 上一节中给大家介绍了如何在SpringBoot中搭建Redis缓存数据库,这一节就针对 ...
- SpringBoot中Redis的使用
转载:http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html Spring Boot 对常用的数据库支持外,对 No ...
- Redis服务器搭建/配置/及Jedis客户端的使用方法
摘要 Redis服务器搭建.常用参数含意说明.主从配置.以及使用Jedis客户端来操作Redis Redis服务器搭建 安装 在命令行执行下面的命令: $ wget http://download.r ...
- springboot中redis取缓存类型转换异常
异常如下: [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested ...
- SpringBoot中redis的使用介绍
REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...
- ③SpringBoot中Redis的使用
本文基于前面的springBoot系列文章进行学习,主要介绍redis的使用. SpringBoot对常用的数据库支持外,对NoSQL 数据库也进行了封装自动化. redis介绍 Redis是目前业界 ...
- springboot中redis的缓存穿透问题
什么是缓存穿透问题?? 我们使用redis是为了减少数据库的压力,让尽量多的请求去承压能力比较大的redis,而不是数据库.但是高并发条件下,可能会在redis还没有缓存的时候,大量的请求同时进入,导 ...
- springBoot 中redis 注解缓存的使用
1,首先在启动类上加上 @EnableCaching 这个注解 在查询类的controller,或service ,dao 中方法上加 @Cacheable 更新或修改方法上加 @CachePut 注 ...
- redis学习(七)jedis客户端
1.下载jedis的jar包 http://repo1.maven.org/maven2/redis/clients/jedis/2.8.1/ 2.启动redis后台 3.测试联通 package c ...
随机推荐
- C 神奇项链
时间限制 : - MS 空间限制 : - KB 评测说明 : 1s,64m 问题描述 母亲节就要到了,小 H 准备送给她一个特殊的项链.这个项链可以看作一个用小写字母组成的字符串,每个小写字母表 ...
- Golang入门(1):安装与配置环境变量的意义
摘要 在几年前学习Java的时候,环境的配置就会劝退一部分的初学者.而对于Golang来说,也需要从环境的配置开始学起.这一篇文章将从如何安装Golang开始讲起,随后将会提到Golang中的环境变量 ...
- Ubuntu16.04安装Vmware Tools
开启虚拟机 安装VMware Tools 在虚拟机名称上,右键>>安装VMware Tools 此时,Ubuntu会提示已经插入光盘,并弹出文件管理页面. 此时我们打开终端查看分区挂载情况 ...
- 关于wget下载jdk问题解决
问题: 直接从jdk官网下载会出现: 正在解析主机 login.oracle.com (login.oracle.com)... 156.151.58.18正在连接 login.oracle.com ...
- mongodb 指令
db.xxx.stats() 查看表的大小 db.xxx.remove({'endtime':{'$lte':ISODate('2018-10-01')}}) 删除小于等于固定时间的数据. db.us ...
- 深入理解== 和 equals 的本质区别
简介 初学者常常被"= =“和‘equals ’所折磨,为什么,因为他们的大概意思相同,都是比较两个对象是否相等,而又不搞不清他们的具体比较两个对象相等的原理是什么,所以经常搞混淆,接下来我 ...
- GitHub+PicGo构建免费图床及其高效使用
搭建免费图床全过程! 一.搭建缘由 一开始搭建博客,避免不了要用许多图片,最初使用七牛云来做博客图床,但是后来发现,七牛云只有30天的临时域名,hhhhhhh,果然啊,天下就没有免费的好事啊~后来就发 ...
- 利用numpy实现多维数组操作图片
1.上次介绍了一点点numpy的操作,今天我们来介绍它如何用多维数组操作图片,这之前我们要了解一下色彩是由blue ,green ,red 三种颜色混合而成,0:表示黑色 ,127:灰色 ,255:白 ...
- Complete the Sequence HDU - 1121
题目大意: 输入两个数n和m,n表示有n个数,这n个数是一个多项式的前n项,让输出这个序列的n+1,n+2,..n+m项. 题解:差分规律,一直差分,直到全为0或者只剩下一个数.然后再递推回去. 给出 ...
- CodeForces - 913C (贪心)
点完菜,他们发现好像觉得少了点什么? 想想马上就要回老家了某不愿透露姓名的林姓学长再次却陷入了沉思......... 他默默的去前台打算点几瓶二锅头. 他发现菜单上有n 种不同毫升的酒. 第 i 种有 ...