1.引入依赖
在需要使用redis的服务中引入相关依赖。
compile('org.springframework.boot:spring-boot-starter-redis')
compile('redis.clients:jedis:2.9.0')
compile('org.apache.commons:commons-pool2:2.5.0')
compile('org.springframework.boot:spring-boot-configuration-processor:2.0.2.RELEASE')
2.配置文件
spring:
redis:
password: Allways_123
clusterNodes: 10.102.4.153:6279,10.102.4.154:6379,10.102.4.154:6279,10.102.4.151:6479,10.102.4.153:6479,10.102.4.151:6479
expireSeconds: 120
commandTimeout: 10000 #redis操作的超时时间
pool:
#最大连接数
maxActive: 5000
#最大空闲连接数
maxIdle: 30
#最小空闲连接数
minIdle: 5
#获取连接最大等待时间 ms #default -1
maxWait: 3000
#最大尝试连接数
maxAttempts: 1
3.获取配置信息
1.引入依赖
在需要使用redis的服务中引入相关依赖。
compile('org.springframework.boot:spring-boot-starter-redis')
compile('redis.clients:jedis:2.9.0')
compile('org.apache.commons:commons-pool2:2.5.0')
compile('org.springframework.boot:spring-boot-configuration-processor:2.0.2.RELEASE')
2.配置文件
spring:
redis:
password: Allways_123
clusterNodes: 10.102.4.153:6279,10.102.4.154:6379,10.102.4.154:6279,10.102.4.151:6479,10.102.4.153:6479,10.102.4.151:6479
expireSeconds: 120
commandTimeout: 10000 #redis操作的超时时间
pool:
#最大连接数
maxActive: 5000
#最大空闲连接数
maxIdle: 30
#最小空闲连接数
minIdle: 5
#获取连接最大等待时间 ms #default -1
maxWait: 3000
#最大尝试连接数
maxAttempts: 1
3.获取配置信息
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
private int expireSeconds;
private String clusterNodes;
private String password;
private int commandTimeout;
private Map<String,Integer> pool = new HashMap<>();
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;
}
public Map<String, Integer> getPool() {
return pool;
}
public void setPool(Map<String, Integer> pool) {
this.pool = pool;
}
}
4.JedisCluster方式连接集群的配置
@Configuration
public class JedisClusterConfig {
@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())));
}
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(redisProperties.getPool().get("maxActive"));//最大连接数
poolConfig.setMaxIdle(redisProperties.getPool().get("maxIdle"));//最大空闲连接数
poolConfig.setMinIdle(redisProperties.getPool().get("minIdle"));//最小空闲连接数
poolConfig.setMaxWaitMillis(redisProperties.getPool().get("maxWait").longValue());//连接最大等待时间
return new JedisCluster(nodes,redisProperties.getCommandTimeout(),redisProperties.getCommandTimeout(),
redisProperties.getPool().get("maxAttempts"),redisProperties.getPassword() ,poolConfig);//需要密码连接的创建对象方式
}
}
5.redis帮助类
@Component
public class RedisUtil {
@Autowired
private JedisCluster jedisCluster;
/**
* 设置缓存
* @param key 缓存key
* @param value 缓存value
*/
public void set(String key, String value) {
jedisCluster.set(key, value);
}
/**
* 设置缓存,并且自己指定过期时间
* @param key
* @param value
* @param expireTime 过期时间
*/
public void setWithExpireTime( String key, String value, int expireTime) {
jedisCluster.setex(key, expireTime, value);
}
/**
* 获取指定key的缓存
* @param key
*/
public String get(String key) {
String value = jedisCluster.get(key);
return value;
}
/**
* 设置缓存对象
* @param key 缓存key
* @param obj 缓存value
* @param expireTime 过期时间
*/
public <T> void setObject(String key, T obj , int expireTime) {
jedisCluster.setex(key, expireTime, 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);
}
/**
* 删除指定key的缓存
* @param key
*/
public void delete(String key) {
jedisCluster.del(key);
}
}
6.测试
@Autowired
private RedisUtil redisUtil;
@RequestMapping("/redis")
public String findRedis(@RequestBody Map map) {
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
redisUtil.get(entry.getKey().toString());
System.out.println(entry.getKey().toString() + ":" + redisUtil.get(entry.getKey().toString()));
redisUtil.set(entry.getKey().toString(), entry.getValue().toString());
System.out.println(entry.getKey().toString() + ":" + redisUtil.get(entry.getKey().toString()));
}
return "OK";
}
4.JedisCluster方式连接集群的配置
@Configuration
public class JedisClusterConfig {
@Autowired
private RedisProperties redisProperties;
/**
* 返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
*
* @return
*/
@Bean
public JedisCluster getJedisCluster() {
Set<HostAndPort> nodes = new HashSet<>();
List<String> clusterNodes = redisProperties.getClusterNodes();
for (String ipPort : clusterNodes) {
String[] ipPortPair = ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
}
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(redisProperties.getPool().get("maxActive"));//最大连接数
poolConfig.setMaxIdle(redisProperties.getPool().get("maxIdle"));//最大空闲连接数
poolConfig.setMinIdle(redisProperties.getPool().get("minIdle"));//最小空闲连接数
poolConfig.setMaxWaitMillis(redisProperties.getPool().get("maxWait").longValue());//连接最大等待时间
return new JedisCluster(nodes, redisProperties.getCommandTimeout(), redisProperties.getCommandTimeout(),
redisProperties.getPool().get("maxAttempts"), redisProperties.getPassword(), poolConfig);//需要密码连接的创建对象方式
}
}
5.redis帮助类
@Component
public class RedisUtils {
private static String redisCode = "utf-8";
@Autowired
private JedisCluster jedisCluster;
/**
* 设置缓存
*
* @param key 缓存key
* @param value 缓存value
*/
public void set(String key, String value) {
jedisCluster.set(key, value);
}
/**
* 设置缓存,并且自己指定过期时间
*
* @param key
* @param value
* @param expireTime 过期时间
*/
public void setWithExpireTime(String key, String value, int expireTime) {
jedisCluster.setex(key, expireTime, value);
}
/**
* 设置失效时间
*
* @param key
* @param expireTime
*/
public void expire(String key, int expireTime) {
jedisCluster.setex(key, expireTime, jedisCluster.get(key));
}
/**
* 获取指定key的缓存
*
* @param key
*/
public String get(String key) {
String value = jedisCluster.get(key);
return value;
}
//解决redis异常
public String getThrowRedis(String key) {
try {
get(key);
} catch (Exception e) {
return null;
}
return get(key);
}
/**
* 设置缓存对象
*
* @param key 缓存key
* @param obj 缓存value
* @param expireTime 过期时间
*/
public <T> void setObject(String key, T obj, int expireTime) {
jedisCluster.setex(key, expireTime, 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);
}
/**
* 删除指定key的缓存
*
* @param key
*/
public void delete(String key) {
jedisCluster.del(key);
}
/**
* <pre>
* 上锁
* </pre>
*
* @param key
*/
public synchronized void lock(String key) {
if (StringUtils.isBlank(key)) {
return;
}
this.set(key, new Date().toString());
}
/**
* <pre>
* 上锁
* </pre>
*
* @param key
*/
public synchronized void lockWithExpireTime(String key, int seconds) {
if (StringUtils.isBlank(key)) {
return;
}
jedisCluster.setex(key, seconds, new Date().toString());
}
/**
* <pre>
* 判断key是否被锁住了
* </pre>
*
* @param key
* @return
*/
public synchronized Boolean isLock(String key) {
if (StringUtils.isBlank(key)) {
return false;
}
String stringDate = this.get(key);
if (StringUtils.isBlank(stringDate)) {
return false;
}
return true;
}
/**
* <pre>
* 解锁
* </pre>
*
* @param key
*/
public synchronized void unLock(String key) {
if (StringUtils.isBlank(key)) {
return;
}
this.delete(key);
}
/**
* <pre>
* 递增
* </pre>
*
* @param key
* @param by
* @return
*/
public Long incr(String key, Long by) {
//默认原子操作
if (by == null) {
by = 1l;
}
return jedisCluster.incrBy(key, by);
}
/**
* <pre>
*
* </pre>
*
* @param key
* @param value
* @param liveTime
*/
public void set(String key, Object value, Long liveTime) {
try {
jedisCluster.setex(key.getBytes(redisCode), liveTime.intValue(), value.toString().getBytes(redisCode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
6.测试
@Autowired
private RedisUtil redisUtil;
@RequestMapping("/redis")
public String findRedis(@RequestBody Map map) {
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
redisUtil.get(entry.getKey().toString());
System.out.println(entry.getKey().toString() + ":" + redisUtil.get(entry.getKey().toString()));
redisUtil.set(entry.getKey().toString(), entry.getValue().toString());
System.out.println(entry.getKey().toString() + ":" + redisUtil.get(entry.getKey().toString()));
}
return "OK";
}