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 ...
随机推荐
- CentOS 6.5 nginx+tomcat+ssl配置
本文档用于指导在CentOS 6.5下使用nginx反向代理tomcat,并在nginx端支持ssl. 安装nginx.参见CentOS 6 nginx安装. SSL证书申请.参见腾讯SSL证书申请和 ...
- JDBC获取连接抛出java.sql.SQLException: The server time zone...
今天尝试数据库,代码确实没问题就是给了给这个东西 java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecogniz ...
- markdown中锚链接实现目录跳转以及注意事项
当文章有分类,需要快速阅读,通常会先在文首部写一个目录,点击可以跳转. 为文章写目录,特别在文章较长的时候,有助于对内容的整体把握,能提高阅读效率. 以下,将写一个基本的锚目录demo,然后特别说明需 ...
- 《Three.js 入门指南》3.1.1 - 基本几何形状 -圆环结(TorusKnotGeometry)
3.1 基本几何形状 圆环结(TorusKnotGeometry) 构造函数 THREE.TorusKnotGeometry(radius, tube, radialSegments, tubular ...
- js 实现浏览器全屏效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 1006 Sign In and Sign Out (25 分)
At the beginning of every day, the first person who signs in the computer room will unlock the door, ...
- C++primer(第五版)Sales_item.h头文件
C++primer(第五版)1.51练习章节需要有一个Sales_item类,但是给的网站找不到,直接复制下面就好咯: #ifndef SALESITEM_H #define SALESITEM_H ...
- thinkphp中array_diff运行无效 Invalid opcode 153/1/8
经本人查证,发现是thinkPHP优化导致的与array_diff冲突.thinkPHP 报的错:Invalid opcode 153/1/8.有谁知道原理的,说说,让俺也明白.
- Java第三天,如何从键盘输入?匿名对象的使用方法
在学习完Java的基础语法之后,我们还需要学会如何使用API文档,这几乎是程序员所必备的能力.对于API我们不必须去记住每一个类的功能乃至用法,只需会查就行了.但是话说回来,一些经常使用的类我们还是必 ...
- Python实战---制作专属有声小说(调用百度语音合成接口)
这一次的目标是使用百度云的人工智能接口,实现文字转语音的实时转换,将小说文字转换成语音朗读出来. 百度云接口调用 百度的这个接口对于我们普通用户非常友好,他的很多功能都是免费的,而且我们每天可以免费调 ...