博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring-boot-redis-cluster-demo
阅读量:2431 次
发布时间:2019-05-10

本文共 2335 字,大约阅读时间需要 7 分钟。

摘要

Redis在项目中使用频率是很高的,使用的时候经常都是以Redis集群的形式。现整理一下Spring-Boot整合redis cluster最基础配置,方便以后查阅。

依赖包

下面2个依赖是spring-boot集成Redis的必备依赖。

org.springframework.boot
spring-boot-starter
${spring-boot.version}
org.springframework.boot
spring-boot-starter-redis
1.4.4.RELEASE

如果启用spring-boot单元测试,还需要加入下面的依赖。

org.springframework.boot
spring-boot-starter-test
${spring-boot.version}
test

配置

application.yml配置Redis集群节点信息

spring:  redis:    cluster:      nodes:        - redis1.itclj.com:7000        - redis1.itclj.com:7001        - redis2.itclj.com:7002        - redis2.itclj.com:7003        - redis3.itclj.com:7004        - redis3.itclj.com:7005

初始化

spring-boot默认都采用注解方式初始化bean。

首先建一个redis集群配置bean,从配置文件中读取配置到配置bean里面。
其次建一个redis Cluster初始化配置bean,用于初始化Redis Cluster。

集群配置Bean

由于复杂配置项,如数组不能通过@Value注解直接读取配置项,所有只能采用新建配置Bean通过@ConfigurationProperties注解读取。

@Configuration@ConfigurationProperties(prefix = "spring.redis.cluster")public class RedisClusterProperties {
//集群节点 private List
nodes=new ArrayList<>(); public List
getNodes() { return nodes; } public void setNodes(List
nodes) { this.nodes = nodes; }}

初始化RedisCluster

@Configuration@ConditionalOnClass(RedisClusterConfig.class)@EnableConfigurationProperties(RedisClusterProperties.class)public class RedisClusterConfig {
@Resource private RedisClusterProperties redisClusterProperties; @Bean public JedisCluster redisCluster(){ Set
nodes = new HashSet<>(); for (String node:redisClusterProperties.getNodes()){ String[] parts= StringUtils.split(node,":"); Assert.state(parts.length==2, "redis node shoule be defined as 'host:port', not '" + Arrays.toString(parts) + "'"); nodes.add(new HostAndPort(parts[0], Integer.valueOf(parts[1]))); } return new JedisCluster(nodes); }}

测试

@RunWith(SpringRunner.class)@SpringBootTestpublic class RedisTest {
@Autowired private JedisCluster jedisCluster; @Test public void get(){ System.out.println("=============="+jedisCluster.get("youqian-spread-sync-to-mysql-date")); }}

原文地址:

项目地址:

转载地址:http://iuvmb.baihongyu.com/

你可能感兴趣的文章
阿里巴巴架构师:十问业务中台和我的答案
查看>>
华为云发布三类六款计算实例 打造更强云端计算能力
查看>>
PHP 语言地位遭受挑战,PHP 程序员路在何方?
查看>>
PostgreSQL好评如潮,它是如何做到的?
查看>>
2017码云群英会,共享开源技术盛宴
查看>>
看完这份参会指南,Get 2017 OSC 年终盛典正确参会姿势!
查看>>
盛食厉兵 中科天玑挖掘大数据价值助力行业数字化转型
查看>>
白鹭引擎正式支持微信小游戏开发
查看>>
2018年,你所不知道的Jira!
查看>>
2017年,阿里巴巴开源的那些事
查看>>
推动边缘计算的七项核心技术
查看>>
边缘计算精华问答 | 边缘计算需要IaaS、PaaS、SaaS等服务能力吗?
查看>>
Spark精华问答 | Spark 会替代Hadoop 吗?
查看>>
豆瓣已玩烂,来爬点有逼格的 ——IMDB 电影提升你的品位
查看>>
一部刷爆朋友圈的5G短片,看完才知道5G多暖多重要!
查看>>
SDN精华问答 | SDN可以做什么?
查看>>
云评测 | 开发者最有用的开源云监控工具有哪些呢? 这7款神器总有一款适合你!...
查看>>
小团队的微服务之路
查看>>
K8S精华问答 | Kubernetes集群不能正常工作,难道是防火墙问题?
查看>>
5G精华问答 | 什么是5G?5G与LTE有什么关系?
查看>>