这篇“SpringBoot集成Lettuce连接Redis的方法是什么”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringBoot集成Lettuce连接Redis的方法是什么”文章吧。
首先使用maven在pom.xml添加如下依赖
说明:
SpringBoot从2.0起默认使用lettuce客户端进行连接。
此次使用的版本:springboot:2.6.6,lettuce:6.1.8。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
使用SpringBoot集成Lettuce连接实例
Springboot+Lettuce单连方式连接Redis单机/主备/Proxy集群示例。
1、在application.properties配置文件中加上redis相关配置。
spring.redis.host=host spring.redis.database=0 spring.redis.password=pwd spring.redis.port=port
2、Redis配置类RedisConfiguration。
@Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(lettuceConnectionFactory); //使用Jackson2JsonRedisSerializer替换默认的JdkSerializationRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jackson2JsonRedisSerializer.setObjectMapper(mapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }
3、Redis操作类RedisUtil。
/** * 普通缓存获取 * @param key 键 * @return 值 */ public Object get(String key){ return key==null?null:redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key,Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
4、编写controller类进行测试。
@RestController public class HelloRedis { @Autowired RedisUtil redisUtil; @RequestMapping("/setParams") @ResponseBody public String setParams(String name) { redisUtil.set("name", name); return "success"; } @RequestMapping("/getParams") @ResponseBody public String getParams(String name) { System.out.println("--------------" + name + "-------------"); String retName = redisUtil.get(name) + ""; return retName; } }
SpringBoot+Lettuce连接池方式连接Redis单机/主备/Proxy集群示例。
1、在上边maven依赖的基础上添加以下依赖。
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
2、在application.properties配置文件中加上redis相关配置。
spring.redis.host=host spring.redis.database=0 spring.redis.password=pwd spring.redis.port=port # 连接超时时间 spring.redis.timeout=1000 # 连接池最大连接数(使用负值表示没有限制) spring.redis.lettuce.pool.max-active=50 # 连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=5 # 连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=50 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.lettuce.pool.max-wait=5000 #eviction线程调度时间间隔 spring.redis.pool.time-between-eviction-runs-millis=2000
这里最后的这个配置:spring.redis.pool.time-between-eviction-runs-millis=2000 在某些版本中会不生效,需要自己DEBUG看一下
LettuceConnectionFactory
实例里边有没设置成功,如果没有则调整成如下配置:
spring.redis.lettuce.pool.time-between-eviction-runs=2000
3、Redis连接配置类RedisConfiguration。
@Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { lettuceConnectionFactory.setShareNativeConnection(false); RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(lettuceConnectionFactory); //使用Jackson2JsonRedisSerializer替换默认的JdkSerializationRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jackson2JsonRedisSerializer.setObjectMapper(mapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }
SpringBoot+Lettuce单连接方式连接Redis Cluster集群代码示例。
1、在application.properties配置文件中加上redis相关配置。
spring.redis.cluster.nodes=host:port spring.redis.cluster.max-redirects=3 spring.redis.password= pwd # 自动刷新时间 spring.redis.lettuce.cluster.refresh.period=60 # 开启自适应刷新 spring.redis.lettuce.cluster.refresh.adaptive=true spring.redis.timeout=60
2、Redis配置类RedisConfiguration,请务必开启集群自动刷新拓扑配置。
@Bean public LettuceConnectionFactory lettuceConnectionFactory() { String[] nodes = clusterNodes.split(","); List<RedisNode> listNodes = new ArrayList(); for (String node : nodes) { String[] ipAndPort = node.split(":"); RedisNode redisNode = new RedisNode(ipAndPort[0], Integer.parseInt(ipAndPort[1])); listNodes.add(redisNode); } RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(); redisClusterConfiguration.setClusterNodes(listNodes); redisClusterConfiguration.setPassword(password); redisClusterConfiguration.setMaxRedirects(maxRedirects); // 配置集群自动刷新拓扑 ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照周期刷新拓扑 .enableAllAdaptiveRefreshTriggers() //根据事件刷新拓扑 .build(); ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder() //redis命令超时时间,超时后才会使用新的拓扑信息重新建立连接 .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(period))) .topologyRefreshOptions(topologyRefreshOptions) .build(); LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder() .commandTimeout(Duration.ofSeconds(timeout)) .readFrom(ReadFrom.REPLICA_PREFERRED) // 优先从副本读取 .clientOptions(clusterClientOptions) .build(); LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClusterConfiguration, clientConfig); return factory; } @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(lettuceConnectionFactory); //使用Jackson2JsonRedisSerializer替换默认的JdkSerializationRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jackson2JsonRedisSerializer.setObjectMapper(mapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }
springboot+lettuce连接池方式连接Redis Cluster集群代码示例。
1、在application.properties配置文件中加上Redis相关配置。
spring.redis.cluster.nodes=host:port spring.redis.cluster.max-redirects=3 spring.redis.password=pwd spring.redis.lettuce.cluster.refresh.period=60 spring.redis.lettuce.cluster.refresh.adaptive=true # 连接超时时间 spring.redis.timeout=60s # 连接池最大连接数(使用负值表示没有限制) spring.redis.lettuce.pool.max-active=50 # 连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=5 # 连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=50 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.lettuce.pool.max-wait=5000 #eviction线程调度时间间隔 spring.redis.lettuce.pool.time-between-eviction-runs=2000
2、redis配置类RedisConfiguration,请务必开启集群自动刷新拓扑配置。
@Bean public LettuceConnectionFactory lettuceConnectionFactory() { GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); genericObjectPoolConfig.setMaxIdle(maxIdle); genericObjectPoolConfig.setMinIdle(minIdle); genericObjectPoolConfig.setMaxTotal(maxActive); genericObjectPoolConfig.setMaxWait(Duration.ofMillis(maxWait)); genericObjectPoolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(timeBetweenEvictionRunsMillis)); String[] nodes = clusterNodes.split(","); List<RedisNode> listNodes = new ArrayList(); for (String node : nodes) { String[] ipAndPort = node.split(":"); RedisNode redisNode = new RedisNode(ipAndPort[0], Integer.parseInt(ipAndPort[1])); listNodes.add(redisNode); } RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(); redisClusterConfiguration.setClusterNodes(listNodes); redisClusterConfiguration.setPassword(password); redisClusterConfiguration.setMaxRedirects(maxRedirects); // 配置集群自动刷新拓扑 ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() .enablePeriodicRefresh(Duration.ofSeconds(period)) //按照周期刷新拓扑 .enableAllAdaptiveRefreshTriggers() //根据事件刷新拓扑 .build(); ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder() //redis命令超时时间,超时后才会使用新的拓扑信息重新建立连接 .timeoutOptions(TimeoutOptions.enabled(Duration.ofSeconds(period))) .topologyRefreshOptions(topologyRefreshOptions) .build(); LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder() .commandTimeout(Duration.ofSeconds(timeout)) .poolConfig(genericObjectPoolConfig) .readFrom(ReadFrom.REPLICA_PREFERRED) // 优先从副本读取 .clientOptions(clusterClientOptions) .build(); LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClusterConfiguration, clientConfig); return factory; } @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { lettuceConnectionFactory.setShareNativeConnection(false); RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(lettuceConnectionFactory); //使用Jackson2JsonRedisSerializer替换默认的JdkSerializationRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jackson2JsonRedisSerializer.setObjectMapper(mapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }