Spring集成redis(SSM框架)

一、本地安装 redis(windows)

1、 下载redis压缩包

      下载地址:https://github.com/MicrosoftArchive/redis/tags

2、解压到对应目录:

Spring集成redis(SSM框架)

3、双击redis-server.exe启动redis,双击redis-cli.exe操作redis命令。

Spring集成redis(SSM框架)

启动成功页面如上图,至此redis安装完毕。若不能正确安装还请读者留言咨询。接下来步入正题。

二、jar包引入,配置redis.properties

 
  1. <!--redis相关 -->

  2. <dependency>

  3. <groupId>org.springframework.data</groupId>

  4. <artifactId>spring-data-redis</artifactId>

  5. <version>1.8.6.RELEASE</version>

  6. </dependency>

  7. <dependency>

  8. <groupId>redis.clients</groupId>

  9. <artifactId>jedis</artifactId>

  10. <version>2.9.0</version>

  11. </dependency>

redis.priperties文件内容:

redis.host=127.0.0.1
redis.port=6379

redis.sentinel.port=26879

redis.pwd=

redis.database=0
redis.timeout=1000
redis.userPool=true
redis.pool.maxIdle=100
redis.pool.minIdle=10
redis.pool.maxTotal=200
redis.pool.maxWaitMillis=10000
redis.pool.minEvictableIdleTimeMillis=300000
redis.pool.numTestsPerEvictionRun=10
redis.pool.timeBetweenEvictionRunsMillis=30000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true

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}"></property>

  27. <property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"></property>

  28. <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"></property>

  29. <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />

  30. <property name="testOnReturn" value="${redis.pool.testOnReturn}" />

  31. <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"></property>

  32. </bean>

  33.  
  34. <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">

  35. <property name="poolConfig" ref="jedisPoolConfig" />

  36. <property name="hostName" value="${redis.host}" />

  37. <property name="port" value="${redis.port}" />

  38. <property name="password" value="${redis.pwd}" />

  39. <property name="usePool" value="${redis.userPool} " />

  40. <property name="database" value="${redis.database}" />

  41. <property name="timeout" value="${redis.timeout}" />

  42. </bean>

  43.  
  44. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">

  45. <property name="connectionFactory" ref="jedisConnectionFactory" />

  46.  
  47. <!-- 序列化方式 建议key/hashKey采用StringRedisSerializer -->

  48. <property name="keySerializer">

  49. <bean

  50. class="org.springframework.data.redis.serializer.StringRedisSerializer" />

  51. </property>

  52. <property name="valueSerializer">

  53. <bean

  54. class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

  55. </property>

  56. <property name="hashKeySerializer">

  57. <bean

  58. class="org.springframework.data.redis.serializer.StringRedisSerializer" />

  59. </property>

  60. <property name="hashValueSerializer">

  61. <bean

  62. class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

  63. </property>

  64. <!-- 开启REIDS事务支持 -->

  65. <property name="enableTransactionSupport" value="false" />

  66. </bean>

  67.  
  68. <!-- 对string操作的封装 -->

  69. <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">

  70. <constructor-arg ref="jedisConnectionFactory" />

  71. <!-- 开启REIDS事务支持 -->

  72. <property name="enableTransactionSupport" value="false" />

  73. </bean>

  74.  
  75. </beans>

四、在applactionContext.xml引入spring-redis.xml

           <import resource="classpath:spring/spring-redis.xml" />

 

