springboot配置redis多数据源

硅谷探秘者 Md redis,springboot 1077 0 0

一、springboot集成redis一般配置

pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.8.0</version>
        </dependency>

配置文件

spring:
  redis:
    database: 0
    host: 127.0.0.1
    password: 123456
    lettuce:
      pool:
        max-active: 8   #最大连接数据库连接数,设 0 为没有限制
        max-idle: 8     #最大等待连接中的数量,设 0 为没有限制
        max-wait: -1ms  #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
        min-idle: 0     #最小等待连接中的数量,设 0 为没有限制
      shutdown-timeout: 100ms
    port: 6379

配置类


import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Resource
    private RedisConnectionFactory factory;

    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericFastJsonRedisSerializer());
        return redisTemplate;
    }
}

使用

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

二、引入第二个数据源other

在一般配置的基础上,引入第二个redis数据源

yml配置文件添加

spring:
  redis:
    database: 0
    host: 127.0.0.1
    password: 123456
    lettuce:
      pool:
        max-active: 8   #最大连接数据库连接数,设 0 为没有限制
        max-idle: 8     #最大等待连接中的数量,设 0 为没有限制
        max-wait: -1ms  #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
        min-idle: 0     #最小等待连接中的数量,设 0 为没有限制
      shutdown-timeout: 100ms
    port: 6379
  other:  # 第二个数据源的配置,至少要配置一个database,如果host,port,password不配置,则使用spring.redis中的配置
    database: 2
    host: 192.168.1.103
    port: 6379
    password: 123456

第二个数据源的配置,至少要配置一个database,如果host,port,password不配置,则使用spring.redis中的配置

添加配置类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("spring.other")
@Data
public class OtherRedisProperties {
    private Integer database;
    private String host;
    private String password;
    private Integer port;
}
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
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;
@Configuration
@EnableConfigurationProperties(OtherRedisProperties.class)
public class OtherRedisConfig {

    @Bean
    @ConditionalOnMissingBean(name = "otherRedisTemplate")
    public RedisTemplate<String, Object> otherRedisTemplate(RedisProperties redisProperties, OtherRedisProperties otherRedisProperties, @Autowired(required = false) RedisSerializer<Object> defaultRedisSerializer) {
        LettucePoolingClientConfiguration build = LettucePoolingClientConfiguration.builder().poolConfig(getPoolConfig(redisProperties.getLettuce().getPool())).build();
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(getStandaloneConfig(redisProperties, otherRedisProperties), build);
        connectionFactory.afterPropertiesSet();
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
        if (defaultRedisSerializer != null) {
            redisTemplate.setDefaultSerializer(defaultRedisSerializer);
        }
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
    private GenericObjectPoolConfig<?> getPoolConfig(RedisProperties.Pool properties) {
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(properties.getMaxActive());
        config.setMaxIdle(properties.getMaxIdle());
        config.setMinIdle(properties.getMinIdle());
        if (properties.getTimeBetweenEvictionRuns() != null) {
            config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis());
        }
        if (properties.getMaxWait() != null) {
            config.setMaxWaitMillis(properties.getMaxWait().toMillis());
        }
        return config;
    }
    protected final RedisStandaloneConfiguration getStandaloneConfig(RedisProperties properties, OtherRedisProperties otherRedisProperties) {
        PropertyMapper map = PropertyMapper.get();
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();

        config.setHostName(properties.getHost());
        config.setPort(properties.getPort());
        config.setPassword(properties.getPassword());
        config.setDatabase(properties.getDatabase());

        //设置新设置的redis参数
        map.from(otherRedisProperties.getHost()).whenNonNull().to(config::setHostName);
        map.from(otherRedisProperties.getPort()).whenNonNull().to(config::setPort);
        map.from(otherRedisProperties.getDatabase()).whenNonNull().to(config::setDatabase);
        map.from(otherRedisProperties.getPassword()).whenNonNull().to(config::setPassword);
        return config;
    }
}

使用

    @Resource
    private RedisTemplate<String,Object> otherRedisTemplate;

评论区
请写下您的评论...
暂无评论...
猜你喜欢
框架 3374 spring:datasource:main:#主username:rootpassword:123456jdbc-url:jdbc:mysql://localhost:3306/main?useUni
java项目 1394 springboot+mybatis并利用aop实现自动切换(demo)
框架 1660 springboot+mybatis并利用aop实现自动切换1.项目大致结构2.pom依赖dependencygroupIdorg.springframework.boot
框架 2415 安装redis库参考:http://www.jiajiajia.club/blog/artical/166redis详解参考:http://www.jiajiajia.club/blog
框架,springboot 97 springboot用自带的logback打印日志环境打印生产环境输出到控制台和文件,一天一个文件,保留30天开发环境输出到控制台 二、logback-spring.xml文件详情?xmlversion="1.
spring/springmvc 2666 springMVC视图管理器在springmvc的文件中如下:!--视图管理器--!--jsp视图管理器1--beanclass
redis 735 介绍  单机版的Redis存在性能瓶颈,Redis通过提高主从复制实现读写分离,提高了了Redis的可用性,另一方便也能实现Redis直接的备份。  通过Redis的主从复制机制可以提
linux系统 3939 linux下安装redis库到官网下载对应的tar.gz包https://redis.io/解压我是直接解压到了/opt文件夹下进入redis-5.0.4文件夹下,执行#cdredis
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1 2024-04  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。