SpringBoot连接Redis集群案例

一、安装redis集群

可以参考:Redis-cluster集群案例

二、新建SpringBoot项目

1)、导入案例需要的pom依赖

SpringBoot连接Redis集群案例_第1张图片

2)、添加配置

spring:
  redis:
    database: 0
    password: 123456
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 10000
    cluster:
      nodes:
        - 192.168.1.122:9001
        - 192.168.1.122:9002
        - 192.168.1.122:9003
        - 192.168.1.122:9004
        - 192.168.1.122:9005
        - 192.168.1.122:9006

3)、编写测试代码

封装redis:

/** springboot 2.0 整合redis
 * @program: testrediscluster
 * @description:
 * @author: HQ Zheng
 * @create: 2020-04-02 16:56
 */
@Component
public class RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object object, Long time) {
        // 让该方法能够支持多种数据类型存放
        if (object instanceof String) {
            setString(key, object);
        }
        // 如果存放时Set类型
        if (object instanceof Set) {
            setSet(key, object);
        }
        // 设置有效期

        if (time != null) {
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }

    }

    public void setString(String key, Object object) {
        String value = (String) object;
        // 存放string类型
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public void setSet(String key, Object object) {
        Set valueSet = (Set) object;
        for (String string : valueSet) {
            stringRedisTemplate.opsForSet().add(key, string);
        }
    }

    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

}

测试接口:

/**
 * @program: testrediscluster
 * @description: 测试Redis集群
 * @author: HQ Zheng
 * @create: 2020-04-02 16:56
 */
@RestController
public class IndexController {
    @Autowired
    private RedisService redisService;

    @RequestMapping("/setString")
    public String setString(String key, String value) {
        redisService.set(key, value, 60l);
        return "success";
    }

    @RequestMapping("/get")
    public String get(String key) {
        return redisService.getString(key);
    }

}

4)、测试结果

添加测试值key=test100,value=12345

 

获取测试key=test100

整合成功 

你可能感兴趣的:(SpringBoot,SpringCloud)