一、前言
spring-boot項目整合redis很常見,Redis 一般上生產的時候都是以集群模式部署,也就是redis cluster。本demo以最干凈簡潔的方式整合spring-boot和redis cluster,方便需要的同學查閱。
二、項目結構

三、整合過程
本工程采用maven管理依賴,程序主框架采用spring-boot。
maven核心依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>
工程主要包括4部分:
- redis cluster配置類
- spring-boot主文件
- spring-boot配置文件
- 單元測試
redis cluster配置類
- RedisClusterProperties
把配置文件application.yml中redis cluster的配置項,映射到java對象中,方便直接使用
@Configuration
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterProperties {
//集群節點
private List<String> nodes=new ArrayList<>();
public List<String> getNodes() {
return nodes;
}
public void setNodes(List<String> nodes) {
this.nodes = nodes;
}
}
- RedisClusterConfig
redis cluster核心配置類,啟動spring-boot項目的時候在這里實例化JedisCluster對象
@Bean
public JedisCluster redisCluster(){
Set<HostAndPort> 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);
}
spring-boot主文件
- ItcljApplication
spring-boot工程啟動文件,里面就是main方法,用於啟動項目,項目啟動過程中會自動掃描com.itclj包下的所有類,掃描到RedisClusterConfig類的時候,由於public JedisCluster redisCluster()方法加了@Bean注解,spring會自動執行該方法實例化一個JedisCluster對象放入spring上下文,以后需要使用的時候在需要的類直接自動注入即可。
spring-boot配置文件
- application.yml
配置redis集群服務器地址
spring:
redis:
cluster:
nodes:
- redis1.msxf.lotest:7000
- redis1.msxf.lotest:7001
- redis2.msxf.lotest:7002
- redis2.msxf.lotest:7003
- redis3.msxf.lotest:7004
- redis3.msxf.lotest:7005
單元測試
- RedisTest
采用junit作為單元測試工具,啟動單元測試spring-boot會初始化整個項目,構建上下文,在這個過程中JedisCluster也將被實例化放入spring-boot上下文中,在單元測試類中直接使用,調用其get()方法獲取redis集群的數據。
在正式寫業務邏輯的時候用法也是一樣的,在需要的類里面自動注入JedisCluster即可,然后直接使用,進行redis的增刪改查。
@Autowired
private JedisCluster jedisCluster;
@Test
public void get(){
System.out.println("=============="+jedisCluster.get("youqian-spread-sync-to-mysql-date"));
}
四、運行代碼
在idea里面,進入單元測試類RedisTest選中get()方法,有單擊鼠標,run即可。然后在控制台輸出從redis cluster中獲取到的數據了。
spring-boot-redis-cluster簡單整合例子
注:本文著作權歸作者,由demo大師代發,拒絕轉載,轉載需要作者授權
