写点什么

springboot + redis 多数据源 + jedis 集群模式

作者:try catch
  • 2022-10-14
    江苏
  • 本文字数:3961 字

    阅读完需:约 13 分钟

最近有个项目需要 redis 支持多个集群,网上搜了下,发现有个开源的项目spring-boot-starter-dynamic-redis,代码写的挺好,可惜只有单机版的,于是 fork 了他的代码改了下,支持 jedis 集群模式。


新代码昨天已提交给了原作者,还没看到他的回复。今天就先写个博客简单介绍下吧。


支持集群版的项目地址fork from spring-boot-starter-dynamic-redis


客户端集成方式如下。

1.在 pom.xml 中添加如下依赖:

<dependency>    <groupId>com.mk</groupId>    <artifactId>spring-boot-starter-dynamic-redis</artifactId>    <!-- 单机版 1.0-SNAPSHOT-->    <!-- <version>1.0-SNAPSHOT</version> -->        <!-- 集群版 1.1-SNAPSHOT-->    <version>1.1-SNAPSHOT</version></dependency>
复制代码

2.在 yml 配置文件中添加如下配置:

dms:  dynamic:    redis:      enabled: true      #是否启用集群版配置      isJedisCluster: true      connection:        # 第一个Redis连接        redis1:          #host单机版填单个ip值; 集群版填ip和端口号,多个用逗号分隔: ip1:port1,ip2:port2,...;           host: 192.168.0.1:6573,192.168.0.2:6573,192.168.0.3:6573          #单机版填端口, 集群版忽略不用填          port: 6379          database: 1          timeout: 3000          jedis:            pool:              max-wait: 3000              max-active: 100              max-idle: 20              min-idle: 0        # 第二个Redis连接        redis2:          host: 127.0.0.1          port: 6379          database: 2          timeout: 3000          jedis:            pool:              max-wait: 3000              max-active: 100              max-idle: 20              min-idle: 0
复制代码

3.在启动类上面添加 @ComponentScan 注解,如下:

//@EnableDynamicRedis //此注解貌似没啥用@SpringBootApplication@ComponentScan({"com.mk.*"})public class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class);    }}
复制代码

4.1 单机版,创建 Redis 配置类,如下:

@Configurationpublic class RedisConfig {
/** * 是否启用jedis集群模式,默认为否 */ @Value("${dms.dynamic.redis.isJedisCluster:false}") private boolean isJedisCluster; @Resource private DynamicRedisProvider dynamicRedisProvider;
@Bean(name = "demo1Redis") public RedisTemplate demo1Redis() { return new StringRedisTemplate(dynamicRedisProvider.loadRedis(isJedisCluster).get("redis1")); }
@Bean(name = "demo2Redis") public RedisTemplate demo2Redis() { return new StringRedisTemplate(dynamicRedisProvider.loadRedis(isJedisCluster).get("redis2")); }}
复制代码

4.2.单机版测试类:

@RestControllerpublic class TestController {    @Resource(name = "demo1Redis")    private StringRedisTemplate demo1Template;
@Resource(name = "demo2Redis") private StringRedisTemplate demo2Template;
@GetMapping("/testRedis") public String testRedis(){ demo1Template.opsForValue().set("testKey", "我存放到Redis下db为1的库"); demo2Template.opsForValue().set("testKey", "我存放到Redis下db为2的库"); return "success"; }}
复制代码

5.1 集群版,创建 Redis 配置类,如下:

@Configuration@ConditionalOnProperty(prefix = DynamicRedisProperties.PREFIX, value = "enabled", matchIfMissing = false)public class CustomerDynamicRedisConfig extends DynamicRedisConfig {    /**     * 是否启用jedis集群模式,默认为否     */    @Value("${dms.dynamic.redis.isJedisCluster:false}")    private boolean isJedisCluster;
/** * 指定序列化方式: key <== String, value <== json */ @Bean(name = RedisHelper.REDIS_1) public RedisTemplate<Object, Object> redis1() { return createRedisTemplate(dynamicRedisProvider.loadRedis(isJedisCluster).get(RedisHelper.REDIS_1)); }
/** * 指定序列化方式: key <== String, value <== String */ @Bean(name = RedisHelper.STR_REDIS_1) public RedisTemplate<String, String> stringRedis1() { return createStringRedisTemplate(dynamicRedisProvider.loadRedis(isJedisCluster).get(RedisHelper.REDIS_1)); }
@Bean(name = RedisHelper.REDIS_2) public RedisTemplate<Object, Object> redis2() { return createRedisTemplate(dynamicRedisProvider.loadRedis(isJedisCluster).get(RedisHelper.REDIS_2)); }
@Bean(name = RedisHelper.STR_REDIS_2) public RedisTemplate<String, String> stringRedis2() { return createStringRedisTemplate(dynamicRedisProvider.loadRedis(isJedisCluster).get(RedisHelper.REDIS_2)); }}
复制代码

