SrpingBoot 2.x 整合 Redis (集群版)

废话不多说。直接开始

1,pom


        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
    

2,配置文件

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

java代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object object, Long time) {
        // 存放String 类型
        if (object instanceof String) {
            setString(key, object);
        }
        // 存放 set类型
        if (object instanceof Set) {
            setSet(key, object);
        }
        // 设置有效期 以秒为单位
        stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    public void setString(String key, Object object) {
        // 如果是String 类型
        String value = (String) object;
        stringRedisTemplate.opsForValue().set(key, value);
    }

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

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

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@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("/getString")
    public String getString(String key) {
        return redisService.getString(key);
    }

    @RequestMapping("/setSet")
    public String setSet() {
        Set set = new HashSet();
        set.add("zs");
        set.add("ls");
        redisService.setSet("setTest", set);
        return "success";
    }
}

测试

success

 

你可能感兴趣的:(redis)