1. 程式人生 > >Spring cloud整合Reids 配置多個數據源

Spring cloud整合Reids 配置多個數據源

首先是連線池的選擇 一般有兩種 lettuce ,jedis

Jedis  執行緒不安全,方法同步

Lettuce  基於Netty.nio, 方法非同步 執行緒 安全

letture通過引入spring-boot-starter-redis就可以使用

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
             <version>1.0
.1.RELEASE</version> </dependency>

而Jedis需要在這基礎上引入

    <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <type>jar</type>
        </dependency>

可以同時配置多個RedisConnectionFactory

多個factory需要標註Primary  未標註的Factory系統會呼叫 StringRedisTemplate

@RestController
public class MyController {
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate lettuceTemplate;
    @Autowired
    @Resource(name="jedisTemplate")
    private RedisTemplate jedisTemplate;

     
    @RequestMapping(
"/") public String index() { return "hello "+lettuceTemplate.opsForValue().get("name"); } @RequestMapping("/set") public String index(@RequestParam String name) { jedisTemplate.opsForValue().set("name",name,Duration.ofMillis(5000)); return "success "; } // @Bean("jedisTemplate") public RedisTemplate<String, Object> jedisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory()); return template; } @Bean("lettuceTemplate") public RedisTemplate<String, Object> lettuceTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(lettuceConnectionFactory()); return template; } @Primary @Bean("jedisConnectionFactory") public RedisConnectionFactory jedisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName("127.0.0.1"); config.setPort(6379); config.setPassword("123456"); return new JedisConnectionFactory(config); } /** * Lettuce */ @Bean("lettuceConnectionFactory") public RedisConnectionFactory lettuceConnectionFactory() { System.out.println("lettuceConnectionFactory "); RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName("127.0.0.1"); config.setPort(6379); config.setPassword("123456"); return new LettuceConnectionFactory(config); } }