您的位置:首页 > 数据库 > Redis

SpringBoot实践之---集成Redis

2018-02-12 11:15 716 查看

1.引入依赖

build.gradle中加入 //redis
compile('org.springframework.data:spring-data-redis:1.8.0.RELEASE')
compile('redis.clients:jedis:2.9.0')

2.配置Redis参数

application.properties中加入#redis
spring.redis.host=172.16.3.72
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=5000
spring.redis.pool.max-active=1500
spring.redis.pool.max-idle=20
spring.redis.pool.max-wait=5
spring.redis.pool.testOnBorrow=true
spring.redis.pool.testOnReturn=true

3.编写Redis操作工具类

import com.alibaba.fastjson.JSONObject;
import com.my.web.enums.ERedisDomain;
import com.my.web.exception.RedisException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.*;

/**
* Description: 该类主要用于提供操作Redis连接池缓存的工具
**/
public class RedisUtils {

/** jedis连接池 */
private static JedisPool pool;

/**
* 初始化redis连接
*/
static  {
if (pool == null) {
// 创建jedis池配置实例
JedisPoolConfig config = new JedisPoolConfig();
String hostIP = PropertyReaderUtils.getProValue("spring.redis.host"); //Redis主机IP
Integer hostPort = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.port")); //Redis主机端口
Integer maxActive = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.max-active"));
Integer maxIdle = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.max-idle"));
Long maxWait = Long.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.max-wait"));
Boolean testOnBorrow = Boolean.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.testOnBorrow"));
Boolean testOnReturn = Boolean.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.testOnReturn"));
int timeout = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.timeout"));
//设置池配置项值
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdle);
config.setMaxWaitMillis(maxWait);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
//根据配置实例化jedis池
pool = new JedisPool(config, hostIP, hostPort, timeout);
}
}

/**
* 添加单个Redis缓存
*
* @param domain Redis分组
* @param key Redis的组内key
* @param value Redis的组内value
* @return boolean 是否添加成功
*/
public static boolean save(ERedisDomain domain, String key, Object value) {
Jedis jedis = null;
long result = 0l;
try {
jedis = getJedis();
result = jedis.hset(domain.getKey(), key, JSONObject.toJSONString(value));
} catch (Exception e) {
throw new RedisException("unable to save key " + key + " in domain " + domain.getKey(), e);
} finally {
if (null != jedis)
jedis.close(); // 释放资源还给连接池
}
return (result == 1) ? true : false;
}

