1. 程式人生 > >spring-boot-redis-cluster-demo

spring-boot-redis-cluster-demo

摘要

Redis在專案中使用頻率是很高的,使用的時候經常都是以Redis叢集的形式。現整理一下Spring-Boot整合redis cluster最基礎配置,方便以後查閱。

依賴包

下面2個依賴是spring-boot整合Redis的必備依賴。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>${spring-boot.version}</version
>
</dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.4.4.RELEASE</version> </dependency>

如果啟用spring-boot單元測試,還需要加入下面的依賴。

<dependency>
    <groupId
>
org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>${spring-boot.version}</version> <scope>test</scope> </dependency>

配置

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<String> nodes=new ArrayList<>();

    public List<String> getNodes() {
        return nodes;
    }

    public void setNodes(List<String> nodes) {
        this.nodes = nodes;
    }
}

初始化RedisCluster

@Configuration
@ConditionalOnClass(RedisClusterConfig.class)
@EnableConfigurationProperties(RedisClusterProperties.class)
public class RedisClusterConfig {

    @Resource
    private RedisClusterProperties redisClusterProperties;

    @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);
    }

}

測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    private JedisCluster jedisCluster;

    @Test
    public void get(){
       System.out.println("=============="+jedisCluster.get("youqian-spread-sync-to-mysql-date"));
    }

}