SpringBoot集成Lettuce

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Redis 版,经济版 1GB 1个月
简介: SpringBoot集成Lettuce


SpringBoot从2.0起默认使用lettuce客户端进行连接

参考

Springboot+Lettuce单连方式连接Redis单机/主备/Proxy集群示例

  • pom
<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> 
spring.redis.host=host   
spring.redis.database=0   
spring.redis.password=pwd  
spring.redis.port=port 
  • Redis配置类
@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;   
}  
  • 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;   
     }   
 }
  • 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集群示例

  • 添加以下依赖
<dependency>   
  <groupId>org.apache.commons</groupId>   
  <artifactId>commons-pool2</artifactId>   
</dependency> 
  • 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 
  • Redis连接配置类
@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集群代码示例

  • 配置文件中加上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
  • Redis配置类,务必开启集群自动刷新拓扑配置
@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集群代码示例

  • 配置文件中加上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
  • redis配置类,务必开启集群自动刷新拓扑配置
@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;   
}  

说明:host为Redis实例的IP地址/域名,port为Redis实例的端口,请按实际情况修改后执行,pwd为创建Redis实例时自定义的密码,请按实际情况修改后执行。推荐使用连接池方式。超时时间(TimeOut),最大连接数(MaxTotal),最小空闲连接(MinIdle),最大空闲连接(MaxIdle),最大等待时间(MaxWait)等相关参数,请根据业务实际来调优


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
6天前
|
消息中间件 Java Kafka
集成Kafka到Spring Boot项目中的步骤和配置
集成Kafka到Spring Boot项目中的步骤和配置
34 7
|
6天前
|
druid Java 关系型数据库
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
59 5
|
6天前
|
Java 数据库连接 mybatis
在Spring Boot应用中集成MyBatis与MyBatis-Plus
在Spring Boot应用中集成MyBatis与MyBatis-Plus
38 5
|
6天前
|
前端开发 JavaScript 安全
集成WebSocket在Spring Boot中可以用于实现实时的双向通信
集成WebSocket在Spring Boot中可以用于实现实时的双向通信
25 4
|
6天前
|
安全 Java Maven
在 Spring Boot 中实现邮件发送功能可以通过集成 Spring Boot 提供的邮件发送支持来完成
在 Spring Boot 中实现邮件发送功能可以通过集成 Spring Boot 提供的邮件发送支持来完成
14 2
|
6天前
|
XML 搜索推荐 Java
Elasticsearch集成到Spring Boot项目
将Elasticsearch集成到Spring Boot项目中,可以方便地实现数据的搜索、分析等功能。
29 2
|
6天前
|
监控 前端开发 Java
五分钟后,你将学会在SpringBoot项目中如何集成CAT调用链
五分钟后,你将学会在SpringBoot项目中如何集成CAT调用链
|
6天前
|
Java API Spring
集成EasyPoi(一个基于POI的Excel导入导出工具)到Spring Boot项目中
集成EasyPoi(一个基于POI的Excel导入导出工具)到Spring Boot项目中
38 1
|
7天前
|
easyexcel Java API
SpringBoot集成EasyExcel 3.x:高效实现Excel数据的优雅导入与导出
SpringBoot集成EasyExcel 3.x:高效实现Excel数据的优雅导入与导出
26 1
|
9天前
|
缓存 人工智能 监控
集成人工智能到Spring Boot项目
集成人工智能到Spring Boot项目
24 1