码迷,mamicode.com
首页 > 编程语言 > 详细

Spring cloud整合Reids 配置多个数据源

时间:2018-12-07 01:30:21      阅读:714      评论:0      收藏:0      [点我收藏+]

标签:dal   ali   temp   size   dex   redis   return   etc   frame   

首先是连接池的选择 一般有两种 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);
    }

}

 

Spring cloud整合Reids 配置多个数据源

标签:dal   ali   temp   size   dex   redis   return   etc   frame   

原文地址:https://www.cnblogs.com/dikeboy/p/10080653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!