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 ...
随机推荐
- 字典树基础进阶全掌握(Trie树、01字典树、后缀自动机、AC自动机)
字典树 概述 字典树,又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种.典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计.它 ...
- WDK驱动开发点滴
老程序员做新方向,老树发新芽,作为菜鸟的我,写点心得,用以记录并与同行交流 1对一些概念的理解: KMDF与UMDF.两者的框架,及使用VS生成的初始代码基本相同,只有所包含的头文件不同,链接的系统库 ...
- 《Java基础复习》—规范与基础
参考书目<Java 编程思想>所以大家放心食用 一.注释规范以及API文档 1.注释 1.1三种注释方法 //注释内容 单行注释 /* 注释内容 */ 多行注释 /**注释内容*/ 文档注 ...
- Appium:We shut down because no new commands came in
在使用Appium自带的Inspector来查找元素定位时,一段时间(60s)不对其进行任何操作appium就会关闭Android应用,并打印出 info: [debug] We shut down ...
- CentOS 7 Docker安装
1. uname -a 查询机器信息,确保CPU为64位,且Linux内核在3.10版本以上 2. 更新yum包: yum update 3. 在 /etc/yum.repos.d下创建 docker ...
- 「给产品经理讲JVM」:垃圾收集算法
纠结的我,给我的JVM系列终于起了第三个名字,害,我真是太难了.从 JVM 到 每日五分钟,玩转 JVM 再到现在的给产品经理讲 JVM ,虽然内容为王,但是标题可以让更多的人看到我的文章,所以,历经 ...
- Linux强大屏幕截图方法,理论能截取任何图形界面,包括登录界面
众所周知,屏幕截图可以使用“Print Screen”按键,但是,此按键的响应是靠系统的后台服务实现的,Linux在某些场景下,是不响应此按键的. 这里介绍一种更强大的截图方法,它是靠转储X图形环境的 ...
- wireshark抓包实战(七),数据流追踪
方法一 选中一个包,然后右键选择 "追踪流" ==> "xx流" 方法二 选中某个数据包后,点击 "分析" ===> " ...
- Java第二天,类的概念,属性和方法的使用
上文中我们已近说到过了,Java是一种面向对象的编程语言,对象是用类来创建的,就比如世界上有无数个父亲,但是他们都有一个共同的属性--男人.也就是说某个父亲这个对象属于男人这个类.类是Java必不可少 ...
- JAVA集合框架之List和Set、泛型
一 List是有序可重复的集合 可以进行增删改查,直接看代码 package com.collection; import java.util.ArrayList; import java.util. ...