springboot redis使用lettuce配置多数据源的实现

 更新时间:2021年04月29日 16:27:08   作者:cccccloud.com  
这篇文章主要介绍了springboot redis使用lettuce配置多数据源的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

目前项目上需要连接两个redis数据源,一个redis数据源是单机模式,一个redis数据源是分片集群模式,这里将具体配置列一下。

项目用的springboot版本为

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

一、在yml中配置redis数据源信息

redis:
    cluster:
      nodes: 127.0.0.1:9001
    lettuce:
      #连接池配置
      pool:
        #连接池最大连接数
        max-active: 20
        #连接池最大等待时间,负数表示不做限制
        max-wait: -1
        #最大空闲连接
        max-idle: 9
        #最小空闲连接
        min-idle: 0
    timeout: 500000
  redis2:
    host: 127.0.0.1
    port: 6385
    lettuce:
      pool:
        max-active: 20
        max-idle: 8
        max-wait: -1
        min-idle: 0
    timeout: 500000

(这里的redis都没有配置密码)

二、添加redis配置类

package com.cq.config;
 
import cn.hutool.core.convert.Convert;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author cccccloud on 2020/11/16 17:16
 */
@Configuration
public class RedisConfig {
 
    @Autowired
    private Environment environment;
 
    @Value("${spring.redis2.host}")
    private String host;
    @Value("${spring.redis2.port}")
    private String port;
    @Value("${spring.redis2.lettuce.pool.max-active}")
    private String max_active;
    @Value("${spring.redis2.lettuce.pool.max-idle}")
    private String max_idle;
    @Value("${spring.redis2.lettuce.pool.max-wait}")
    private String max_wait;
    @Value("${spring.redis2.lettuce.pool.min-idle}")
    private String min_idle;
 
    /**
     * 配置lettuce连接池
     *
     * @return
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.redis.cluster.lettuce.pool")
    public GenericObjectPoolConfig redisPool() {
        return new GenericObjectPoolConfig();
    }
 
    /**
     * 配置第一个数据源的
     *
     * @return
     */
    @Bean("redisClusterConfig")
    @Primary
    public RedisClusterConfiguration redisClusterConfig() {
 
        Map<String, Object> source = new HashMap<>(8);
        source.put("spring.redis.cluster.nodes", environment.getProperty("spring.redis.cluster.nodes"));
        RedisClusterConfiguration redisClusterConfiguration;
        redisClusterConfiguration = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
        redisClusterConfiguration.setPassword(environment.getProperty("spring.redis.password"));
        return redisClusterConfiguration;
 
    }
 
    /**
     * 配置第一个数据源的连接工厂
     * 这里注意:需要添加@Primary 指定bean的名称,目的是为了创建两个不同名称的LettuceConnectionFactory
     *
     * @param redisPool
     * @param redisClusterConfig
     * @return
     */
    @Bean("lettuceConnectionFactory")
    @Primary
    public LettuceConnectionFactory lettuceConnectionFactory(GenericObjectPoolConfig redisPool, @Qualifier("redisClusterConfig") RedisClusterConfiguration redisClusterConfig) {
        LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(redisPool).build();
        return new LettuceConnectionFactory(redisClusterConfig, clientConfiguration);
    }
 
