springboot(8)-多数据源-同一个redis地址的两个database

感谢大佬的参考文档:http://blog.51cto.com/13954634/2170900

https://blog.csdn.net/lc199408/article/details/77154375

总结:

 需要连接几个redis数据源,都可以只创建1个JedisConnectionFactory,其中JedisConnectionFactory使用 setdatabase、sethostName、setport等方法指定了访问Redis的哪个数据库。然后再创建多个RedisTemplate、StringRedisTemplate(两者的区别:https://blog.csdn.net/notsaltedfish/article/details/75948281)。使用@Autowired注解时,会自动创建一个实例,所以我们采用@Resource(name)会指定对应名称的@bean注解。

@Autowired
    @Resource(name="secondStringRedisTemplate")
    private StringRedisTemplate mStringRedisTemplate;
在运行上图时,由于碰到@Autowired,所以springboot会自动查找对应名称的@Bean:

    @Bean(name="secondStringRedisTemplate")
    public StringRedisTemplate secondStringRedisTemplate() {
        Object template;
        template = new StringRedisTemplate();
        ((StringRedisTemplate) template).setConnectionFactory(secondConnectionFactory());
        return (StringRedisTemplate) template;
    }
 
    public JedisConnectionFactory secondConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory(jedisPoolConfig());
        ((JedisConnectionFactory)factory).setHostName(RedisProperty.getHostName);
        ((JedisConnectionFactory)factory).setPort(RedisProperty);
        ((JedisConnectionFactory)factory).setDatabase(RedisProperty);
        ((JedisConnectionFactory)factory).setPoolConfig(PoolConfig());
        return factory;
    }
然后生成对应的template,上面的代码中通过prefix自动匹配到数据源,而@Autowired会自动将配置项set方法自动设置RedisProperty(需要创建这个类):

@ConfigurationProperties(prefix = "spring.redis")//不确定需不需要加prefix,可以试试
//如果加上这个会匹配到spring.redis配置并set各属性,但是jedisConnectionfactory(template不能覆盖)的prefix=spring.redis2可以覆盖这里的redis,会将redis2的配置set到各属性中。
public class RedisProperty {
    private String hostName;
    private int port;
    private String password;
 
    public String getHostName() {
        return this.hostName;
    }
 
    public int getPort() {
        return this.port;
    }
 
    public int getDatabase() {
        return this.database;
    }
}
然后又运行到setConnectionFactory(secondConnectionFactory()),其中secondConnectionFactory()函数指定了对应地址的redis(通过RedisProperty.getdatabase等方法),这样就可以实现使用不同的redis数据源。

实战一:

application.properties:

## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=xxx
## Redis服务器连接端口
spring.redis.port=6379
# 连接超时时间(毫秒)
spring.redis.timeout=5000
 
 
## Redis 配置
## Redis数据库索引(默认为0)
spring.redis2.database=1
## Redis服务器地址
spring.redis2.host=xxx
## Redis服务器连接端口
spring.redis2.port=6379
# 连接超时时间(毫秒)
spring.redis2.timeout=5000
然后创建redisProperty.class:在这里匹配了redis的数据源地址1

@ConfigurationProperties(prefix = "spring.redis")//不确定需不需要加prefix,可以试试
//如果加上这个会匹配到spring.redis配置并set各属性,但是jedisConnectionfactory(template不能覆盖)的prefix=spring.redis2可以覆盖这里的redis,会将redis2的配置set到各属性中。
public class RedisProperty {
    private String hostName;
    private int port;
    private String password;
 
    public String getHostName() {
        return this.hostName;
    }
 
    public int getPort() {
        return this.port;
    }
 
    public int getDatabase() {
        return this.database;
    }
}
然后创建redisConfig:

创建StringredisTemplate,设置beanname(一定要设置,因为创建实例时,需要匹配beanname):

 @Bean(name="RedisTemplate")
    @ConditionalOnBean({RedisConnectionFactory.class})
    public RedisTemplate<Object, Object> RedisTemplate() {
        Object template;
        template = new RedisTemplate();
        ((RedisTemplate) template).setConnectionFactory(RedisConnectionFactory());
        return (RedisTemplate) template;
    }
    @Bean(name="StringRedisTemplate")
    public StringRedisTemplate StringRedisTemplate() {
        Object template;
        template = new StringRedisTemplate();
        ((StringRedisTemplate) template).setConnectionFactory(RedisConnectionFactory());
        return (StringRedisTemplate) template;
    }
创建RedisConnectionFactory:

    public JedisConnectionFactory RedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory(jedisPoolConfig());
        ((JedisConnectionFactory)factory).setHostName(RedisProperty.getHostName);
        ((JedisConnectionFactory)factory).setPort(RedisProperty);
        ((JedisConnectionFactory)factory).setDatabase(RedisProperty);
        ((JedisConnectionFactory)factory).setPoolConfig(PoolConfig());
        return factory;
    }
然后创建一个controller:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
 
@RestController
public class Getxxx {
    @Autowired
    @Resource(name="StringRedisTemplate")
    private StringRedisTemplate mStringRedisTemplate;
 
    @GetMapping(value = xxx)
    public String getxxx(
          mStringRedisTemplate.delete(key);
            mStringRedisTemplate.opsForValue().set(key,value)
 
    }
}
使用第二个redis操作:

