一,导入相关包
<!-- redisStarter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis 客户端类 jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
二、配置文件
redis:
database: 0
clusterNodes: 10.100.252.70:6383,10.100.252.70:6384,10.100.242.71:6383,10.100.252.71:6384,10.100.252.72:6383,10.100.252.72:6384//redis集群
timeout: 30000
password: welcome
expireSeconds: 120//默认保存时间
commandTimeout: 10000 //过期时间
pool:
maxIdle: 300//最大空闲连接数
maxWait: 30000#获取连接最大等待时间 ms
maxActive: 8#最大连接数
min-idle: 0//最小空闲连接数
三、加载redis配置信息
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
private int expireSeconds;
private String clusterNodes;
private String password;
private int commandTimeout;
public int getExpireSeconds() {
return expireSeconds;
}
public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}
public String getClusterNodes() {
return clusterNodes;
}
public void setClusterNodes(String clusterNodes) {
this.clusterNodes = clusterNodes;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCommandTimeout() {
return commandTimeout;
}
public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
}
四、JedisCluster方式连接集群的配置
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.Set;
/**
* @Author: guoyu
* @Description:
* @Date: Create in 2018/6/14 16:28
*/
@Configuration
public class JedisClusterConfig {
private static final Logger log = LoggerFactory.getLogger(JedisClusterConfig.class);
@Autowired
private RedisProperties redisProperties;
/**
* 注意:
* 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
* @return
*/
@Bean
public JedisCluster getJedisCluster() {
String[] serverArray = redisProperties.getClusterNodes().split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
Set<HostAndPort> nodes = new HashSet<>();
for (String ipPort : serverArray) {
String[] ipPortPair = ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
}
log.info("JedisPool注入成功!");
return new JedisCluster(nodes,redisProperties.getCommandTimeout(),1000,1,redisProperties.getPassword() ,new GenericObjectPoolConfig());//需要密码连接的创建对象方式
}
}
五、对 jedisCluster操作的封装
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.JedisCluster;
@Component
@Service
public class RedisUtil{
private static final Logger LOGGER= LoggerFactory.getLogger(RedisUtil.class);
@Autowired
private JedisCluster jedisCluster;
/**
* 设置缓存
* @param key 缓存key
* @param value 缓存value
*/
public void set(String key, String value) {
jedisCluster.set(key, value);
LOGGER.debug("RedisUtil:set cache key={},value={}", key, value);
}
/**
* 设置缓存对象
* @param key 缓存key
* @param obj 缓存value
*/
public <T> void setObject(String key, T obj , int expireTime) {
jedisCluster.setex(key, expireTime, JSON.toJSONString(obj));
LOGGER.debug("RedisUtil:set cache key={},value={}", key, JSON.toJSONString(obj));
}
/**
* 获取指定key的缓存
* @param key---JSON.parseObject(value, User.class);
*/
public String getObject(String key) {
return jedisCluster.get(key);
}
/**
* 判断当前key值 是否存在
*
* @param key
*/
public boolean hasKey(String key) {
return jedisCluster.exists(key);
}
/**
* 设置缓存,并且自己指定过期时间
* @param key
* @param value
* @param expireTime 过期时间
*/
public void setWithExpireTime( String key, String value, int expireTime) {
jedisCluster.setex(key, expireTime, value);
LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", key, value, expireTime);
}
/**
* 获取指定key的缓存
* @param key
*/
public String get(String key) {
String value = jedisCluster.get(key);
LOGGER.debug("RedisUtil:get cache key={},value={}",key, value);
return value;
}
/**
* 删除指定key的缓存
* @param key
*/
public void delete(String key) {
jedisCluster.del(key);
LOGGER.debug("RedisUtil:delete cache key={}", key);
}
}
六、使用
1、注入
@Autowired
private RedisUtil redisUtil;
2、使用
redisUtil.setObject(verifyCodeFlag,verifyCode, 300);//设置key过期时间,5分钟
log.info("Redis里保存验证码,标识为"+verifyCodeFlag+"验证码为"+verifyCode);
if (!(redisUtil.hasKey(verifyCodeFlag))) {
log.info("验证码过期");
}
String verifyCodeRedis = redisUtil.getObject(verifyCodeFlag).toString().toLowerCase().replace("\"", "");//提取验证码
redisUtil.delete(verifyCodeFlag);//删除验证码