当前位置:   article > 正文

SpringBoot实践之---集成Redis_spring.redis.pool.testonborrow

spring.redis.pool.testonborrow

1.引入依赖

build.gradle中加入

  1. //redis
  2. compile('org.springframework.data:spring-data-redis:1.8.0.RELEASE')
  3. compile('redis.clients:jedis:2.9.0')

2.配置Redis参数

application.properties中加入

  1. #redis
  2. spring.redis.host=172.16.3.72
  3. spring.redis.port=6379
  4. spring.redis.password=
  5. spring.redis.timeout=5000
  6. spring.redis.pool.max-active=1500
  7. spring.redis.pool.max-idle=20
  8. spring.redis.pool.max-wait=5
  9. spring.redis.pool.testOnBorrow=true
  10. spring.redis.pool.testOnReturn=true

3.编写Redis操作工具类

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.my.web.enums.ERedisDomain;
  3. import com.my.web.exception.RedisException;
  4. import redis.clients.jedis.Jedis;
  5. import redis.clients.jedis.JedisPool;
  6. import redis.clients.jedis.JedisPoolConfig;
  7. import java.util.*;
  8. /**
  9. * Description: 该类主要用于提供操作Redis连接池缓存的工具
  10. **/
  11. public class RedisUtils {
  12. /** jedis连接池 */
  13. private static JedisPool pool;
  14. /**
  15. * 初始化redis连接
  16. */
  17. static {
  18. if (pool == null) {
  19. // 创建jedis池配置实例
  20. JedisPoolConfig config = new JedisPoolConfig();
  21. String hostIP = PropertyReaderUtils.getProValue("spring.redis.host"); //Redis主机IP
  22. Integer hostPort = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.port")); //Redis主机端口
  23. Integer maxActive = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.max-active"));
  24. Integer maxIdle = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.max-idle"));
  25. Long maxWait = Long.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.max-wait"));
  26. Boolean testOnBorrow = Boolean.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.testOnBorrow"));
  27. Boolean testOnReturn = Boolean.valueOf(PropertyReaderUtils.getProValue("spring.redis.pool.testOnReturn"));
  28. int timeout = Integer.valueOf(PropertyReaderUtils.getProValue("spring.redis.timeout"));
  29. //设置池配置项值
  30. config.setMaxTotal(maxActive);
  31. config.setMaxIdle(maxIdle);
  32. config.setMaxWaitMillis(maxWait);
  33. config.setTestOnBorrow(testOnBorrow);
  34. config.setTestOnReturn(testOnReturn);
  35. //根据配置实例化jedis池
  36. pool = new JedisPool(config, hostIP, hostPort, timeout);
  37. }
  38. }
  39. /**
  40. * 添加单个Redis缓存
  41. *
  42. * @param domain Redis分组
  43. * @param key Redis的组内key
  44. * @param value Redis的组内value
  45. * @return boolean 是否添加成功
  46. */
  47. public static boolean save(ERedisDomain domain, String key, Object value) {
  48. Jedis jedis = null;
  49. long result = 0l;
  50. try {
  51. jedis = getJedis();
  52. result = jedis.hset(domain.getKey(), key, JSONObject.toJSONString(value));
  53. } catch (Exception e) {
  54. throw new RedisException("unable to save key " + key + " in domain " + domain.getKey(), e);
  55. } finally {
  56. if (null != jedis)
  57. jedis.close(); // 释放资源还给连接池
  58. }
  59. return (result == 1) ? true : false;
  60. }
  61. /**
  62. * 添加单个Redis缓存
  63. *
  64. * @param domain Redis分组
  65. * @param key Redis的组内key
  66. * @param valueJson Redis的组内value(JSON格式)
  67. * @return boolean 是否添加成功
  68. */
  69. public static boolean save(ERedisDomain domain, String key, String valueJson) {
  70. Jedis jedis = null;
  71. long result = 0l;
  72. try {
  73. jedis = getJedis();
  74. result = jedis.hset(domain.getKey(), key, valueJson);
  75. } catch (Exception e) {
  76. throw new RedisException("unable to save key " + key + " in domain " + domain.getKey(), e);
  77. } finally {
  78. close(jedis);// 释放资源还给连接池
  79. }
  80. return (result == 1) ? true : false;
  81. }
  82. /**
  83. * 批量添加Redis缓存
  84. *
  85. * @param domain Redis分组
  86. * @param data Redis缓存数据
  87. * @return boolean 是否添加成功
  88. */
  89. public static boolean batchSave(ERedisDomain domain, Map<String, Object> data) {
  90. Jedis jedis = null;
  91. String result = "fail";
  92. try {
  93. jedis = getJedis();
  94. Map<String, String> jsonData = new HashMap<>(); //json格式的数据
  95. for (String key : data.keySet()) {
  96. jsonData.put(key, JSONObject.toJSONString(data.get(key)));
  97. }
  98. result = jedis.hmset(domain.getKey(), jsonData);
  99. } catch (Exception e) {
  100. throw new RedisException("unable to batch save keys " + data.keySet() + " in domain " + domain.getKey(), e);
  101. } finally {
  102. close(jedis);// 释放资源还给连接池
  103. }
  104. return ("OK".equalsIgnoreCase(result)) ? true : false;
  105. }
  106. /**
  107. * 批量添加Redis缓存
  108. *
  109. * @param domain Redis分组
  110. * @param data Redis缓存数据(值为json格式)
  111. * @return boolean 是否添加成功
  112. */
  113. public static boolean batchSaveJson(ERedisDomain domain, Map<String, String> data) {
  114. Jedis jedis = null;
  115. String result = "fail";
  116. try {
  117. jedis = getJedis();
  118. result = jedis.hmset(domain.getKey(), data);
  119. } catch (Exception e) {
  120. throw new RedisException("unable to batch save keys " + data.keySet() + " in domain " + domain.getKey(), e);
  121. } finally {
  122. close(jedis);// 释放资源还给连接池
  123. }
  124. return ("OK".equalsIgnoreCase(result)) ? true : false;
  125. }
  126. /**
  127. * 获取指定Redis组内的所有缓存数据
  128. *
  129. * @param domain Redis分组
  130. * @return Map 缓存数据,值为json格式
  131. */
  132. public static Map<String, String> get(ERedisDomain domain) {
  133. Jedis jedis = null;
  134. Map<String, String> maps = null;
  135. try {
  136. jedis = getJedis();
  137. maps = jedis.hgetAll(domain.getKey());
  138. } catch (Exception e) {
  139. throw new RedisException("unable to get data from domain " + domain.getKey(), e);
  140. } finally {
  141. close(jedis);// 释放资源还给连接池
  142. }
  143. return maps;
  144. }
  145. /**
  146. * 获取指定Redis组内的所有缓存数据
  147. *
  148. * @param domain Redis分组
  149. * @param clazz 缓存对象的类型
  150. * @return Map 缓存数据
  151. */
  152. public static <T> Map<String, T> get(ERedisDomain domain, Class<T> clazz) {
  153. Jedis jedis = null;
  154. Map<String, T> resultMap = new HashMap<>(); //初始化返回结果
  155. try {
  156. jedis = getJedis();
  157. Map<String, String> data = jedis.hgetAll(domain.getKey()); //json格式的缓存结果
  158. for (String key : data.keySet()) {
  159. JSONObject jsonCacheObj = JSONObject.parseObject(data.get(key));
  160. T cacheData = JSONObject.toJavaObject(jsonCacheObj, clazz);
  161. resultMap.put(key, cacheData);
  162. }
  163. } catch (Exception e) {
  164. throw new RedisException("unable to get data from domain " + domain.getKey(), e);
  165. } finally {
  166. close(jedis);// 释放资源还给连接池
  167. }
  168. return resultMap;
  169. }
  170. /**
  171. * 获取单个缓存对象
  172. *
  173. * @param domain Redis分组
  174. * @param key 缓存对象的key
  175. * @return String json格式的缓存对象
  176. */
  177. public static String get(ERedisDomain domain, String key) {
  178. Jedis jedis = null;
  179. String retureValue = null;
  180. try {
  181. jedis = getJedis();
  182. retureValue = jedis.hget(domain.getKey(), key);
  183. } catch (Exception e) {
  184. throw new RedisException("unable to get key " + key + " in domain " + domain.getKey(), e);
  185. } finally {
  186. close(jedis);// 释放资源还给连接池
  187. }
  188. return retureValue;
  189. }
  190. /**
  191. * 获取单个缓存对象
  192. *
  193. * @param domain Redis分组
  194. * @param key 缓存对象的key
  195. * @param clazz 缓存对象的类型
  196. * @return T 缓存对象
  197. */
  198. public static <T> T get(ERedisDomain domain, String key, Class<T> clazz) {
  199. Jedis jedis = null;
  200. T retureObj = null;
  201. try {
  202. jedis = getJedis();
  203. String jsonData = jedis.hget(domain.getKey(), key);
  204. JSONObject jsonCacheObj = JSONObject.parseObject(jsonData);
  205. retureObj = JSONObject.toJavaObject(jsonCacheObj, clazz);
  206. } catch (Exception e) {
  207. throw new RedisException("unable to get key " + key + " in domain " + domain.getKey(), e);
  208. } finally {
  209. close(jedis);// 释放资源还给连接池
  210. }
  211. return retureObj;
  212. }
  213. /**
  214. * 删除给定Redis分组的所有缓存
  215. *
  216. * @param domain Redis分组
  217. * @return boolean 是否删除成功
  218. */
  219. public static boolean delete(ERedisDomain domain) {
  220. Jedis jedis = null;
  221. long result = 0l;
  222. try {
  223. jedis = getJedis();
  224. result = jedis.del(domain.getKey());
  225. } catch (Exception e) {
  226. throw new RedisException("unable to delete data in domain " + domain.getKey(), e);
  227. } finally {
  228. close(jedis);// 释放资源还给连接池
  229. }
  230. return (result == 1) ? true : false;
  231. }
  232. /**
  233. * 删除缓存
  234. *
  235. * @param domain 缓存所属分组
  236. * @param keys 缓存对象的key
  237. * @return boolean 是否删除成功
  238. */
  239. public static boolean delete(ERedisDomain domain, String... keys) {
  240. Jedis jedis = null;
  241. long result = 0l;
  242. try {
  243. jedis = getJedis();
  244. result = jedis.hdel(domain.getKey(), keys);
  245. } catch (Exception e) {
  246. throw new RedisException("unable to delete keys " + keys + " in domain " + domain.getKey(), e);
  247. } finally {
  248. close(jedis);// 释放资源还给连接池
  249. }
  250. return (result == 1) ? true : false;
  251. }
  252. /**
  253. * 获取给定分组的所有Redis缓存对象
  254. *
  255. * @param domain Redis分组
  256. * @return List json格式的缓存对象列表
  257. */
  258. public static List<String> getValues(ERedisDomain domain) {
  259. Jedis jedis = null;
  260. List<String> retureList = null;
  261. try {
  262. jedis = getJedis();
  263. retureList = jedis.hvals(domain.getKey());
  264. } catch (Exception e) {
  265. throw new RedisException("unable to delete data in domain " + domain.getKey(), e);
  266. } finally {
  267. close(jedis);// 释放资源还给连接池
  268. }
  269. return retureList;
  270. }
  271. /**
  272. * 获取给定分组的所有Redis缓存对象
  273. *
  274. * @param domain Redis分组
  275. * @param clazz 缓存对象类型
  276. * @return List 缓存对象列表
  277. */
  278. public static <T> List<T> getValues(ERedisDomain domain, Class<T> clazz) {
  279. Jedis jedis = null;
  280. List<T> result = new ArrayList<>(); //初始化返回结果
  281. try {
  282. jedis = getJedis();
  283. List<String> cacheObjs = jedis.hvals(domain.getKey());
  284. for (String cache : cacheObjs) {
  285. JSONObject jsonCacheObj = JSONObject.parseObject(cache);
  286. result.add(JSONObject.toJavaObject(jsonCacheObj, clazz));
  287. }
  288. } catch (Exception e) {
  289. throw new RedisException("unable to get data in domain " + domain.getKey(), e);
  290. } finally {
  291. close(jedis);// 释放资源还给连接池
  292. }
  293. return result;
  294. }
  295. /**
  296. * 获取给定分组的所有Redis缓存key
  297. *
  298. * @param domain Redis分组
  299. * @return Set 缓存key集
  300. */
  301. public static Set<String> getKeys(ERedisDomain domain) {
  302. Jedis jedis = null;
  303. Set<String> retureSet = null;
  304. try {
  305. jedis = getJedis();
  306. retureSet = jedis.hkeys(domain.getKey());
  307. } catch (Exception e) {
  308. throw new RedisException("unable to get keys in domain " + domain.getKey(), e);
  309. } finally {
  310. close(jedis);// 释放资源还给连接池
  311. }
  312. return retureSet;
  313. }
  314. /**
  315. * 获取Jedis实例
  316. *
  317. * @return
  318. */
  319. private synchronized static Jedis getJedis() {
  320. if (pool != null) {
  321. return pool.getResource();
  322. } else {
  323. return null;
  324. }
  325. }
  326. /**
  327. * 释放jedis资源
  328. *
  329. * @param jedis
  330. */
  331. private static void close(final Jedis jedis) {
  332. if (jedis != null) {
  333. jedis.close();
  334. }
  335. }
  336. }

4.实际使用

  1. //取值
  2. Set<String> loginTokens = RedisUtils.getKeys(ERedisDomain.TOKEN_LOGIN_USER);
  3. //存值
  4. RedisUtils.save(ERedisDomain.USER_REQUEST_TIME, userID, currentTimeMillis);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/160076
推荐阅读
相关标签
  

闽ICP备14008679号