    /**
     * 配置第一个数据源的RedisTemplate
     * 注意:这里指定使用名称=factory 的 RedisConnectionFactory
     * 并且标识第一个数据源是默认数据源 @Primary
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean("redisTemplate")
    @Primary
    public RedisTemplate redisTemplate(@Qualifier("lettuceConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
 
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(stringRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(stringRedisSerializer);
        template.afterPropertiesSet();
 
        return template;
    }
 
    @Bean
    public GenericObjectPoolConfig redisPool2() {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMinIdle(Convert.toInt(min_idle));
        config.setMaxIdle(Convert.toInt(max_idle));
        config.setMaxTotal(Convert.toInt(max_active));
        config.setMaxWaitMillis(Convert.toInt(max_wait));
        return config;
    }
 
    @Bean
    public RedisStandaloneConfiguration redisConfig2() {
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration(host,Convert.toInt(port));
        return redisConfig;
    }
 
    @Bean("factory2")
    public LettuceConnectionFactory factory2(@Qualifier("redisPool2") GenericObjectPoolConfig config,
                                             @Qualifier("redisConfig2") RedisStandaloneConfiguration redisConfig) {//注意传入的对象名和类型RedisStandaloneConfiguration
        LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(config).build();
        return new LettuceConnectionFactory(redisConfig, clientConfiguration);
    }
 
 
    /**
     * 单实例redis数据源
     *
     * @param connectionFactory
     * @return
     */
    @Bean("redisTemplateSingle")
    public RedisTemplate<String, Object> redisTemplateSingle(@Qualifier("factory2")LettuceConnectionFactory connectionFactory) {//注意传入的对象名
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
 
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        redisTemplate.setHashValueSerializer(redisSerializer);
        return redisTemplate;
    }
}

三、使用redis

使用单实例redis

    /**
     * redis 单节点
     */
    @Resource(name = "redisTemplateSingle")
    private RedisTemplate redisTemplateSingle;

使用redis集群

    /**
     * redis 集群
     */
    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;
 

到此这篇关于springboot redis使用lettuce配置多数据源的实现的文章就介绍到这了,更多相关springboot lettuce多数据源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java字符串编码解码性能提升的技巧分享

    Java字符串编码解码性能提升的技巧分享

    这篇文章主要是和大家分享几个Java中提升字符串编码解码性能的小技巧,文中的示例代码讲解详细,对我们学习有一定的帮助,需要的可以参考一下
    2022-05-05
  • springboot使用校验框架validation校验的示例

    springboot使用校验框架validation校验的示例

    这篇文章主要介绍了springboot使用校验框架validation校验的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • Java优雅的关闭线程池的方法

    Java优雅的关闭线程池的方法

    本文主要介绍了Java如何优雅的关闭线程池,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • java中lombok的@Data引发问题详解

    java中lombok的@Data引发问题详解

    这篇文章主要给大家介绍了关于java中lombok的@Data引发问题的相关资料,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • idea集成shell运行环境以及shell输出中文乱码的解决

    idea集成shell运行环境以及shell输出中文乱码的解决

    这篇文章主要介绍了idea集成shell运行环境以及shell输出中文乱码的解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • 浅谈 JDBC 元数据

    浅谈 JDBC 元数据

    这篇文章主要介绍了JDBC元数据的相关内容,涉及一些获取数据源各种信息的方法,具有一定参考价值,需要的朋友可以了解下。
    2017-09-09
  • Java ClassCastException异常解决方案

    Java ClassCastException异常解决方案

    这篇文章主要介绍了Java ClassCastException异常解决方案,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • IntelliJ IDEA cmd和idea Terminal查看java版本不一致的解决方案

    IntelliJ IDEA cmd和idea Terminal查看java版本不一致的解决

    原来win10电脑上安装的是jdk8的版本,因某些原因,现在想换成jdk7的版本,修改环境变量后,在cmd中执行 [java -version]命令,显示的是7的版本,遇到这样的问题如何解决呢?下面小编给大家分享IntelliJ IDEA cmd和idea Terminal查看java版本不一致的解决方案,一起看看吧
    2023-09-09
  • Spring MVC请求转发与请求重定向的示例详解

    Spring MVC请求转发与请求重定向的示例详解

    转发指服务器接收请求后,从一个资源跳转到另一个资源中,请求转发是一次请求,不会改变浏览器的请求地址,这篇文章主要介绍了Spring MVC请求转发与请求重定向的相关知识,需要的朋友可以参考下
    2023-09-09
  • java 使用线程监控文件目录变化的实现方法

    java 使用线程监控文件目录变化的实现方法

    这篇文章主要介绍了java 使用线程监控文件目录变化的实现方法的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下
    2017-10-10

最新评论