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,256m 问题描述 何老板在玩一款怪兽游戏.游戏虽然简单,何老板仍旧乐此不疲.游戏一开始有N只怪兽,编号1到N.其中第i只怪兽 ...
- FarmCraft --(树形DP)
题目描述 In a village called Byteville, there are houses connected with N-1 roads. For each pair of hous ...
- chrome浏览器的json格式化插件
JSON-Handle 下载地址: http://jsonhandle.sinaapp.com/ 插件下载后,在浏览器输入:chrome://extensions/ 将下载后的文件 ...
- 使用Homebrew在Mountain Lion上安装MySQL
一.安装mysql brew install mysql 二.开机启动mysql brew info mysql 根据提示,设置开机启动 三.设置mysql开启和停止命令 alias mysql-st ...
- Hadoop(七):自定义输入输出格式
MR输入格式概述 数据输入格式 InputFormat. 用于描述MR作业的数据输入规范. 输入格式在MR框架中的作用: 文件进行分块(split),1个块就是1个Mapper任务. 从输入分块中将数 ...
- Flask 入门(九)
外键数据库 我们想想,所有的数据不可能这么简单,万一建的数据库有了外键呢?如何增加,如何查询? 承接上文: 先登录mysql数据库,把里面的表和数据都删了 执行语句: use data select ...
- std::string::copy函数
size_t copy (char* s, size_t len, size_t pos = 0) const;
- 11-JS变量
一. JavaScript 是什么 JavaScript是一种运行在客户端(浏览器)的脚本语言 客户端:客户端是相对于服务器而言的,在这里先简单理解为浏览器 浏览器就是一个客户端软件,浏览器从服务器上 ...
- Geber文件,装配图,BOM表的输出
一.Geber文件的输出步骤: 注:选择需要导出的层 注:所指箭头的地方都多加个零,让输出有更大的空间来容纳 总结:这就是最终的Geber文件了 二.NC Drill file的输出: 三.IPC ...
- 基于 Njmon + InfluxDB + Grafana 实现性能指标实时可视监控
引言 最近逛 nmon 官网时,发现了一个新工具 njmon,功能与 nmon 类似,但输出为 JSON 格式,可以用于服务器性能统计. 可以使用 njmon 来向 InfluxDB 存储服务器性能统 ...