当前位置:   article > 正文

【Redis】——实战(11)_redis.pool.testonborrow = true redis.pool.testonre

redis.pool.testonborrow = true redis.pool.testonreturn = true

一、资源下载

官网地址(Windows):https://github.com/dmajkic/redis/downloads

官网地址(Linux):https://redis.io/

二、安装

安装教程:http://www.runoob.com/redis/redis-install.html

三、运用

本人使用的是spring集成redis,下面说下步骤

第一步:导入相关依赖

  1. <!--jackson版本号-->
  2. <properties>
  3. <jackson.version>2.7.1</jackson.version>
  4. </properties>
  5. <!-- 映入JSON -->
  6. <dependency>
  7. <groupId>com.fasterxml.jackson.core</groupId>
  8. <artifactId>jackson-core</artifactId>
  9. <version>${jackson.version}</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.fasterxml.jackson.core</groupId>
  13. <artifactId>jackson-databind</artifactId>
  14. <version>${jackson.version}</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>com.fasterxml.jackson.core</groupId>
  18. <artifactId>jackson-annotations</artifactId>
  19. <version>${jackson.version}</version>
  20. </dependency>
  21. <!-- redis依赖 -->
  22. <dependency>
  23. <groupId>org.springframework.data</groupId>
  24. <artifactId>spring-data-redis</artifactId>
  25. <version>1.8.6.RELEASE</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>redis.clients</groupId>
  29. <artifactId>jedis</artifactId>
  30. <version>2.9.0</version>
  31. </dependency>

第二步:相关配置文件

redis.properties

  1. redis.host=192.***.*.**2
  2. redis.port=6379
  3. redis.pwd=123456
  4. redis.database=0
  5. redis.timeout=1000
  6. redis.userPool=true
  7. redis.pool.maxIdle=100
  8. redis.pool.minIdle=10
  9. redis.pool.maxTotal=200
  10. redis.pool.maxWaitMillis=10000
  11. redis.pool.minEvictableIdleTimeMillis=300000
  12. redis.pool.numTestsPerEvictionRun=10
  13. redis.pool.timeBetweenEvictionRunsMillis=30000
  14. redis.pool.testOnBorrow=true
  15. redis.pool.testOnReturn=true
  16. redis.pool.testWhileIdle=true

spring-redis.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:redis="http://www.springframework.org/schema/redis" xmlns:cache="http://www.springframework.org/schema/cache"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/redis
  14. http://www.springframework.org/schema/redis/spring-redis.xsd
  15. http://www.springframework.org/schema/cache
  16. http://www.springframework.org/schema/cache/spring-cache.xsd
  17. ">
  18. <context:property-placeholder order="1" location="classpath:redis.properties" ignore-unresolvable="true"/>
  19. <!-- Redis -->
  20. <!-- 连接池参数 -->
  21. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
  22. <property name="maxIdle" value="${redis.pool.maxIdle}" />
  23. <property name="minIdle" value="${redis.pool.minIdle}" />
  24. <property name="maxTotal" value="${redis.pool.maxTotal}" />
  25. <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
  26. <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"/>
  27. <property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"/>
  28. <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/>
  29. <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
  30. <property name="testOnReturn" value="${redis.pool.testOnReturn}" />
  31. <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/>
  32. </bean>
  33. <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  34. <property name="poolConfig" ref="jedisPoolConfig" />
  35. <property name="hostName" value="${redis.host}" />
  36. <property name="port" value="${redis.port}" />
  37. <property name="password" value="${redis.pwd}" />
  38. <property name="usePool" value="${redis.userPool}" />
  39. <property name="database" value="${redis.database}" />
  40. <property name="timeout" value="${redis.timeout}" />
  41. </bean>
  42. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  43. <property name="connectionFactory" ref="jedisConnectionFactory" />
  44. <!-- 序列化方式 建议key/hashKey采用StringRedisSerializer -->
  45. <property name="keySerializer">
  46. <bean
  47. class="org.springframework.data.redis.serializer.StringRedisSerializer" />
  48. </property>
  49. <property name="valueSerializer">
  50. <bean
  51. class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
  52. </property>
  53. <property name="hashKeySerializer">
  54. <bean
  55. class="org.springframework.data.redis.serializer.StringRedisSerializer" />
  56. </property>
  57. <property name="hashValueSerializer">
  58. <bean
  59. class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
  60. </property>
  61. <!-- 开启REIDS事务支持 -->
  62. <property name="enableTransactionSupport" value="false" />
  63. </bean>
  64. <!-- 对string操作的封装 -->
  65. <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
  66. <constructor-arg ref="jedisConnectionFactory" />
  67. <!-- 开启REIDS事务支持 -->
  68. <property name="enableTransactionSupport" value="false" />
  69. </bean>
  70. </beans>

