springboot redis多数据源设置

18 篇文章 0 订阅
4 篇文章 0 订阅

遇到这样一个需求:运营人员在发布内容的时候可以选择性的发布到测试库、开发库和线上库。 
项目使用的是spring boot集成redis,实现如下:

1. 引入依赖

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
1
2
3
4
5
6
7
8
2.多数据源设置

application.yml设置(application.properties同理):

spring:
  redis:
    database: 0
    pool:
      max-active: 8
      max-idle: 9
      max-wait: -1
      min-idle: 0
    redis-dev:
      host: 填redis的ip地址
      prot: 填redis的端口号
      password: 填redis的密码
      testOnBorrow: fals
    redis-test:
      host:
      prot:
      password:
      testOnBorrow: false
    redis-online:
      host:
      prot:
      password:
      testOnBorrow: false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
针对每个数据源写一个配置类: 
这里就只列举其中一个,不同的数据源设置不同的@Bean和@Value注解即可

@Configuration
public class RedisDevConfiguration {

    @Bean(name = "redisDevTemplate")
    public StringRedisTemplate redisTemplate(@Value("${spring.redis-dev.host}") String hostName,
            @Value("${spring.redis-dev.port}") int port, @Value("${spring.redis-dev.password}") String password,
            @Value("${spring.redis-dev.testOnBorrow}") boolean testOnBorrow,
            @Value("${spring.redis.pool.max-idle}") int maxIdle, @Value("${spring.redis.pool.max-active}") int maxTotal,
            @Value("${spring.redis.database}") int index, @Value("${spring.redis.pool.max-wait}") long maxWaitMillis) {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(
                connectionFactory(hostName, port, password, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow));

        return temple;
    }

    public RedisConnectionFactory connectionFactory(String hostName, int port, String password, int maxIdle,
            int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(hostName);
        jedis.setPort(port);
        if (StringUtils.isNotEmpty(password)) {
            jedis.setPassword(password);
        }
        if (index != 0) {
            jedis.setDatabase(index);
        }
        jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, testOnBorrow));
        // 初始化连接pool
        jedis.afterPropertiesSet();
        RedisConnectionFactory factory = jedis;

        return factory;
    }

    public JedisPoolConfig poolCofig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {
        JedisPoolConfig poolCofig = new JedisPoolConfig();
        poolCofig.setMaxIdle(maxIdle);
        poolCofig.setMaxTotal(maxTotal);
        poolCofig.setMaxWaitMillis(maxWaitMillis);
        poolCofig.setTestOnBorrow(testOnBorrow);
        return poolCofig;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
3.构造redis实例

写一个redis实例抽象类

public abstract class AbRedisConfiguration {
    protected StringRedisTemplate temple;

    public void setData(String key, String value) {
        getTemple().opsForValue().set(key, value);
    }

    public String getData(String key) {
        return getTemple().opsForValue().get(key);
    }

    public StringRedisTemplate getTemple() {
        return temple;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
继成抽象类实现操作类,这里只列举一个

@Component
public class RedisDev extends AbRedisConfiguration {
    @Resource(name = "redisDevTemplate")
    private StringRedisTemplate temple;

    public StringRedisTemplate getTemple() {
        return temple;
    }
}
1
2
3
4
5
6
7
8
9
4.使用

在service中注入redis操作类

    @Autowired
    private RedisDev redisDev;
    @Autowired
    private RedisTest redisTest;
    @Autowired
    private RedisTest redisOnline;
1
2
3
4
5
6
调用不同的操作类即可使用不同的redis数据源。
--------------------- 
作者:lc199408 
来源:CSDN 
原文:https://blog.csdn.net/lc199408/article/details/77154375?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

在Spring Boot中配置多个Redis数据源需要做以下几个步骤: 1. 在pom.xml中添加Redis和Lettuce的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` 2. 在application.yml中配置多个Redis数据源,例如: ```yaml spring: redis: host: localhost port: 6379 password: password database: 0 jedis: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1ms redis2: host: localhost port: 6380 password: password database: 1 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1ms ``` 注意,每个Redis数据源需要定义一个唯一的名称,如redisredis2。 3. 在Java代码中创建多个RedisTemplate实例,并指定对应的RedisConnectionFactory,例如: ```java @Configuration public class RedisConfig { @Bean(name = "redisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); return redisTemplate; } @Bean(name = "redisTemplate2") public RedisTemplate<String, Object> redisTemplate2(@Qualifier("redisConnectionFactory2") RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); return redisTemplate; } @Bean(name = "redisConnectionFactory") public RedisConnectionFactory redisConnectionFactory(RedisProperties redisProperties) { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName(redisProperties.getHost()); jedisConnectionFactory.setPort(redisProperties.getPort()); jedisConnectionFactory.setPassword(redisProperties.getPassword()); jedisConnectionFactory.setDatabase(redisProperties.getDatabase()); jedisConnectionFactory.setUsePool(true); jedisConnectionFactory.getPoolConfig().setMaxTotal(redisProperties.getJedis().getPool().getMaxActive()); jedisConnectionFactory.getPoolConfig().setMaxIdle(redisProperties.getJedis().getPool().getMaxIdle()); jedisConnectionFactory.getPoolConfig().setMinIdle(redisProperties.getJedis().getPool().getMinIdle()); jedisConnectionFactory.getPoolConfig().setMaxWaitMillis(redisProperties.getJedis().getPool().getMaxWait().toMillis()); return jedisConnectionFactory; } @Bean(name = "redisConnectionFactory2") public RedisConnectionFactory redisConnectionFactory2(@Qualifier("redisProperties2") RedisProperties redisProperties) { LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(); lettuceConnectionFactory.setHostName(redisProperties.getHost()); lettuceConnectionFactory.setPort(redisProperties.getPort()); lettuceConnectionFactory.setPassword(redisProperties.getPassword()); lettuceConnectionFactory.setDatabase(redisProperties.getDatabase()); lettuceConnectionFactory.setUsePooling(true); lettuceConnectionFactory.setPoolConfig(getLettucePoolConfig(redisProperties.getLettuce().getPool())); return lettuceConnectionFactory; } @Bean(name = "redisProperties") @ConfigurationProperties(prefix = "spring.redis") public RedisProperties redisProperties() { return new RedisProperties(); } @Bean(name = "redisProperties2") @ConfigurationProperties(prefix = "spring.redis2") public RedisProperties redisProperties2() { return new RedisProperties(); } private GenericObjectPoolConfig<?> getLettucePoolConfig(LettucePoolingClientConfiguration.Pool pool) { GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>(); config.setMaxTotal(pool.getMaxActive()); config.setMaxIdle(pool.getMaxIdle()); config.setMinIdle(pool.getMinIdle()); config.setMaxWaitMillis(pool.getMaxWait().toMillis()); return config; } } ``` 要使用第二个Redis数据源,只需使用@Qualifier指定对应的RedisTemplate实例,例如: ```java @Autowired @Qualifier("redisTemplate2") private RedisTemplate<String, Object> redisTemplate2; ``` 这样就可以在Spring Boot中配置多个Redis数据源了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值