springboot整合redis集群详解

springboot整合redis集群详解(附源码)

该篇文章接上一篇文正:springboot2.0+spring cloud+eureka(分布式项目)项目搭建详细教程(附加源码),本篇文章的内容下面也会有源码(此处不涉及如何搭建redis集群相关教程,请另行百度),请读者放心;

整合流程:

  • 添加redis依赖;
  • 配置文件修改(yml文件中添加redis相关属性信息)
  • 获取redis集群相关对象,并对redis进行操作 ;

以下为详细步骤:

- 第一步:添加redis依赖;
springboot整合redis集群详解

	 <dependency>
	 <!-- springboot的parents依赖中有对版本号的控制,此处不需要添加版本号相关信息 -->
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
  	 </dependency>

- 第二步:yml配置文件信息添加,配置文件中信息的具体含义已经在注释中写清楚;
springboot整合redis集群详解

spring:
  redis:
    cluster:
      #设置key的生存时间,当key过期时,它会被自动删除;
      expire-seconds: 120
      #设置命令的执行时间,如果超过这个时间,则报错;
      command-timeout: 5000
      #设置redis集群的节点信息,其中namenode为域名解析,通过解析域名来获取相应的地址;
      nodes: namenode22:6379,datanode23:6379,datanode24:6379,datanode25:6379,datanode26:6379,datanode27:6379
  • 第三步:编写相关java代码;
    • 1)、读取application.yml配置文件中的属性信息到bean中,并注入到spring容器;
package com.example.springbootdemoconsumer.redisConfig;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author YangPeng
 * @Title: RedisProperties
 * @ProjectName springbootdemo
 * @Description: 使用ConfigurationProperties注解读取yml文件中的字段值,并使用Component注入到spring容器中;
 * @date 2019/4/3-17:52
 */
//依赖注入
@Component
//该注解用于读取配置文件中的属性,其中prefix表示前缀;
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisProperties {
    private int expireSeconds;
    private String nodes;
    private int commandTimeout;

    public int getExpireSeconds() {
        return expireSeconds;
    }

    public void setExpireSeconds(int expireSeconds) {
        this.expireSeconds = expireSeconds;
    }

    public String getNodes() {
        return nodes;
    }

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

    public int getCommandTimeout() {
        return commandTimeout;
    }

    public void setCommandTimeout(int commandTimeout) {
        this.commandTimeout = commandTimeout;
    }

    @Override
    public String toString() {
        return "RedisProperties{" +
                "expireSeconds=" + expireSeconds +
                ", nodes='" + nodes + '\'' +
                ", commandTimeout=" + commandTimeout +
                '}';
    }
}

    • 2)、根据注入的RedisProperties对象来获取JedisCluster对象;
package com.example.springbootdemoconsumer.redisConfig;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
    * @Title: RedisConfig
    * @ProjectName springbootdemo
    * @Description: TODO
    * @author YangPeng
    * @date 2019/4/3-18:17
    */
@Configuration
public class RedisConfig {

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisCluster getJedisCluster(){
        //获取redis集群的ip及端口号等相关信息;
        String[] serverArray = redisProperties.getNodes().split(",");
        Set<HostAndPort> nodes = new HashSet<>();

        //遍历add到HostAndPort中;
        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        //构建对象并返回;
        return new JedisCluster(nodes, redisProperties.getCommandTimeout());
    }
}

    • 3)、创建一个操作redis集群的接口,并对该接口进行实现,实现类中写了对redis操作的主要的方法;
      接口如下:
package com.example.springbootdemoconsumer.redisConfig;


/**
 * @author YangPeng
 * @Title: JedisClient
 * @ProjectName springbootdemo
 * @Description: TODO
 * @date 2019/4/3-18:29
 */
public interface JedisClient {
    String set(String key, String value);

    String get(String key);

    Boolean exists(String key);

    Long expire(String key, int seconds);

    Long ttl(String key);

    Long incr(String key);

    Long hset(String key, String field, String value);

    String hget(String key, String field);

    Long hdel(String key, String... field);
}

实现类如下:

package com.example.springbootdemoconsumer.service;


import com.example.springbootdemoconsumer.redisConfig.JedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

/**
    * @Title: JedisClientCluster
    * @ProjectName springbootdemo
    * @Description: TODO
    * @author YangPeng
    * @date 2019/4/3-18:30
    */
@Component
public class JedisClientCluster implements JedisClient {
    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public String set(String key, String value) {
        return jedisCluster.set(key, value);
    }

    @Override
    public String get(String key) {
        return jedisCluster.get(key);
    }

    @Override
    public Boolean exists(String key) {
        return jedisCluster.exists(key);
    }

    @Override
    public Long expire(String key, int seconds) {
        return jedisCluster.expire(key, seconds);
    }

    @Override
    public Long ttl(String key) {
        return jedisCluster.ttl(key);
    }

    @Override
    public Long incr(String key) {
        return jedisCluster.incr(key);
    }

    @Override
    public Long hset(String key, String field, String value) {
        return jedisCluster.hset(key, field, value);
    }

    @Override
    public String hget(String key, String field) {
        return jedisCluster.hget(key, field);
    }

    @Override
    public Long hdel(String key, String... field) {
        return jedisCluster.hdel(key, field);
    }
}

  • 第四步:编写Controller,进行测试;
package com.example.springbootdemoconsumer.controller;


import com.example.springbootdemoconsumer.redisConfig.RedisConfig;
import com.example.springbootdemoconsumer.redisConfig.RedisProperties;
import com.example.springbootdemoconsumer.service.JedisClientCluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
    * @Title: RedisController
    * @ProjectName springbootdemo
    * @Description: TODO
    * @author YangPeng
    * @date 2019/4/3-17:55
    */
@RestController
public class RedisController {
    @Autowired
    private RedisProperties redisProperties;

    @Autowired
    private RedisConfig redisConfig;

    @Autowired
    private JedisClientCluster jedisClientCluster;

    @RequestMapping(value = "getRedisValue")
    public String getRedisValue(){
        System.out.println(redisProperties.toString());
        System.out.println(redisConfig.getJedisCluster().getClusterNodes());
        System.out.println(jedisClientCluster.get("yp"));
        jedisClientCluster.set("12","12");
        System.out.println(jedisClientCluster.get("12"));
        return jedisClientCluster.get("12");
    }
}

输出如下:
springboot整合redis集群详解至此,springboot整合redis集群讲解完毕,如有问题,请留言,谢谢(ps:源码地址:https://github.com/yanpgeng/springbootdemo 该源码中包含springboot+springcloud+fegin等相关内容,后续会对该工程进行持续的完善,比如多数据源,整合jsp、token等相关内容)