5.2. 集群版 RedisHelper 工具类:

/** * 获取对应redis操作的帮助类。 * * @author machunlin@126.com */public class RedisHelper {    private static final Map<String, RedisService> map = new ConcurrentHashMap<>();
public static final String REDIS_1 = "redis1"; public static final String STR_REDIS_1 = "stringRedis1";
public static final String REDIS_2 = "redis2"; public static final String STR_REDIS_2 = "stringRedis2";
/** * redis value值为json序列化 */ public static RedisService getRedis1() { if (map.containsKey(REDIS_1)) { return map.get(REDIS_1); }
RedisService _redisService = new RedisService(); RedisTemplate redisTemplate1 = (RedisTemplate) SpringContextUtil.getBean(REDIS_1); _redisService.setRedisTemplate(redisTemplate1); map.put(REDIS_1, _redisService); return _redisService; }
/** * redis value值为string序列化 */ public static RedisService getStringRedis1() { if (map.containsKey(STR_REDIS_1)) { return map.get(STR_REDIS_1); }
RedisService _redisService = new RedisService(); StringRedisTemplate strRedisTemplate1 = (StringRedisTemplate) SpringContextUtil.getBean(STR_REDIS_1); _redisService.setRedisTemplate(strRedisTemplate1); map.put(STR_REDIS_1, _redisService); return _redisService; }
public static RedisService getRedis2() { if (map.containsKey(REDIS_2)) { return map.get(REDIS_2); }
RedisService _redisService = new RedisService(); RedisTemplate redisTemplate = (RedisTemplate) SpringContextUtil.getBean(REDIS_2); _redisService.setRedisTemplate(redisTemplate); map.put(REDIS_2, _redisService); return _redisService; }
public static RedisService getStringRedis2() { if (map.containsKey(STR_REDIS_2)) { return map.get(STR_REDIS_2); }
RedisService _redisService = new RedisService(); StringRedisTemplate strRedisTemplate1 = (StringRedisTemplate) SpringContextUtil.getBean(STR_REDIS_2); _redisService.setRedisTemplate(strRedisTemplate1); map.put(STR_REDIS_2, _redisService); return _redisService; }
}
复制代码

5.3.集群版测试类

@RestController@RequestMapping(value = "/redis")public class RedisTestController {
@GetMapping(value = "/testSet") public String testSet(String redisName, String key) { RedisService redisService; if ("1".equals(redisName)) { redisService = RedisHelper.getRedis1(); } else if ("2".equals(redisName)) { redisService = RedisHelper.getRedis2(); } else if ("str1".equals(redisName)) { redisService = RedisHelper.getStringRedis1(); } else { throw new IllegalArgumentException("redisName错误"); } redisService.set(key, "hahahah你好你好", 600L); return (String) redisService.get(key); }
@GetMapping(value = "/testGet") public String testGet(String redisName, String key) { RedisService redisService; if ("1".equals(redisName)) { redisService = RedisHelper.getRedis1(); } else if ("2".equals(redisName)) { redisService = RedisHelper.getRedis2(); } else if ("str1".equals(redisName)) { redisService = RedisHelper.getStringRedis1(); } else { throw new IllegalArgumentException("redisName错误"); } return (String) redisService.get(key); }}
复制代码


再次感谢原作者开源贡献的代码!


原项目(单机版)集群版


发布于: 刚刚阅读数: 4
用户头像

try catch

关注

还未添加个人签名 2012-07-23 加入

百尺竿头,更进一步

评论

发布
暂无评论
springboot + redis多数据源 + jedis集群模式_redis_try catch_InfoQ写作社区