/**
* 添加单个Redis缓存
*
* @param domain Redis分组
* @param key Redis的组内key
* @param valueJson Redis的组内value(JSON格式)
* @return boolean 是否添加成功
*/
public static boolean save(ERedisDomain domain, String key, String valueJson) {
Jedis jedis = null;
long result = 0l;
try {
jedis = getJedis();
result = jedis.hset(domain.getKey(), key, valueJson);
} catch (Exception e) {
throw new RedisException("unable to save key " + key + " in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return (result == 1) ? true : false;
}

/**
* 批量添加Redis缓存
*
* @param domain Redis分组
* @param data Redis缓存数据
* @return boolean 是否添加成功
*/
public static boolean batchSave(ERedisDomain domain, Map<String, Object> data) {
Jedis jedis = null;
String result = "fail";
try {
jedis = getJedis();
Map<String, String> jsonData = new HashMap<>(); //json格式的数据
for (String key : data.keySet()) {
jsonData.put(key, JSONObject.toJSONString(data.get(key)));
}
result = jedis.hmset(domain.getKey(), jsonData);
} catch (Exception e) {
throw new RedisException("unable to batch save keys " + data.keySet() + " in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return ("OK".equalsIgnoreCase(result)) ? true : false;
}

/**
* 批量添加Redis缓存
*
* @param domain Redis分组
* @param data Redis缓存数据(值为json格式)
* @return boolean 是否添加成功
*/
public static boolean batchSaveJson(ERedisDomain domain, Map<String, String> data) {
Jedis jedis = null;
String result = "fail";
try {
jedis = getJedis();
result = jedis.hmset(domain.getKey(), data);
} catch (Exception e) {
throw new RedisException("unable to batch save keys " + data.keySet() + " in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return ("OK".equalsIgnoreCase(result)) ? true : false;
}

/**
* 获取指定Redis组内的所有缓存数据
*
* @param domain Redis分组
* @return Map 缓存数据,值为json格式
*/
public static Map<String, String> get(ERedisDomain domain) {
Jedis jedis = null;
Map<String, String> maps = null;
try {
jedis = getJedis();
maps = jedis.hgetAll(domain.getKey());
} catch (Exception e) {
throw new RedisException("unable to get data from domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return maps;
}

/**
* 获取指定Redis组内的所有缓存数据
*
* @param domain Redis分组
* @param clazz 缓存对象的类型
* @return Map 缓存数据
*/
public static <T> Map<String, T> get(ERedisDomain domain, Class<T> clazz) {
Jedis jedis = null;
Map<String, T> resultMap = new HashMap<>(); //初始化返回结果
try {
jedis = getJedis();
Map<String, String> data = jedis.hgetAll(domain.getKey()); //json格式的缓存结果
for (String key : data.keySet()) {
JSONObject jsonCacheObj = JSONObject.parseObject(data.get(key));
T cacheData = JSONObject.toJavaObject(jsonCacheObj, clazz);
resultMap.put(key, cacheData);
}
} catch (Exception e) {
throw new RedisException("unable to get data from domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return resultMap;
}

/**
* 获取单个缓存对象
*
* @param domain Redis分组
* @param key 缓存对象的key
* @return String json格式的缓存对象
*/
public static String get(ERedisDomain domain, String key) {
Jedis jedis = null;
String retureValue = null;
try {
jedis = getJedis();
retureValue = jedis.hget(domain.getKey(), key);
} catch (Exception e) {
throw new RedisException("unable to get key " + key + " in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return retureValue;
}

/**
* 获取单个缓存对象
*
* @param domain Redis分组
* @param key 缓存对象的key
* @param clazz 缓存对象的类型
* @return T 缓存对象
*/
public static <T> T get(ERedisDomain domain, String key, Class<T> clazz) {
Jedis jedis = null;
T retureObj = null;
try {
jedis = getJedis();
String jsonData = jedis.hget(domain.getKey(), key);
JSONObject jsonCacheObj = JSONObject.parseObject(jsonData);
retureObj = JSONObject.toJavaObject(jsonCacheObj, clazz);
} catch (Exception e) {
throw new RedisException("unable to get key " + key + " in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return retureObj;
}

/**
* 删除给定Redis分组的所有缓存
*
* @param domain Redis分组
* @return boolean 是否删除成功
*/
public static boolean delete(ERedisDomain domain) {
Jedis jedis = null;
long result = 0l;
try {
jedis = getJedis();
result = jedis.del(domain.getKey());
} catch (Exception e) {
throw new RedisException("unable to delete data in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return (result == 1) ? true : false;
}

/**
* 删除缓存
*
* @param domain 缓存所属分组
* @param keys 缓存对象的key
* @return boolean 是否删除成功
*/
public static boolean delete(ERedisDomain domain, String... keys) {
Jedis jedis = null;
long result = 0l;
try {
jedis = getJedis();
result = jedis.hdel(domain.getKey(), keys);
} catch (Exception e) {
throw new RedisException("unable to delete keys " + keys + " in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return (result == 1) ? true : false;
}

/**
* 获取给定分组的所有Redis缓存对象
*
* @param domain Redis分组
* @return List json格式的缓存对象列表
*/
public static List<String> getValues(ERedisDomain domain) {
Jedis jedis = null;
List<String> retureList = null;
try {
jedis = getJedis();
retureList = jedis.hvals(domain.getKey());
} catch (Exception e) {
throw new RedisException("unable to delete data in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return retureList;
}

/**
* 获取给定分组的所有Redis缓存对象
*
* @param domain Redis分组
* @param clazz 缓存对象类型
* @return List 缓存对象列表
*/
public static <T> List<T> getValues(ERedisDomain domain, Class<T> clazz) {
Jedis jedis = null;
List<T> result = new ArrayList<>(); //初始化返回结果
try {
jedis = getJedis();
List<String> cacheObjs = jedis.hvals(domain.getKey());
for (String cache : cacheObjs) {
JSONObject jsonCacheObj = JSONObject.parseObject(cache);
result.add(JSONObject.toJavaObject(jsonCacheObj, clazz));
}
} catch (Exception e) {
throw new RedisException("unable to get data in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return result;
}

/**
* 获取给定分组的所有Redis缓存key
*
* @param domain Redis分组
* @return Set 缓存key集
*/
public static Set<String> getKeys(ERedisDomain domain) {
Jedis jedis = null;
Set<String> retureSet = null;
try {
jedis = getJedis();
retureSet = jedis.hkeys(domain.getKey());
} catch (Exception e) {
throw new RedisException("unable to get keys in domain " + domain.getKey(), e);
} finally {
close(jedis);// 释放资源还给连接池
}
return retureSet;
}

/**
* 获取Jedis实例
*
* @return
*/
private synchronized static Jedis getJedis() {
if (pool != null) {
return pool.getResource();
} else {
return null;
}
}

/**
* 释放jedis资源
*
* @param jedis
*/
private static void close(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}

4.实际使用

//取值
Set<String> loginTokens = RedisUtils.getKeys(ERedisDomain.TOKEN_LOGIN_USER);
//存值
RedisUtils.save(ERedisDomain.USER_REQUEST_TIME, userID, currentTimeMillis);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: