Redis学习之与Spring整合开发

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wzq__janeGreen_/article/details/81501897

在网上看了Redis整合Spring的文章,都是加入了spring配置的代码,很冗余,让读者不易理解。

本篇就不贴出配置Spring的代码,直接给出与Redis相关配置及代码,建立在Spring项目已经配置好的基础上。

第一步:引入jar包

需要引入和Redis 相关的两个jar包,一个是spring-data-redis.jar,另一个是jedis.jar。

具体的jar包在maven中心库里面都能找到。

maven项目pom.xml的配置:

 
  1. <!-- redis缓存 -->

  2. <dependency>

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

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

  5. <version>1.3.4.RELEASE</version>

  6. </dependency>

  7. <dependency>

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

  9. <artifactId>jedis</artifactId>

  10. <version>2.5.2</version>

  11. </dependency>


第二步:新建RedisCache.class类,自定义Cache。

 
  1. package com.qcjy.common.cache;

  2.  
  3. import java.io.ByteArrayInputStream;

  4. import java.io.ByteArrayOutputStream;

  5. import java.io.IOException;

  6. import java.io.ObjectInputStream;

  7. import java.io.ObjectOutputStream;

  8.  
  9. import org.apache.log4j.Logger;

  10. import org.springframework.cache.Cache;

  11. import org.springframework.cache.support.SimpleValueWrapper;

  12. import org.springframework.dao.DataAccessException;

  13. import org.springframework.data.redis.connection.RedisConnection;

  14. import org.springframework.data.redis.core.RedisCallback;

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

  16.  
  17.  
  18. /**

  19. * 自定义cache,可以定义一个cache名称和一个缓存失效时间。时间到期会自动更新。在xml中配置。

  20. * <功能详细描述>

  21. *

  22. * @author lcma

  23. * @version [版本号, 2016年9月12日]

  24. * @see [相关类/方法]

  25. * @since [产品/模块版本]

  26. */

  27. public class RedisCache implements Cache {

  28. /**

  29. * LOG日志

  30. */

  31. private static final Logger LOGGER = Logger.getLogger(RedisCache.class);

  32.  
  33. private RedisTemplate<String, Object> redisTemplate;

  34.  
  35. /**

  36. * 缓存名称

  37. */

  38. private String name;

  39.  
  40. /**

  41. * 缓存失效时间,时间到了会自动更新

  42. */

  43. private long liveTime = 0;

  44.  
  45. public RedisTemplate<String, Object> getRedisTemplate() {

  46. return redisTemplate;

  47. }

  48.  
  49. public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {

  50. this.redisTemplate = redisTemplate;

  51. }

  52.  
  53. public void setName(String name) {

  54. this.name = name;

  55. }

  56.  
  57. @Override

  58. public String getName() {

  59. return this.name;

  60. }

  61.  
  62. @Override

  63. public Object getNativeCache() {

  64. return this.redisTemplate;

  65. }

  66.  
  67. /**

  68. * 获取

  69. */

  70. @Override

  71. public ValueWrapper get(Object key) {

  72. final String keyf = (String)key;

  73. Object object = null;

  74. object = redisTemplate.execute(new RedisCallback<Object>() {

  75. public Object doInRedis(RedisConnection connection)

  76. throws DataAccessException {

  77.  
  78. byte[] key = keyf.getBytes();

  79. byte[] value = connection.get(key);

  80. if (value == null) {

  81. return null;

  82. }

  83. return toObject(value);

  84.  
  85. }

  86. });

  87. return object != null ? new SimpleValueWrapper(object) : null;

  88. }

  89.  
  90. /**

  91. * 新建

  92. */

  93. @Override

  94. public void put(Object key, Object value) {

  95. final String keyf = (String)key;

  96. final Object valuef = value;

  97.  
  98. redisTemplate.execute(new RedisCallback<Long>() {

  99. public Long doInRedis(RedisConnection connection)

  100. throws DataAccessException {

  101. byte[] keyb = keyf.getBytes();

  102. byte[] valueb = toByteArray(valuef);

  103. connection.set(keyb, valueb);

  104. if (getLiveTime() > 0) {

  105. connection.expire(keyb, getLiveTime());

  106. }

  107. return 1L;

  108. }

  109. });

  110. }

  111.  
  112. /**

  113. * 删除

  114. */

  115. @Override

  116. public void clear() {

  117. redisTemplate.execute(new RedisCallback<String>() {

  118. public String doInRedis(RedisConnection connection)

  119. throws DataAccessException {

  120. connection.flushDb();

  121. return "ok";

  122. }

  123. });

  124. }

  125.  
  126. /**

  127. * 描述 : <Object转byte[]>. <br>

  128. * <p>

  129. * <使用方法说明>

  130. * </p>

  131. *

  132. * @param obj

  133. * @return

  134. */

  135. private byte[] toByteArray(Object obj) {

  136. byte[] bytes = null;

  137. ByteArrayOutputStream bos = new ByteArrayOutputStream();

  138. try {

  139. ObjectOutputStream oos = new ObjectOutputStream(bos);

  140. oos.writeObject(obj);

  141. oos.flush();

  142. bytes = bos.toByteArray();

  143. oos.close();

  144. bos.close();

  145. } catch (IOException ex) {

  146. LOGGER.error(ex.getMessage(),ex);

  147. }

  148. return bytes;

  149. }

  150.  
  151. /**

  152. * 描述 : <byte[]转Object>. <br>

  153. * <p>

  154. * <使用方法说明>

  155. * </p>

  156. *

  157. * @param bytes

  158. * @return

  159. */

  160. private Object toObject(byte[] bytes) {

  161. Object obj = null;

  162. try {

  163. ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

  164. ObjectInputStream ois = new ObjectInputStream(bis);

  165. obj = ois.readObject();

  166. ois.close();

  167. bis.close();

  168. } catch (IOException ex) {

  169. LOGGER.error(ex.getMessage(),ex);

  170. } catch (ClassNotFoundException ex) {

  171. LOGGER.error(ex.getMessage(),ex);

  172. }

  173. return obj;

  174. }

  175.  
  176. @Override

  177. public void evict(Object key) {

  178. final String keyf = (String)key;

  179. redisTemplate.execute(new RedisCallback<Long>() {

  180. public Long doInRedis(RedisConnection connection)

  181. throws DataAccessException {

  182. return connection.del(keyf.getBytes());

  183. }

  184. });

  185. }

  186.  
  187. @Override

  188. public <T> T get(Object key, Class<T> type) {

  189.  
  190. return null;

  191. }

  192.  
  193. @Override

  194. public ValueWrapper putIfAbsent(Object key, Object value) {

  195. return null;

  196. }

  197.  
  198. public long getLiveTime() {

  199. return liveTime;

  200. }

  201.  
  202. public void setLiveTime(long liveTime) {

  203. this.liveTime = liveTime;

  204. }

  205.  
  206. }


第三步:新建spring-redis.xml,配置Redis相关信息。

 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3. xmlns:cache="http://www.springframework.org/schema/cache" xmlns:c="http://www.springframework.org/schema/c"

  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

  5. xsi:schemaLocation="

  6. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

  7. http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

  8.  
  9. <!-- 开启缓存注解 -->

  10. <cache:annotation-driven cache-manager="cacheManager" />

  11.  
  12. <!-- jedis客户端连接工厂 -->

  13. <bean id="jedisConnectionFactory"

  14. class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"

  15. p:host-name="127.0.0.1" p:port="6379" p:password="123456" />

  16.  
  17. <!-- redisTemplate模板 -->

  18. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"

  19. p:connection-factory-ref="jedisConnectionFactory" />

  20.  
  21. <!-- spring自己的管理器,这里定义了三个缓存位置名称 ,既注解中的value -->

  22. <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">

  23. <property name="caches">

  24. <set>

  25. <bean class="com.qcjy.common.cache.RedisCache"> <!-- 短期缓存 1个小时-->

  26. <property name="redisTemplate" ref="redisTemplate" />

  27. <property name="name" value="shortTimeCache" />

  28. <property name="liveTime" value="3600" />

  29. </bean>

  30. <bean class="com.qcjy.common.cache.RedisCache"> <!-- 长期缓存 4个小时-->

  31. <property name="redisTemplate" ref="redisTemplate" />

  32. <property name="name" value="longTimeCache" />

  33. <property name="liveTime" value="14400" />

  34. </bean>

  35. <bean class="com.qcjy.common.cache.RedisCache"> <!-- 永久缓存 -->

  36. <property name="redisTemplate" ref="redisTemplate" />

  37. <property name="name" value="nerverTimeCache" />

  38. <property name="liveTime" value="0" />

  39. </bean>

  40. </set>

  41. </property>

  42. </bean>

  43. </beans>

com.qcjy.common.cache.RedisCache 是我的项目自定义cache的类路径,可根据自己项目类路径变换。

第四步:在spring配置文件中引入导入上面的redis缓存配置

 
  1. <!-- 集成Redis缓存框架 -->

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


第五步:在方法上面添加注解

 
  1. /**

  2. * getProject:根据id获取数据. <br/>

  3. * @author lcma

  4. * @param id

  5. * @return

  6. * @since JDK 1.7

  7. */

  8. @Override

  9. @Cacheable(value = "shortTimeCache", key = "'getProject'+#id")

  10. public Project getProject(String id) {

  11. return projectDao.getById(id);

  12. }


缓存注解有三种,分别是:@CachePut,@Cacheable,@CacheEvict。它们之间的区别下篇再做详解。

到此,Redis与Spring整合成功啦,哈哈。

猜你喜欢

转载自blog.csdn.net/wzq__janeGreen_/article/details/81501897