五、封装redis操作工具类(类中注释解释很详细)

       这里封装的方法包括对String、list 、set、obj、map等的操作 。

 

 
  1. package com.test.util;

  2.  
  3. import java.util.Collections;

  4. import java.util.HashSet;

  5. import java.util.List;

  6. import java.util.Map;

  7. import java.util.Set;

  8. import java.util.concurrent.TimeUnit;

  9.  
  10. import org.slf4j.Logger;

  11. import org.slf4j.LoggerFactory;

  12. import org.springframework.data.redis.core.RedisTemplate;

  13. import org.springframework.data.redis.core.StringRedisTemplate;

  14.  
  15. /**

  16. * redis工具类

  17. *

  18. */

  19. @SuppressWarnings("unchecked")

  20. public class CacheUtil {

  21.  
  22. private static final Logger LOG = LoggerFactory.getLogger(CacheUtil.class);

  23.  
  24. private static RedisTemplate<String, Object> redisTemplate = CacheContextUtil.getBean("redisTemplate", RedisTemplate.class);

  25.  
  26. private static StringRedisTemplate stringRedisTemplate = CacheContextUtil.getBean("stringRedisTemplate", StringRedisTemplate.class);

  27.  
  28. private static String CACHE_PREFIX;

  29.  
  30. private static boolean CACHE_CLOSED;

  31.  
  32. private CacheUtil() {

  33.  
  34. }

  35.  
  36. @SuppressWarnings("rawtypes")

  37. private static boolean isEmpty(Object obj) {

  38. if (obj == null) {

  39. return true;

  40. }

  41. if (obj instanceof String) {

  42. String str = obj.toString();

  43. if ("".equals(str.trim())) {

  44. return true;

  45. }

  46. return false;

  47. }

  48. if (obj instanceof List) {

  49. List<Object> list = (List<Object>) obj;

  50. if (list.isEmpty()) {

  51. return true;

  52. }

  53. return false;

  54. }

  55. if (obj instanceof Map) {

  56. Map map = (Map) obj;

  57. if (map.isEmpty()) {

  58. return true;

  59. }

  60. return false;

  61. }

  62. if (obj instanceof Set) {

  63. Set set = (Set) obj;

  64. if (set.isEmpty()) {

  65. return true;

  66. }

  67. return false;

  68. }

  69. if (obj instanceof Object[]) {

  70. Object[] objs = (Object[]) obj;

  71. if (objs.length <= 0) {

  72. return true;

  73. }

  74. return false;

  75. }

  76. return false;

  77. }

  78.  
  79. /**

  80. * 构建缓存key值

  81. * @param key 缓存key

  82. * @return

  83. */

  84. private static String buildKey(String key) {

  85. if (CACHE_PREFIX == null || "".equals(CACHE_PREFIX)) {

  86. return key;

  87. }

  88. return CACHE_PREFIX + ":" + key;

  89. }

  90.  
  91. /**

  92. * 返回缓存的前缀

  93. * @return CACHE_PREFIX_FLAG

  94. */

  95. public static String getCachePrefix() {

  96. return CACHE_PREFIX;

  97. }

  98.  
  99. /**

  100. * 设置缓存的前缀

  101. * @param cachePrefix

  102. */

  103. public static void setCachePrefix(String cachePrefix) {

  104. if (cachePrefix != null && !"".equals(cachePrefix.trim())) {

  105. CACHE_PREFIX = cachePrefix.trim();

  106. }

  107. }

  108.  
  109. /**

  110. * 关闭缓存

  111. * @return true:成功

  112. * false:失败

  113. */

  114. public static boolean close() {

  115. LOG.debug(" cache closed ! ");

  116. CACHE_CLOSED = true;

  117. return true;

  118. }

  119.  
  120. /**

  121. * 打开缓存

  122. * @return true:存在

  123. * false:不存在

  124. */

  125. public static boolean openCache() {

  126. CACHE_CLOSED = false;

  127. return true;

  128. }

  129.  
  130. /**

  131. * 检查缓存是否开启

  132. * @return true:已关闭

  133. * false:已开启

  134. */

  135. public static boolean isClose() {

  136. return CACHE_CLOSED;

  137. }

  138.  
  139. /**

  140. * 判断key值是否存在

  141. * @param key 缓存的key

  142. * @return true:存在

  143. * false:不存在

  144. */

  145. public static boolean hasKey(String key) {

  146. LOG.debug(" hasKey key :{}", key);

  147. try {

  148. if (isClose() || isEmpty(key)) {

  149. return false;

  150. }

  151. key = buildKey(key);

  152. return redisTemplate.hasKey(key);

  153. } catch (Exception e) {

  154. LOG.error(e.getMessage(), e);

  155. }

  156. return false;

  157. }

  158.  
  159. /**

  160. * 匹配符合正则的key

  161. * @param patternKey

  162. * @return key的集合

  163. */

  164. public static Set<String> keys(String patternKey) {

  165. LOG.debug(" keys key :{}", patternKey);

  166. try {

  167. if (isClose() || isEmpty(patternKey)) {

  168. return Collections.emptySet();

  169. }

  170. return redisTemplate.keys(patternKey);

  171. } catch (Exception e) {

  172. LOG.error(e.getMessage(), e);

  173. }

  174. return Collections.emptySet();

  175. }

  176.  
  177. /**

  178. * 根据key删除缓存

  179. * @param key

  180. * @return true:成功

  181. * false:失败

  182. */

  183. public static boolean del(String... key) {

  184. LOG.debug(" delete key :{}", key.toString());

  185. try {

  186. if (isClose() || isEmpty(key)) {

  187. return false;

  188. }

  189. Set<String> keySet = new HashSet<>();

  190. for (String str : key) {

  191. keySet.add(buildKey(str));

  192. }

  193. redisTemplate.delete(keySet);

  194. return true;

  195. } catch (Exception e) {

  196. LOG.error(e.getMessage(), e);

  197. }

  198. return false;

  199. }

  200.  
  201. /**

  202. * 根据key删除缓存

  203. * @param key

  204. * @return true:成功

  205. * false:失败

  206. */

  207. public static boolean delPattern(String key) {

  208. LOG.debug(" delete Pattern keys :{}", key);

  209. try {

  210. if (isClose() || isEmpty(key)) {

  211. return false;

  212. }

  213. key = buildKey(key);

  214. redisTemplate.delete(redisTemplate.keys(key));

  215. return true;

  216. } catch (Exception e) {

  217. LOG.error(e.getMessage(), e);

  218. }

  219. return false;

  220. }

  221.  
  222. /**

  223. * 删除一组key值

  224. * @param keys

  225. * @return true:成功

  226. * false:失败

  227. */

  228. public static boolean del(Set<String> keys) {

  229. LOG.debug(" delete keys :{}", keys.toString());

  230. try {

  231. if (isClose() || isEmpty(keys)) {

  232. return false;

  233. }

  234. Set<String> keySet = new HashSet<>();

  235. for (String str : keys) {

  236. keySet.add(buildKey(str));

  237. }

  238. redisTemplate.delete(keySet);

  239. return true;

  240. } catch (Exception e) {

  241. LOG.error(e.getMessage(), e);

  242. }

  243. return false;

  244. }

  245.  
  246. /**

  247. * 设置过期时间

  248. * @param key 缓存key

  249. * @param seconds 过期秒数

  250. * @return true:成功

  251. * false:失败

  252. */

  253. public static boolean setExp(String key, long seconds) {

  254. LOG.debug(" setExp key :{}, seconds: {}", key, seconds);

  255. try {

  256. if (isClose() || isEmpty(key) || seconds > 0) {

  257. return false;

  258. }

  259. key = buildKey(key);

  260. return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);

  261. } catch (Exception e) {

  262. LOG.error(e.getMessage(), e);

  263. }

  264. return false;

  265. }

  266.  
  267. /**

  268. * 查询过期时间

  269. * @param key 缓存key

  270. * @return 秒数

  271. */

  272. public static Long getExpire(String key) {

  273. LOG.debug(" getExpire key :{}", key);

  274. try {

  275. if (isClose() || isEmpty(key)) {

  276. return 0L;

  277. }

  278. key = buildKey(key);

  279. return redisTemplate.getExpire(key, TimeUnit.SECONDS);

  280. } catch (Exception e) {

  281. LOG.error(e.getMessage(), e);

  282. }

  283. return 0L;

  284. }

  285.  
  286. /**

  287. * 缓存存入key-value

  288. * @param key 缓存键

  289. * @param value 缓存值

  290. * @return true:成功

  291. * false:失败

  292. */

  293. public static boolean setString(String key, String value) {

  294. LOG.debug(" setString key :{}, value: {}", key, value);

  295. try {

  296. if (isClose() || isEmpty(key) || isEmpty(value)) {

  297. return false;

  298. }

  299. key = buildKey(key);

  300. stringRedisTemplate.opsForValue().set(key, value);

  301. return true;

  302. } catch (Exception e) {

  303. LOG.error(e.getMessage(), e);

  304. }

  305. return false;

  306. }

  307.  
  308. /**

  309. * 缓存存入key-value

  310. * @param key 缓存键

  311. * @param value 缓存值

  312. * @param seconds 秒数

  313. * @return true:成功

  314. * false:失败

  315. */

  316. public static boolean setString(String key, String value, long seconds) {

  317. LOG.debug(" setString key :{}, value: {}, timeout:{}", key, value, seconds);

  318. try {

  319. if (isClose() || isEmpty(key) || isEmpty(value)) {

  320. return false;

  321. }

  322. key = buildKey(key);

  323. stringRedisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);

  324. return true;

  325. } catch (Exception e) {

  326. LOG.error(e.getMessage(), e);

  327. }

  328. return false;

  329. }

  330.  
  331. /**

  332. * 根据key取出String value

  333. * @param key 缓存key值

  334. * @return String 缓存的String

  335. */

  336. public static String getString(String key) {

  337. LOG.debug(" getString key :{}", key);

  338. try {

  339. if (isClose() || isEmpty(key)) {

  340. return null;

  341. }

  342. key = buildKey(key);

  343. return stringRedisTemplate.opsForValue().get(key);

  344. } catch (Exception e) {

  345. LOG.error(e.getMessage(), e);

  346. }

  347. return null;

  348. }

  349.  
  350. /**

  351. * 去的缓存中的最大值并+1

  352. * @param key 缓存key值

  353. * @return long 缓存中的最大值+1

  354. */

  355. public static long incr(String key) {

  356. LOG.debug(" incr key :{}", key);

  357. try {

  358. if (isClose() || isEmpty(key)) {

  359. return 0;

  360. }

  361. key = buildKey(key);

  362. return redisTemplate.opsForValue().increment(key, 1);

  363. } catch (Exception e) {

  364. LOG.error(e.getMessage(), e);

  365. }

  366. return 0;

  367. }

  368.  
  369. /**

  370. * 缓存中存入序列化的Object对象

  371. * @param <T>

  372. * @param key 缓存key

  373. * @param obj 存入的序列化对象

  374. * @return true:成功

  375. * false:失败

  376. */

  377. public static boolean set(String key, Object obj) {

  378. LOG.debug(" set key :{}, value:{}", key, obj);

  379. try {

  380. if (isClose() || isEmpty(key) || isEmpty(obj)) {

  381. return false;

  382. }

  383. key = buildKey(key);

  384. redisTemplate.opsForValue().set(key, obj);

  385. } catch (Exception e) {

  386. LOG.error(e.getMessage(), e);

  387. }

  388. return false;

  389. }

  390.  
  391. /**

  392. * 缓存中存入序列化的Object对象

  393. * @param <T>

  394. * @param key 缓存key

  395. * @param obj 存入的序列化对象

  396. * @return true:成功

  397. * false:失败

  398. */

  399. public static boolean setObj(String key, Object obj, long seconds) {

  400. LOG.debug(" set key :{}, value:{}, seconds:{}", key, obj, seconds);

  401. try {

  402. if (isClose() || isEmpty(key) || isEmpty(obj)) {

  403. return false;

  404. }

  405. key = buildKey(key);

  406. redisTemplate.opsForValue().set(key, obj);

  407. if (seconds > 0) {

  408. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);

  409. }

  410. return true;

  411. } catch (Exception e) {

  412. LOG.error(e.getMessage(), e);

  413. }

  414. return false;

  415. }

  416.  
  417. /**

  418. * 取出缓存中存储的序列化对象

  419. * @param key 缓存key

  420. * @param clazz 对象类

  421. * @return <T> 序列化对象

  422. */

  423. public static <T> T getObj(String key, Class<T> clazz) {

  424. LOG.debug(" get key :{}", key);

  425. try {

  426. if (isClose() || isEmpty(key)) {

  427. return null;

  428. }

  429. key = buildKey(key);

  430. return (T) redisTemplate.opsForValue().get(key);

  431. } catch (Exception e) {

  432. LOG.error(e.getMessage(), e);

  433. }

  434. return null;

  435. }

  436.  
  437. /**

  438. * 存入Map数组

  439. * @param <T>

  440. * @param key 缓存key

  441. * @param map 缓存map

  442. * @return true:成功

  443. * false:失败

  444. */

  445. public static <T> boolean setMap(String key, Map<String, T> map) {

  446. try {

  447. if (isClose() || isEmpty(key) || isEmpty(map)) {

  448. return false;

  449. }

  450. key = buildKey(key);

  451. redisTemplate.opsForHash().putAll(key, map);

  452. return true;

  453. } catch (Exception e) {

  454. LOG.error(e.getMessage(), e);

  455. }

  456. return false;

  457. }

  458.  
  459. /**

  460. * 取出缓存的map

  461. * @param key 缓存key

  462. * @return map 缓存的map

  463. */

  464. @SuppressWarnings("rawtypes")

  465. public static Map getMap(String key) {

  466. LOG.debug(" getMap key :{}", key);

  467. try {

  468. if (isClose() || isEmpty(key)) {

  469. return null;

  470. }

  471. key = buildKey(key);

  472. return redisTemplate.opsForHash().entries(key);

  473. } catch (Exception e) {

  474. LOG.error(e.getMessage(), e);

  475. }

  476. return null;

  477. }

  478.  
  479. /**

  480. * 查询缓存的map的集合大小

  481. * @param key 缓存key

  482. * @return int 缓存map的集合大小

  483. */

  484. public static long getMapSize(String key) {

  485. LOG.debug(" getMap key :{}", key);

  486. try {

  487. if (isClose() || isEmpty(key)) {

  488. return 0;

  489. }

  490. key = buildKey(key);

  491. return redisTemplate.opsForHash().size(key);

  492. } catch (Exception e) {

  493. LOG.error(e.getMessage(), e);

  494. }

  495. return 0;

  496. }

  497.  
  498.  
  499. /**

  500. * 根据key以及hashKey取出对应的Object对象

  501. * @param key 缓存key

  502. * @param hashKey 对应map的key

  503. * @return object map中的对象

  504. */

  505. public static Object getMapKey(String key, String hashKey) {

  506. LOG.debug(" getMapkey :{}, hashKey:{}", key, hashKey);

  507. try {

  508. if (isClose() || isEmpty(key) || isEmpty(hashKey)) {

  509. return null;

  510. }

  511. key = buildKey(key);

  512. return redisTemplate.opsForHash().get(key, hashKey);

  513. } catch (Exception e) {

  514. LOG.error(e.getMessage(), e);

  515. }

  516. return null;

  517. }

  518.  
  519. /**

  520. * 取出缓存中map的所有key值

  521. * @param key 缓存key

  522. * @return Set<String> map的key值合集

  523. */

  524. public static Set<Object> getMapKeys(String key) {

  525. LOG.debug(" getMapKeys key :{}", key);

  526. try {

  527. if (isClose() || isEmpty(key)) {

  528. return null;

  529. }

  530. key = buildKey(key);

  531. return redisTemplate.opsForHash().keys(key);

  532. } catch (Exception e) {

  533. LOG.error(e.getMessage(), e);

  534. }

  535. return null;

  536. }

  537.  
  538. /**

  539. * 删除map中指定的key值

  540. * @param key 缓存key

  541. * @param hashKey map中指定的hashKey

  542. * @return true:成功

  543. * false:失败

  544. */

  545. public static boolean delMapKey(String key, String hashKey) {

  546. LOG.debug(" delMapKey key :{}, hashKey:{}", key, hashKey);

  547. try {

  548. if (isClose() || isEmpty(key) || isEmpty(hashKey)) {

  549. return false;

  550. }

  551. key = buildKey(key);

  552. redisTemplate.opsForHash().delete(key, hashKey);

  553. return true;

  554. } catch (Exception e) {

  555. LOG.error(e.getMessage(), e);

  556. }

  557. return false;

  558. }

  559.  
  560. /**

  561. * 存入Map数组

  562. * @param <T>

  563. * @param key 缓存key

  564. * @param map 缓存map

  565. * @param seconds 秒数

  566. * @return true:成功

  567. * false:失败

  568. */

  569. public static <T> boolean setMapExp(String key, Map<String, T> map, long seconds) {

  570. LOG.debug(" setMapExp key :{}, value: {}, seconds:{}", key, map, seconds);

  571. try {

  572. if (isClose() || isEmpty(key) || isEmpty(map)) {

  573. return false;

  574. }

  575. key = buildKey(key);

  576. redisTemplate.opsForHash().putAll(key, map);

  577. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);

  578. return true;

  579. } catch (Exception e) {

  580. LOG.error(e.getMessage(), e);

  581. }

  582. return false;

  583. }

  584.  
  585. /**

  586. * map中加入新的key

  587. * @param <T>

  588. * @param key 缓存key

  589. * @param hashKey map的Key值

  590. * @param value map的value值

  591. * @return true:成功

  592. * false:失败

  593. */

  594. public static <T> boolean addMap(String key, String hashKey, T value) {

  595. LOG.debug(" addMap key :{}, hashKey: {}, value:{}", key, hashKey, value);

  596. try {

  597. if (isClose() || isEmpty(key) || isEmpty(hashKey) || isEmpty(value)) {

  598. return false;

  599. }

  600. key = buildKey(key);

  601. redisTemplate.opsForHash().put(key, hashKey, value);

  602. return true;

  603. } catch (Exception e) {

  604. LOG.error(e.getMessage(), e);

  605. }

  606. return false;

  607. }

  608.  
  609. /**

  610. * 缓存存入List

  611. * @param <T>

  612. * @param key 缓存key

  613. * @param list 缓存List

  614. * @return true:成功

  615. * false:失败

  616. */

  617. public static <T> boolean setList(String key, List<T> list) {

  618. LOG.debug(" setList key :{}, list: {}", key, list);

  619. try {

  620. if (isClose() || isEmpty(key) || isEmpty(list)) {

  621. return false;

  622. }

  623. key = buildKey(key);

  624. redisTemplate.opsForList().leftPushAll(key, list.toArray());

  625. } catch (Exception e) {

  626. LOG.error(e.getMessage(), e);

  627. }

  628. return false;

  629. }

  630.  
  631. /**

  632. * 根据key值取出对应的list合集

  633. * @param key 缓存key

  634. * @return List<Object> 缓存中对应的list合集

  635. */

  636. public static <V> List<V> getList(String key) {

  637. LOG.debug(" getList key :{}", key);

  638. try {

  639. if (isClose() || isEmpty(key)) {

  640. return null;

  641. }

  642. key = buildKey(key);

  643. return (List<V>) redisTemplate.opsForList().range(key, 0, -1);

  644. } catch (Exception e) {

  645. LOG.error(e.getMessage(), e);

  646. }

  647. return null;

  648. }

  649.  
  650. /**

  651. * 根据key值截取对应的list合集

  652. * @param key 缓存key

  653. * @param start 开始位置

  654. * @param end 结束位置

  655. * @return

  656. */

  657. public static void trimList(String key, int start, int end) {

  658. LOG.debug(" trimList key :{}", key);

  659. try {

  660. if (isClose() || isEmpty(key)) {

  661. return;

  662. }

  663. key = buildKey(key);

  664. redisTemplate.opsForList().trim(key, start, end);

  665. } catch (Exception e) {

  666. LOG.error(e.getMessage(), e);

  667. }

  668. }

  669.  
  670. /**

  671. * 取出list合集中指定位置的对象

  672. * @param key 缓存key

  673. * @param index 索引位置

  674. * @return Object list指定索引位置的对象

  675. */

  676. public static Object getIndexList(String key, int index) {

  677. LOG.debug(" getIndexList key :{}, index:{}", key, index);

  678. try {

  679. if (isClose() || isEmpty(key) || index < 0) {

  680. return null;

  681. }

  682. key = buildKey(key);

  683. return redisTemplate.opsForList().index(key, index);

  684. } catch (Exception e) {

  685. LOG.error(e.getMessage(), e);

  686. }

  687. return null;

  688. }

  689.  
  690. /**

  691. * Object存入List

  692. * @param <T>

  693. * @param key 缓存key

  694. * @param value List中的值

  695. * @return true:成功

  696. * false:失败

  697. */

  698. public static boolean addList(String key, Object value) {

  699. LOG.debug(" addList key :{}, value:{}", key, value);

  700. try {

  701. if (isClose() || isEmpty(key) || isEmpty(value)) {

  702. return false;

  703. }

  704. key = buildKey(key);

  705. redisTemplate.opsForList().leftPush(key, value);

  706. return true;

  707. } catch (Exception e) {

  708. LOG.error(e.getMessage(), e);

  709. }

  710. return false;

  711. }

  712.  
  713. /**

  714. * 缓存存入List

  715. * @param <T>

  716. * @param key 缓存key

  717. * @param list 缓存List

  718. * @param seconds 秒数

  719. * @return true:成功

  720. * false:失败

  721. */

  722. public static <T> boolean setList(String key, List<T> list, long seconds) {

  723. LOG.debug(" setList key :{}, value:{}, seconds:{}", key, list, seconds);

  724. try {

  725. if (isClose() || isEmpty(key) || isEmpty(list)) {

  726. return false;

  727. }

  728. key = buildKey(key);

  729. redisTemplate.opsForList().leftPushAll(key, list.toArray());

  730. if (seconds > 0) {

  731. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);

  732. }

  733. return true;

  734. } catch (Exception e) {

  735. LOG.error(e.getMessage(), e);

  736. }

  737. return false;

  738. }

  739.  
  740. /**

  741. * set集合存入缓存

  742. * @param <T>

  743. * @param key 缓存key

  744. * @param set 缓存set集合

  745. * @return true:成功

  746. * false:失败

  747. */

  748. public static <T> boolean setSet(String key, Set<T> set) {

  749. LOG.debug(" setSet key :{}, value:{}", key, set);

  750. try {

  751. if (isClose() || isEmpty(key) || isEmpty(set)) {

  752. return false;

  753. }

  754. key = buildKey(key);

  755. redisTemplate.opsForSet().add(key, set.toArray());

  756. return true;

  757. } catch (Exception e) {

  758. LOG.error(e.getMessage(), e);

  759. }

  760. return false;

  761. }

  762.  
  763. /**

  764. * set集合中增加value

  765. * @param <T>

  766. * @param key 缓存key

  767. * @param value 增加的value

  768. * @return true:成功

  769. * false:失败

  770. */

  771. public static boolean addSet(String key, Object value) {

  772. LOG.debug(" addSet key :{}, value:{}", key, value);

  773. try {

  774. if (isClose() || isEmpty(key) || isEmpty(value)) {

  775. return false;

  776. }

  777. key = buildKey(key);

  778. redisTemplate.opsForSet().add(key, value);

  779. return true;

  780. } catch (Exception e) {

  781. LOG.error(e.getMessage(), e);

  782. }

  783. return false;

  784. }

  785.  
  786. /**

  787. * set集合存入缓存

  788. * @param <T>

  789. * @param key 缓存key

  790. * @param set 缓存set集合

  791. * @param seconds 秒数

  792. * @return true:成功

  793. * false:失败

  794. */

  795. public static <T> boolean setSet(String key, Set<T> set, long seconds) {

  796. LOG.debug(" setSet key :{}, value:{}, seconds:{}", key, set, seconds);

  797. try {

  798. if (isClose() || isEmpty(key) || isEmpty(set)) {

  799. return false;

  800. }

  801. key = buildKey(key);

  802. redisTemplate.opsForSet().add(key, set.toArray());

  803. if (seconds > 0) {

  804. redisTemplate.expire(key, seconds, TimeUnit.SECONDS);

  805. }

  806. return true;

  807. } catch (Exception e) {

  808. LOG.error(e.getMessage(), e);

  809. }

  810. return false;

  811. }

  812.  
  813. /**

  814. * 取出缓存中对应的set合集

  815. * @param <T>

  816. * @param key 缓存key

  817. * @return Set<Object> 缓存中的set合集

  818. */

  819. public static <T> Set<T> getSet(String key) {

  820. LOG.debug(" getSet key :{}", key);

  821. try {

  822. if (isClose() || isEmpty(key)) {

  823. return null;

  824. }

  825. key = buildKey(key);

  826. return (Set<T>) redisTemplate.opsForSet().members(key);

  827. } catch (Exception e) {

  828. LOG.error(e.getMessage(), e);

  829. }

  830. return null;

  831. }

  832.  
  833. /**

  834. * 有序集合存入数值

  835. * @param key 缓存key

  836. * @param value 缓存value

  837. * @param score 评分

  838. * @return

  839. */

  840. public static boolean addZSet(String key, Object value, double score) {

  841. LOG.debug(" addZSet key :{},value:{}, score:{}", key, value, score);

  842. try {

  843. if (isClose() || isEmpty(key) || isEmpty(value)) {

  844. return false;

  845. }

  846. key = buildKey(key);

  847. return redisTemplate.opsForZSet().add(key, value, score);

  848. } catch (Exception e) {

  849. LOG.error(e.getMessage(), e);

  850. }

  851. return false;

  852. }

  853.  
  854. /**

  855. * 从有序集合中删除指定值

  856. * @param key 缓存key

  857. * @param value 缓存value

  858. * @return

  859. */

  860. public static boolean removeZSet(String key, Object value) {

  861. LOG.debug(" removeZSet key :{},value:{}", key, value);

  862. try {

  863. if (isClose() || isEmpty(key) || isEmpty(value)) {

  864. return false;

  865. }

  866. key = buildKey(key);

  867. redisTemplate.opsForZSet().remove(key, value);

  868. return true;

  869. } catch (Exception e) {

  870. LOG.error(e.getMessage(), e);

  871. }

  872. return false;

  873. }

  874.  
  875. /**

  876. * 从有序集合中删除指定位置的值

  877. * @param key 缓存key

  878. * @param start 起始位置

  879. * @param end 结束为止

  880. * @return

  881. */

  882. public static boolean removeZSet(String key, long start, long end) {

  883. LOG.debug(" removeZSet key :{},start:{}, end:{}", key, start, end);

  884. try {

  885. if (isClose() || isEmpty(key)) {

  886. return false;

  887. }

  888. key = buildKey(key);

  889. redisTemplate.opsForZSet().removeRange(key, start, end);

  890. return true;

  891. } catch (Exception e) {

  892. LOG.error(e.getMessage(), e);

  893. }

  894. return false;

  895. }

  896.  
  897. /**

  898. * 从有序集合中获取指定位置的值

  899. * @param key 缓存key

  900. * @param start 起始位置

  901. * @param end 结束为止

  902. * @return

  903. */

  904. public static <T> Set<T> getZSet(String key, long start, long end) {

  905. LOG.debug(" getZSet key :{},start:{}, end:{}", key, start, end);

  906. try {

  907. if (isClose() || isEmpty(key)) {

  908. return Collections.emptySet();

  909. }

  910. key = buildKey(key);

  911. return (Set<T>) redisTemplate.opsForZSet().range(key, start, end);

  912. } catch (Exception e) {

  913. LOG.error(e.getMessage(), e);

  914. }

  915. return Collections.emptySet();

  916. }

  917. }

 
  1. package com.test.util;

  2.  
  3.  
  4. import org.springframework.beans.BeansException;

  5. import org.springframework.context.ApplicationContext;

  6. import org.springframework.context.ApplicationContextAware;

  7. import org.springframework.stereotype.Component;

  8.  
  9.  
  10. /**

  11.  * Context 工具类

  12.  */

  13. @SuppressWarnings("static-access")

  14. @Component

  15. public class CacheContextUtil implements ApplicationContextAware {

  16.     private static ApplicationContext commonApplicationContext;

  17.  
  18.  
  19.     @Override

  20.     public void setApplicationContext(ApplicationContext context) throws BeansException {

  21. this.commonApplicationContext = context;

  22.     }

  23.  
  24.  
  25.     /**

  26.      * 根据提供的bean名称得到相应的服务类

  27.      * @param beanId bean的id

  28.      * @return 返回bean的实例对象

  29.      */

  30.     public static Object getBean(String beanId) {

  31. return commonApplicationContext.getBean(beanId);

  32.     }

  33.  
  34.  
  35.     /**

  36.      * 根据提供的bean名称得到对应于指定类型的服务类

  37.      * @param beanId bean的id

  38.      * @param clazz bean的类类型

  39.      * @return 返回的bean类型,若类型不匹配,将抛出异常

  40.      */

  41.     public static <T> T getBean(String beanId, Class<T> clazz) {

  42. return commonApplicationContext.getBean(beanId, clazz);

  43.     }

}

 

六 、测试代码

 

 
  1. @RequestMapping("redis")

  2. public String redisTest() {

  3. try {

  4. boolean b = CacheUtil.setString("123", "redis");//向redis里存字符串 key-value

  5. System.out.println(b);//true成功,

  6. System.out.println(CacheUtil.getString("123"));//从radis里取数据 key

  7. } catch (Exception e) {

  8. e.printStackTrace();

  9. return null;

  10. }

  11. return "hello";

  12. }

访问这个地址请求时,用到了我们封装的工具类,用缓存操作string的存取。测试结果如下图

Spring集成redis(SSM框架)

 根据测试可知,Spring集成redis成功。

如有不足之处,欢迎各位读者博友留言评论!

--------------------- 本文来自 zhao_pq 的**** 博客 ,全文地址请点击:https://blog.****.net/weixin_42184707/article/details/80361464?utm_source=copy