springboot中Redis的Lettuce客户端和jedis客户端

时间:2021-07-03 09:31:37

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客户端的更多相关文章

  1. SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍

    今天给大家介绍一下SpringBoot中Redis的set.map.list.value等基本操作的具体使用方法 上一节中给大家介绍了如何在SpringBoot中搭建Redis缓存数据库,这一节就针对 ...

  2. SpringBoot中Redis的使用

    转载:http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html Spring Boot 对常用的数据库支持外,对 No ...

  3. Redis服务器搭建&sol;配置&sol;及Jedis客户端的使用方法

    摘要 Redis服务器搭建.常用参数含意说明.主从配置.以及使用Jedis客户端来操作Redis Redis服务器搭建 安装 在命令行执行下面的命令: $ wget http://download.r ...

  4. springboot中redis取缓存类型转换异常

    异常如下: [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested ...

  5. SpringBoot中redis的使用介绍

    REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...

  6. ③SpringBoot中Redis的使用

    本文基于前面的springBoot系列文章进行学习,主要介绍redis的使用. SpringBoot对常用的数据库支持外,对NoSQL 数据库也进行了封装自动化. redis介绍 Redis是目前业界 ...

  7. springboot中redis的缓存穿透问题

    什么是缓存穿透问题?? 我们使用redis是为了减少数据库的压力,让尽量多的请求去承压能力比较大的redis,而不是数据库.但是高并发条件下,可能会在redis还没有缓存的时候,大量的请求同时进入,导 ...

  8. springBoot 中redis 注解缓存的使用

    1,首先在启动类上加上 @EnableCaching 这个注解 在查询类的controller,或service ,dao 中方法上加 @Cacheable 更新或修改方法上加 @CachePut 注 ...

  9. redis学习(七)jedis客户端

    1.下载jedis的jar包 http://repo1.maven.org/maven2/redis/clients/jedis/2.8.1/ 2.启动redis后台 3.测试联通 package c ...

随机推荐

  1. Device Tree(二):基本概念

    转自:http://www.wowotech.net/linux_kenrel/dt_basic_concept.html 一.前言 一些背景知识(例如:为何要引入Device Tree,这个机制是用 ...

  2. C&num;邮件发送

    public static void CreateCopyMessage() { MailAddress from = new MailAddress("yang@163.com" ...

  3. Android Studio git ignore

    # Built application files *.apk *.ap_ # Files for the Dalvik VM *.dex # Java class files *.class # G ...

  4. 引入工程报包导入异常:import javax&period;servlet&period;annotation&period;WebFilter&semi;

    引入工程报包导入异常:import javax.servlet.annotation.WebFilter; (2013-02-21 16:38:00)   分类: java 今天上午导入了一个项目,用 ...

  5. 屏幕适配&sol;autoLayout autoresizingMask

    #pragma mark-- 屏幕适配/autoLayout autoresizingMask 1> 发展历程 代码计算frame -> autoreszing(父控件和子控件的关系) - ...

  6. Html5如何自学 只需这几步

    Html5在整个行业卷起了一场大潮流,好多人都,但是很多人都不知道该怎么学习Html5,不知道Html5该如何自学?不知道Html5开发多久才会学会?接下来将从以下几点内容详细讲述. 第一,很多人建议 ...

  7. Leetcode&lowbar;94&lowbar;Binary Tree Inorder Traversal

    本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42876657 Given a binary tree, r ...

  8. JS基础题

    1.三目运算符(三元条件语句)的使用方法? 条件表达式?true表达式:false表达式 2.JS数据中哪些属于引用类型? 数组.对象 引用类型变量,变量名所储存的不是变量值,而是变量所在的地址. 3 ...

  9. Java Base64编码

    使用commons-codec, 下载地址 http://commons.apache.org/proper/commons-codec/ 下载commons-codec-1.12-bin.zip,解 ...

  10. BZOJ 3329 - Xorequ - 数位DP&comma; 矩乘

    Solution 发现 $x \ xor \  2x = 3x$ 仅当 $x$ 的二进制中没有相邻的 $1$ 对于第一个问题就可以进行数位DP 了. 但是对于第二个问题, 我们只能通过递推 打表 来算 ...