第三步:编写工具类

CacheUtil

  1. package com.huyue.common.util;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.data.redis.core.StringRedisTemplate;
  6. import java.util.*;
  7. import java.util.concurrent.TimeUnit;
  8. /**
  9. * redis工具类
  10. *
  11. * @author 2019/3/24 23:10
  12. */
  13. public class CacheUtil {
  14. private static final Logger log = LoggerFactory.getLogger(CacheUtil.class);
  15. private static RedisTemplate<String, Object> redisTemplate = CacheContextUtil.getBean("redisTemplate", RedisTemplate.class);
  16. private static StringRedisTemplate stringRedisTemplate = CacheContextUtil.getBean("stringRedisTemplate", StringRedisTemplate.class);
  17. private static String CACHE_PROFIX;
  18. private static boolean CACHE_CLOSED;
  19. public CacheUtil() {
  20. }
  21. private static boolean isEmpty(Object object) {
  22. if (object == null) {
  23. return true;
  24. }
  25. if (object instanceof String) {
  26. String string = object.toString();
  27. if ("".equals(string.trim())) {
  28. return true;
  29. }
  30. return false;
  31. }
  32. if (object instanceof List) {
  33. List<Object> list = (List<Object>) object;
  34. if (list.isEmpty()) {
  35. return true;
  36. }
  37. return false;
  38. }
  39. if (object instanceof Map) {
  40. Map map = (Map) object;
  41. if (map.isEmpty()) {
  42. return true;
  43. }
  44. return false;
  45. }
  46. if (object instanceof Set) {
  47. Set set = (Set) object;
  48. if (set.isEmpty()) {
  49. return true;
  50. }
  51. return false;
  52. }
  53. if (object instanceof Object[]) {
  54. Object[] objects = (Object[]) object;
  55. if (objects.length <= 0) {
  56. return true;
  57. }
  58. return false;
  59. }
  60. return false;
  61. }
  62. /**
  63. * 构建缓存key
  64. *
  65. * @param key
  66. * @return
  67. */
  68. private static String buildKey(String key) {
  69. if (CACHE_PROFIX == null || "".equals(CACHE_PROFIX)) {
  70. return key;
  71. }
  72. return CACHE_PROFIX + ":" + key;
  73. }
  74. /**
  75. * 返回缓存前缀
  76. *
  77. * @return
  78. */
  79. public static String getCacheProfix() {
  80. return CACHE_PROFIX;
  81. }
  82. /**
  83. * 设置缓存前缀
  84. *
  85. * @param cacheProfix
  86. */
  87. public static void setCacheProfix(String cacheProfix) {
  88. if (cacheProfix != null && !"".equals(cacheProfix.trim())) {
  89. CACHE_PROFIX = cacheProfix.trim();
  90. }
  91. }
  92. /**
  93. * 关闭缓存
  94. *
  95. * @return
  96. */
  97. public static boolean close() {
  98. log.info("=====cache closed=====");
  99. CACHE_CLOSED = true;
  100. return true;
  101. }
  102. /**
  103. * 打开缓存
  104. *
  105. * @return
  106. */
  107. public static boolean open() {
  108. log.info("=====cache open=====");
  109. CACHE_CLOSED = false;
  110. return true;
  111. }
  112. /**
  113. * 检查缓存是否开启
  114. *
  115. * @return
  116. */
  117. public static boolean isClose() {
  118. return CACHE_CLOSED;
  119. }
  120. /**
  121. * 判断key值是否存在
  122. *
  123. * @param key
  124. * @return
  125. */
  126. public static boolean hasKey(String key) {
  127. log.info(" haskey key:" + key);
  128. try {
  129. if (isClose() || isEmpty(key)) {
  130. return false;
  131. }
  132. return redisTemplate.hasKey(buildKey(key));
  133. } catch (Exception e) {
  134. log.error(e.getMessage(), e);
  135. }
  136. return false;
  137. }
  138. /**
  139. * 匹配符合正则的key
  140. *
  141. * @param patterKey
  142. * @return
  143. */
  144. public static Set<String> keys(String patterKey) {
  145. log.info("keys key:" + patterKey);
  146. try {
  147. if (isClose() || isEmpty(patterKey)) {
  148. return Collections.emptySet();
  149. }
  150. return redisTemplate.keys(patterKey);
  151. } catch (Exception e) {
  152. log.error(e.getMessage(), e);
  153. }
  154. return Collections.emptySet();
  155. }
  156. /**
  157. * 根据key删除缓存
  158. *
  159. * @param key
  160. * @return
  161. */
  162. public static boolean delete(String... key) {
  163. log.info("delete key:" + key.toString());
  164. try {
  165. if (isClose() || isEmpty(key)) {
  166. return false;
  167. }
  168. Set<String> keySet = new HashSet<String>();
  169. for (String str : key) {
  170. keySet.add(buildKey(str));
  171. }
  172. redisTemplate.delete(keySet);
  173. return true;
  174. } catch (Exception e) {
  175. log.error(e.getMessage(), e);
  176. }
  177. return false;
  178. }
  179. /**
  180. * 根据key删除缓存
  181. *
  182. * @param key
  183. * @return
  184. */
  185. public static boolean delete(String key) {
  186. log.info("delete key:" + key);
  187. try {
  188. if (isClose() || isEmpty(key)) {
  189. return false;
  190. }
  191. redisTemplate.delete(redisTemplate.keys(buildKey(key)));
  192. return true;
  193. } catch (Exception e) {
  194. log.error(e.getMessage(), e);
  195. }
  196. return false;
  197. }
  198. /**
  199. * 删除一组key值
  200. *
  201. * @param keys
  202. * @return
  203. */
  204. public static boolean delete(Set<String> keys) {
  205. log.info("delete key:" + keys.toString());
  206. try {
  207. if (isClose() || isEmpty(keys)) {
  208. return false;
  209. }
  210. Set<String> keySet = new HashSet<String>();
  211. for (String str : keys) {
  212. keySet.add(buildKey(str));
  213. }
  214. redisTemplate.delete(keySet);
  215. return true;
  216. } catch (Exception e) {
  217. log.error(e.getMessage(), e);
  218. }
  219. return false;
  220. }
  221. /**
  222. * 设置过期时间
  223. *
  224. * @param key
  225. * @param seconds
  226. * @return
  227. */
  228. public static boolean setExp(String key, long seconds) {
  229. log.info("setExp key:" + key + " seconds:" + seconds);
  230. try {
  231. if (isClose() || isEmpty(key) || seconds <= 0) {
  232. return false;
  233. }
  234. return redisTemplate.expire(buildKey(key), seconds, TimeUnit.SECONDS);
  235. } catch (Exception e) {
  236. log.error(e.getMessage(), e);
  237. }
  238. return false;
  239. }
  240. /**
  241. * 查询过期时间
  242. *
  243. * @param key
  244. * @return
  245. */
  246. public static Long getExpire(String key) {
  247. log.info(" getExpire key:" + key);
  248. try {
  249. if (isClose() || isEmpty(key)) {
  250. return 0L;
  251. }
  252. return redisTemplate.getExpire(buildKey(key), TimeUnit.SECONDS);
  253. } catch (Exception e) {
  254. log.info(e.getMessage(), e);
  255. }
  256. return 0L;
  257. }
  258. /**
  259. * 缓存存入key—value
  260. *
  261. * @param key
  262. * @param value
  263. * @return
  264. */
  265. public static boolean setString(String key, String value) {
  266. log.info("setString key:" + key + " value:" + value);
  267. try {
  268. if (isClose() || isEmpty(key) || isEmpty(value)) {
  269. return false;
  270. }
  271. stringRedisTemplate.opsForValue().set(key, value);
  272. return true;
  273. } catch (Exception e) {
  274. log.error(e.getMessage(), e);
  275. }
  276. return false;
  277. }
  278. /**
  279. * 缓存存入key—value
  280. *
  281. * @param key
  282. * @param value
  283. * @param seconds
  284. * @return
  285. */
  286. public static boolean setString(String key, String value, long seconds) {
  287. log.info("setString key:" + key + " value:" + value + " seconds:" + seconds);
  288. try {
  289. if (isClose() || isEmpty(key) || isEmpty(value)) {
  290. return false;
  291. }
  292. stringRedisTemplate.opsForValue().set(key, value, seconds);
  293. return true;
  294. } catch (Exception e) {
  295. log.error(e.getMessage(), e);
  296. }
  297. return false;
  298. }
  299. /**
  300. * 根据key取出String value
  301. *
  302. * @param key
  303. * @return
  304. */
  305. public static String getString(String key) {
  306. log.info("getString key:" + key);
  307. try {
  308. if (isClose() || isEmpty(key)) {
  309. return null;
  310. }
  311. return stringRedisTemplate.opsForValue().get(key);
  312. } catch (Exception e) {
  313. log.error(e.getMessage(), e);
  314. }
  315. return null;
  316. }
  317. /**
  318. * 去的缓存中的最大值并+1
  319. *
  320. * @param key 缓存key值
  321. * @return long 缓存中的最大值+1
  322. */
  323. public static long incr(String key) {
  324. log.debug(" incr key :{}", key);
  325. try {
  326. if (isClose() || isEmpty(key)) {
  327. return 0;
  328. }
  329. key = buildKey(key);
  330. return redisTemplate.opsForValue().increment(key, 1);
  331. } catch (Exception e) {
  332. log.error(e.getMessage(), e);
  333. }
  334. return 0;
  335. }
  336. /**
  337. * 缓存中存入序列化的Object对象
  338. *
  339. * @param key 缓存key
  340. * @param obj 存入的序列化对象
  341. * @return true:成功 false:失败
  342. */
  343. public static boolean set(String key, Object obj) {
  344. log.debug(" set key :{}, value:{}", key, obj);
  345. try {
  346. if (isClose() || isEmpty(key) || isEmpty(obj)) {
  347. return false;
  348. }
  349. key = buildKey(key);
  350. redisTemplate.opsForValue().set(key, obj);
  351. } catch (Exception e) {
  352. log.error(e.getMessage(), e);
  353. }
  354. return false;
  355. }
  356. /**
  357. * 缓存中存入序列化的Object对象
  358. *
  359. * @param key 缓存key
  360. * @param obj 存入的序列化对象
  361. * @return true:成功 false:失败
  362. */
  363. public static boolean setObj(String key, Object obj, long seconds) {
  364. log.debug(" set key :{}, value:{}, seconds:{}", key, obj, seconds);
  365. try {
  366. if (isClose() || isEmpty(key) || isEmpty(obj)) {
  367. return false;
  368. }
  369. key = buildKey(key);
  370. redisTemplate.opsForValue().set(key, obj);
  371. if (seconds > 0) {
  372. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
  373. }
  374. return true;
  375. } catch (Exception e) {
  376. log.error(e.getMessage(), e);
  377. }
  378. return false;
  379. }
  380. /**
  381. * 取出缓存中存储的序列化对象
  382. *
  383. * @param key 缓存key
  384. * @param clazz 对象类
  385. * @return <T> 序列化对象
  386. */
  387. public static <T> T getObj(String key, Class<T> clazz) {
  388. log.debug(" get key :{}", key);
  389. try {
  390. if (isClose() || isEmpty(key)) {
  391. return null;
  392. }
  393. key = buildKey(key);
  394. return (T) redisTemplate.opsForValue().get(key);
  395. } catch (Exception e) {
  396. log.error(e.getMessage(), e);
  397. }
  398. return null;
  399. }
  400. /**
  401. * 存入Map数组
  402. *
  403. * @param <T>
  404. * @param key 缓存key
  405. * @param map 缓存map
  406. * @return true:成功 false:失败
  407. */
  408. public static <T> boolean setMap(String key, Map<String, T> map) {
  409. try {
  410. if (isClose() || isEmpty(key) || isEmpty(map)) {
  411. return false;
  412. }
  413. key = buildKey(key);
  414. redisTemplate.opsForHash().putAll(key, map);
  415. return true;
  416. } catch (Exception e) {
  417. log.error(e.getMessage(), e);
  418. }
  419. return false;
  420. }
  421. /**
  422. * 取出缓存的map
  423. *
  424. * @param key 缓存key
  425. * @return map 缓存的map
  426. */
  427. @SuppressWarnings("rawtypes")
  428. public static Map getMap(String key) {
  429. log.debug(" getMap key :{}", key);
  430. try {
  431. if (isClose() || isEmpty(key)) {
  432. return null;
  433. }
  434. key = buildKey(key);
  435. return redisTemplate.opsForHash().entries(key);
  436. } catch (Exception e) {
  437. log.error(e.getMessage(), e);
  438. }
  439. return null;
  440. }
  441. /**
  442. * 查询缓存的map的集合大小
  443. *
  444. * @param key 缓存key
  445. * @return int 缓存map的集合大小
  446. */
  447. public static long getMapSize(String key) {
  448. log.debug(" getMap key :{}", key);
  449. try {
  450. if (isClose() || isEmpty(key)) {
  451. return 0;
  452. }
  453. key = buildKey(key);
  454. return redisTemplate.opsForHash().size(key);
  455. } catch (Exception e) {
  456. log.error(e.getMessage(), e);
  457. }
  458. return 0;
  459. }
  460. /**
  461. * 根据key以及hashKey取出对应的Object对象
  462. *
  463. * @param key 缓存key
  464. * @param hashKey 对应map的key
  465. * @return object map中的对象
  466. */
  467. public static Object getMapKey(String key, String hashKey) {
  468. log.debug(" getMapkey :{}, hashKey:{}", key, hashKey);
  469. try {
  470. if (isClose() || isEmpty(key) || isEmpty(hashKey)) {
  471. return null;
  472. }
  473. key = buildKey(key);
  474. return redisTemplate.opsForHash().get(key, hashKey);
  475. } catch (Exception e) {
  476. log.error(e.getMessage(), e);
  477. }
  478. return null;
  479. }
  480. /**
  481. * 取出缓存中map的所有key值
  482. *
  483. * @param key 缓存key
  484. * @return Set<String> map的key值合集
  485. */
  486. public static Set<Object> getMapKeys(String key) {
  487. log.debug(" getMapKeys key :{}", key);
  488. try {
  489. if (isClose() || isEmpty(key)) {
  490. return null;
  491. }
  492. key = buildKey(key);
  493. return redisTemplate.opsForHash().keys(key);
  494. } catch (Exception e) {
  495. log.error(e.getMessage(), e);
  496. }
  497. return null;
  498. }
  499. /**
  500. * 删除map中指定的key值
  501. *
  502. * @param key 缓存key
  503. * @param hashKey map中指定的hashKey
  504. * @return true:成功 false:失败
  505. */
  506. public static boolean delMapKey(String key, String hashKey) {
  507. log.debug(" delMapKey key :{}, hashKey:{}", key, hashKey);
  508. try {
  509. if (isClose() || isEmpty(key) || isEmpty(hashKey)) {
  510. return false;
  511. }
  512. key = buildKey(key);
  513. redisTemplate.opsForHash().delete(key, hashKey);
  514. return true;
  515. } catch (Exception e) {
  516. log.error(e.getMessage(), e);
  517. }
  518. return false;
  519. }
  520. /**
  521. * 存入Map数组
  522. *
  523. * @param <T>
  524. * @param key 缓存key
  525. * @param map 缓存map
  526. * @param seconds 秒数
  527. * @return true:成功 false:失败
  528. */
  529. public static <T> boolean setMapExp(String key, Map<String, T> map, long seconds) {
  530. log.debug(" setMapExp key :{}, value: {}, seconds:{}", key, map, seconds);
  531. try {
  532. if (isClose() || isEmpty(key) || isEmpty(map)) {
  533. return false;
  534. }
  535. key = buildKey(key);
  536. redisTemplate.opsForHash().putAll(key, map);
  537. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
  538. return true;
  539. } catch (Exception e) {
  540. log.error(e.getMessage(), e);
  541. }
  542. return false;
  543. }
  544. /**
  545. * map中加入新的key
  546. *
  547. * @param <T>
  548. * @param key 缓存key
  549. * @param hashKey map的Key值
  550. * @param value map的value值
  551. * @return true:成功 false:失败
  552. */
  553. public static <T> boolean addMap(String key, String hashKey, T value) {
  554. log.debug(" addMap key :{}, hashKey: {}, value:{}", key, hashKey, value);
  555. try {
  556. if (isClose() || isEmpty(key) || isEmpty(hashKey) || isEmpty(value)) {
  557. return false;
  558. }
  559. key = buildKey(key);
  560. redisTemplate.opsForHash().put(key, hashKey, value);
  561. return true;
  562. } catch (Exception e) {
  563. log.error(e.getMessage(), e);
  564. }
  565. return false;
  566. }
  567. /**
  568. * 缓存存入List
  569. *
  570. * @param <T>
  571. * @param key 缓存key
  572. * @param list 缓存List
  573. * @return true:成功 false:失败
  574. */
  575. public static <T> boolean setList(String key, List<T> list) {
  576. log.debug(" setList key :{}, list: {}", key, list);
  577. try {
  578. if (isClose() || isEmpty(key) || isEmpty(list)) {
  579. return false;
  580. }
  581. key = buildKey(key);
  582. redisTemplate.opsForList().leftPushAll(key, list.toArray());
  583. } catch (Exception e) {
  584. log.error(e.getMessage(), e);
  585. }
  586. return false;
  587. }
  588. /**
  589. * 根据key值取出对应的list合集
  590. *
  591. * @param key 缓存key
  592. * @return List<Object> 缓存中对应的list合集
  593. */
  594. public static <V> List<V> getList(String key) {
  595. log.debug(" getList key :{}", key);
  596. try {
  597. if (isClose() || isEmpty(key)) {
  598. return null;
  599. }
  600. key = buildKey(key);
  601. return (List<V>) redisTemplate.opsForList().range(key, 0, -1);
  602. } catch (Exception e) {
  603. log.error(e.getMessage(), e);
  604. }
  605. return null;
  606. }
  607. /**
  608. * 根据key值截取对应的list合集
  609. *
  610. * @param key 缓存key
  611. * @param start 开始位置
  612. * @param end 结束位置
  613. * @return
  614. */
  615. public static void trimList(String key, int start, int end) {
  616. log.debug(" trimList key :{}", key);
  617. try {
  618. if (isClose() || isEmpty(key)) {
  619. return;
  620. }
  621. key = buildKey(key);
  622. redisTemplate.opsForList().trim(key, start, end);
  623. } catch (Exception e) {
  624. log.error(e.getMessage(), e);
  625. }
  626. }
  627. /**
  628. * 取出list合集中指定位置的对象
  629. *
  630. * @param key 缓存key
  631. * @param index 索引位置
  632. * @return Object list指定索引位置的对象
  633. */
  634. public static Object getIndexList(String key, int index) {
  635. log.debug(" getIndexList key :{}, index:{}", key, index);
  636. try {
  637. if (isClose() || isEmpty(key) || index < 0) {
  638. return null;
  639. }
  640. key = buildKey(key);
  641. return redisTemplate.opsForList().index(key, index);
  642. } catch (Exception e) {
  643. log.error(e.getMessage(), e);
  644. }
  645. return null;
  646. }
  647. /**
  648. * Object存入List
  649. *
  650. * @param key 缓存key
  651. * @param value List中的值
  652. * @return true:成功 false:失败
  653. */
  654. public static boolean addList(String key, Object value) {
  655. log.debug(" addList key :{}, value:{}", key, value);
  656. try {
  657. if (isClose() || isEmpty(key) || isEmpty(value)) {
  658. return false;
  659. }
  660. key = buildKey(key);
  661. redisTemplate.opsForList().leftPush(key, value);
  662. return true;
  663. } catch (Exception e) {
  664. log.error(e.getMessage(), e);
  665. }
  666. return false;
  667. }
  668. /**
  669. * 缓存存入List
  670. *
  671. * @param <T>
  672. * @param key 缓存key
  673. * @param list 缓存List
  674. * @param seconds 秒数
  675. * @return true:成功 false:失败
  676. */
  677. public static <T> boolean setList(String key, List<T> list, long seconds) {
  678. log.debug(" setList key :{}, value:{}, seconds:{}", key, list, seconds);
  679. try {
  680. if (isClose() || isEmpty(key) || isEmpty(list)) {
  681. return false;
  682. }
  683. key = buildKey(key);
  684. redisTemplate.opsForList().leftPushAll(key, list.toArray());
  685. if (seconds > 0) {
  686. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
  687. }
  688. return true;
  689. } catch (Exception e) {
  690. log.error(e.getMessage(), e);
  691. }
  692. return false;
  693. }
  694. /**
  695. * set集合存入缓存
  696. *
  697. * @param <T>
  698. * @param key 缓存key
  699. * @param set 缓存set集合
  700. * @return true:成功 false:失败
  701. */
  702. public static <T> boolean setSet(String key, Set<T> set) {
  703. log.debug(" setSet key :{}, value:{}", key, set);
  704. try {
  705. if (isClose() || isEmpty(key) || isEmpty(set)) {
  706. return false;
  707. }
  708. key = buildKey(key);
  709. redisTemplate.opsForSet().add(key, set.toArray());
  710. return true;
  711. } catch (Exception e) {
  712. log.error(e.getMessage(), e);
  713. }
  714. return false;
  715. }
  716. /**
  717. * set集合中增加value
  718. *
  719. * @param key 缓存key
  720. * @param value 增加的value
  721. * @return true:成功 false:失败
  722. */
  723. public static boolean addSet(String key, Object value) {
  724. log.debug(" addSet key :{}, value:{}", key, value);
  725. try {
  726. if (isClose() || isEmpty(key) || isEmpty(value)) {
  727. return false;
  728. }
  729. key = buildKey(key);
  730. redisTemplate.opsForSet().add(key, value);
  731. return true;
  732. } catch (Exception e) {
  733. log.error(e.getMessage(), e);
  734. }
  735. return false;
  736. }
  737. /**
  738. * set集合存入缓存
  739. *
  740. * @param <T>
  741. * @param key 缓存key
  742. * @param set 缓存set集合
  743. * @param seconds 秒数
  744. * @return true:成功 false:失败
  745. */
  746. public static <T> boolean setSet(String key, Set<T> set, long seconds) {
  747. log.debug(" setSet key :{}, value:{}, seconds:{}", key, set, seconds);
  748. try {
  749. if (isClose() || isEmpty(key) || isEmpty(set)) {
  750. return false;
  751. }
  752. key = buildKey(key);
  753. redisTemplate.opsForSet().add(key, set.toArray());
  754. if (seconds > 0) {
  755. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
  756. }
  757. return true;
  758. } catch (Exception e) {
  759. log.error(e.getMessage(), e);
  760. }
  761. return false;
  762. }
  763. /**
  764. * 取出缓存中对应的set合集
  765. *
  766. * @param <T>
  767. * @param key 缓存key
  768. * @return Set<Object> 缓存中的set合集
  769. */
  770. public static <T> Set<T> getSet(String key) {
  771. log.debug(" getSet key :{}", key);
  772. try {
  773. if (isClose() || isEmpty(key)) {
  774. return null;
  775. }
  776. key = buildKey(key);
  777. return (Set<T>) redisTemplate.opsForSet().members(key);
  778. } catch (Exception e) {
  779. log.error(e.getMessage(), e);
  780. }
  781. return null;
  782. }
  783. /**
  784. * 有序集合存入数值
  785. *
  786. * @param key 缓存key
  787. * @param value 缓存value
  788. * @param score 评分
  789. * @return
  790. */
  791. public static boolean addZSet(String key, Object value, double score) {
  792. log.debug(" addZSet key :{},value:{}, score:{}", key, value, score);
  793. try {
  794. if (isClose() || isEmpty(key) || isEmpty(value)) {
  795. return false;
  796. }
  797. key = buildKey(key);
  798. return redisTemplate.opsForZSet().add(key, value, score);
  799. } catch (Exception e) {
  800. log.error(e.getMessage(), e);
  801. }
  802. return false;
  803. }
  804. /**
  805. * 从有序集合中删除指定值
  806. *
  807. * @param key 缓存key
  808. * @param value 缓存value
  809. * @return
  810. */
  811. public static boolean removeZSet(String key, Object value) {
  812. log.debug(" removeZSet key :{},value:{}", key, value);
  813. try {
  814. if (isClose() || isEmpty(key) || isEmpty(value)) {
  815. return false;
  816. }
  817. key = buildKey(key);
  818. redisTemplate.opsForZSet().remove(key, value);
  819. return true;
  820. } catch (Exception e) {
  821. log.error(e.getMessage(), e);
  822. }
  823. return false;
  824. }
  825. /**
  826. * 从有序集合中删除指定位置的值
  827. *
  828. * @param key 缓存key
  829. * @param start 起始位置
  830. * @param end 结束为止
  831. * @return
  832. */
  833. public static boolean removeZSet(String key, long start, long end) {
  834. log.debug(" removeZSet key :{},start:{}, end:{}", key, start, end);
  835. try {
  836. if (isClose() || isEmpty(key)) {
  837. return false;
  838. }
  839. key = buildKey(key);
  840. redisTemplate.opsForZSet().removeRange(key, start, end);
  841. return true;
  842. } catch (Exception e) {
  843. log.error(e.getMessage(), e);
  844. }
  845. return false;
  846. }
  847. /**
  848. * 从有序集合中获取指定位置的值
  849. *
  850. * @param key 缓存key
  851. * @param start 起始位置
  852. * @param end 结束为止
  853. * @return
  854. */
  855. public static <T> Set<T> getZSet(String key, long start, long end) {
  856. log.debug(" getZSet key :{},start:{}, end:{}", key, start, end);
  857. try {
  858. if (isClose() || isEmpty(key)) {
  859. return Collections.emptySet();
  860. }
  861. key = buildKey(key);
  862. return (Set<T>) redisTemplate.opsForZSet().range(key, start, end);
  863. } catch (Exception e) {
  864. log.error(e.getMessage(), e);
  865. }
  866. return Collections.emptySet();
  867. }
  868. }

