springboot2.0 整合 redis-cluster集群

1. 首先引入依赖pom


     org.springframework.boot
     spring-boot-starter-data-redis
     2.0.0.RELEASE
 

2. 编写redis工具类

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 BaseRedisService {

	@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) {
		if(object instanceof String){
			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);
	}

	public void deleteKey(String key){
		stringRedisTemplate.delete(key);
	}

}

3. 配置集群链接信息,在application.yml文件中配置

pring:
  application:
    name: member-server
  redis:
    database: 0
#单机版
#    host: 127.0.0.1
#    port: 6379
#    password: 123456
#      pool:
#        max-idle: 100
#        min-idle: 1
#        max-active: 1000
#        max-wait: -1
#集群版
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 10000
    cluster:
      nodes:
        - 192.168.100.131:6001
        - 192.168.100.131:6002
        - 192.168.100.131:6003
        - 192.168.100.131:6004
        - 192.168.100.131:6005
        - 192.168.100.131:6006

4. 接下来就是如何使用redis了

@RestController
public class DemoImpl  implements DemoInterface {

    @Autowired
    private BaseRedisService baseRedisService;

    @Override
    public void testRedisSet(String key, String value) {
        baseRedisService.setString(key,value);
    }
}

 

你可能感兴趣的:(spring,redis)