在redisConfig创建SecondStringredisTemplate,设置beanname(一定要设置,因为创建实例时,需要匹配beanname):

 @Bean(name="SecondRedisTemplate")
    @ConditionalOnBean({RedisConnectionFactory.class})
    public RedisTemplate<Object, Object> RedisTemplate() {
        Object template;
        template = new RedisTemplate();
        ((RedisTemplate) template).setConnectionFactory(SecondRedisConnectionFactory());
        return (RedisTemplate) template;
    }
    @Bean(name="SecondStringRedisTemplate")
    public StringRedisTemplate StringRedisTemplate() {
        Object template;
        template = new StringRedisTemplate();
        ((StringRedisTemplate) template).setConnectionFactory(SecondRedisConnectionFactory());
        return (StringRedisTemplate) template;
    }
创建SecondRedisConnectionFactory:

    @Bean({"secondRedisConnectionFactory"})
    @ConfigurationProperties(prefix="spring.redis2")//匹配redis2,会覆盖RedisProperty的prefix
 public JedisConnectionFactory secondRedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory(jedisPoolConfig());
        ((JedisConnectionFactory)factory).setHostName(RedisProperty.getHostName);
        ((JedisConnectionFactory)factory).setPort(RedisProperty);
        ((JedisConnectionFactory)factory).setDatabase(RedisProperty);
        ((JedisConnectionFactory)factory).setPoolConfig(PoolConfig());
        return factory;
    }
然后创建一个新的controller:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
 
@RestController
public class Getxxx {
    @Autowired
    @Resource(name="SecondStringRedisTemplate")
    private StringRedisTemplate mStringRedisTemplate;
 
    @GetMapping(value = xxx)
    public String getxxx(
          mStringRedisTemplate.delete(key);
            mStringRedisTemplate.opsForValue().set(key,value)
 
    }
}
这样使用不同的

@Autowired
    @Resource(name="SecondStringRedisTemplate")
    private StringRedisTemplate mStringRedisTemplate;

就可以达到使用不同的redis地址。

方法二:(比较科学)

创建RedisConfig.class:Template匹配redis配置源地址,然后传给ConnectionFactory函数中:

@Configuration
public class RedisDevConfiguration {
 
    @Bean(name = "redisTemplate")
    public StringRedisTemplate redisTemplate(
//可以把这一步的@value放在RedisProperty.class进行,设置setter和getter
@Value("${spring.redis.host}") String hostName,
            @Value("${spring.redis.port}") int port, @Value("${spring.redis.password}") String password,
            @Value("${spring.redis.database}") int index {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(
                connectionFactory(hostName, port, password,index));
 
        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;
    }
}
如果需要加上另一个redis(需要几个redis,就创建几个redisTemplate):

就添加:

 @Bean(name = "redis2Template")
    public StringRedisTemplate secondredisTemplate(@Value("${spring.redis2.host}") String hostName,
            @Value("${spring.redis.port}") int port, @Value("${spring.redis.password}") String password,
            @Value("${spring.redis2.database}") int index {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(
                connectionFactory(hostName, port, password, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow));
        return temple;
    }
同理,创建Controller:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
 
@RestController
public class Getxxx {
    @Autowired
    @Resource(name="redisTemplate")//或者是redis2Template
    private StringRedisTemplate mStringRedisTemplate;
 
    @GetMapping(value = xxx)
    public String getxxx(
          mStringRedisTemplate.delete(key);
            mStringRedisTemplate.opsForValue().set(key,value)
 
    }
}
这样使用不同的

@Autowired
    @Resource(name="SecondStringRedisTemplate")
    private StringRedisTemplate mStringRedisTemplate;

就可以达到使用不同的redis地址。


原文链接:https://blog.csdn.net/qq_38204134/article/details/84859875

Spring Boot中集成多个Redis数据源需要进行以下步骤: 1. 添加依赖:在pom.xml文件中添加Spring Boot Redis和Jedis依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> ``` 2. 配置多个数据源:在application.properties或application.yml文件中配置多个Redis数据源的连接信息。示例配置如下: ```properties # 第一个数据源 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.database=0 # 第二个数据源 spring.redis.second.host=127.0.0.1 spring.redis.second.port=6380 spring.redis.second.password= spring.redis.second.database=1 ``` 3. 创建多个RedisTemplate:在配置类中创建多个RedisTemplate,每个Template对应一个Redis数据源。示例代码如下: ```java @Configuration public class RedisConfig { @Bean @Primary public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置key和value的序列化器 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } @Bean("secondRedisTemplate") public RedisTemplate<String, Object> secondRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置key和value的序列化器 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 4. 使用多个数据源:在需要使用Redis的地方,注入对应的RedisTemplate即可。示例代码如下: ```java @RestController public class RedisController { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired @Qualifier("secondRedisTemplate") private RedisTemplate<String, Object> secondRedisTemplate; @RequestMapping("/set") public String set() { redisTemplate.opsForValue().set("key1", "value1"); secondRedisTemplate.opsForValue().set("key2", "value2"); return "success"; } @RequestMapping("/get") public String get() { String value1 = (String) redisTemplate.opsForValue().get("key1"); String value2 = (String) secondRedisTemplate.opsForValue().get("key2"); return "value1: " + value1 + ", value2: " + value2; } } ``` 以上就是在Spring Boot中集成多个Redis数据源的简要步骤。通过配置不同的数据源和创建对应的RedisTemplate,可以实现对多个Redis实例的访问和操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那些年的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值