CacheContextUtil

  1. package com.huyue.common.util;
  2. import javafx.application.Application;
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.ApplicationContextAware;
  6. import org.springframework.stereotype.Component;
  7. /**
  8. * Context工具类
  9. *
  10. * @author .com 2019/3/24 23:17
  11. */
  12. @Component
  13. public class CacheContextUtil implements ApplicationContextAware {
  14. private static ApplicationContext context;
  15. @SuppressWarnings("AccessStaticViaInstance")
  16. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  17. this.context = applicationContext;
  18. }
  19. public static Object getBean(String beanId) {
  20. return context.getBean(beanId);
  21. }
  22. public static <T> T getBean(String beanId, Class<T> clazz) {
  23. return context.getBean(beanId, clazz);
  24. }
  25. }

第四步:启动spring项目

LoginController

  1. package com.huyue.controller;
  2. import com.huyue.bean.User;
  3. import com.huyue.common.util.CacheContextUtil;
  4. import com.huyue.common.util.CacheUtil;
  5. import com.huyue.service.impl.UserServiceImpl;
  6. import com.sun.deploy.net.HttpResponse;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.http.HttpRequest;
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.servlet.ModelAndView;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16. /**
  17. * @author 2019/3/17 15:05
  18. */
  19. @Controller
  20. @RequestMapping("/login")
  21. public class LoginController {
  22. private static Logger log = LoggerFactory.getLogger(LoginController.class);
  23. @Autowired
  24. private UserServiceImpl userServiceImpl;
  25. @RequestMapping("check")
  26. public ModelAndView check(HttpServletRequest request,HttpServletResponse response){
  27. ModelAndView view = new ModelAndView("jsonView");
  28. System.out.println("开始塞入缓存数据");
  29. CacheUtil.setString("123","huyue");
  30. System.out.println(CacheUtil.getString("123"));
  31. // String username= request.getParameter("username");
  32. // String password= request.getParameter("password");
  33. // String superUser = "admin";
  34. // if (superUser.equals(username)){
  35. // view.addObject("result",0);
  36. // }else {
  37. // view.addObject("result",1);
  38. // view.addObject("message","登录名不正确");
  39. // }
  40. return view;
  41. }
  42. }

打印结果

  1. 开始塞入缓存数据
  2. [com.huyue.common.util.CacheUtil] - setString key:123 value:huyue
  3. [com.huyue.common.util.CacheUtil] - getString key:123
  4. huyue

最后给大家推荐一个IDEA连接redis数据库的插件Iedis,但是是收费的

更多高级用法后续在写,敬请期待

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

闽ICP备14008679号