Spring cloud整合Reids 配置多个数据源
Posted dikeboy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); } }
以上是关于Spring cloud整合Reids 配置多个数据源的主要内容,如果未能解决你的问题,请参考以下文章
(十六) 整合spring cloud云架构 -使用spring cloud Bus刷新配置