第一步:引入jar包
需要引入和Redis 相關的兩個jar包,一個是spring-data-redis.jar,另一個是jedis.jar。
具體的jar包在maven中心庫裏面都能找到。
maven項目pom.xml的配置:
- <!-- redis緩存 -->
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-redis</artifactId>
- <version>1.3.4.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>2.5.2</version>
- </dependency>
第二步:新建RedisCache.class類,自定義Cache。
- package com.qcjy.common.cache;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import org.apache.log4j.Logger;
- import org.springframework.cache.Cache;
- import org.springframework.cache.support.SimpleValueWrapper;
- import org.springframework.dao.DataAccessException;
- import org.springframework.data.redis.connection.RedisConnection;
- import org.springframework.data.redis.core.RedisCallback;
- import org.springframework.data.redis.core.RedisTemplate;
- /**
- * 自定義cache,可以定義一個cache名稱和一個緩存失效時間。時間到期會自動更新。在xml中配置。
- * <功能詳細描述>
- *
- * @author lcma
- * @version [版本號, 2016年9月12日]
- * @see [相關類/方法]
- * @since [產品/模塊版本]
- */
- public class RedisCache implements Cache {
- /**
- * LOG日誌
- */
- private static final Logger LOGGER = Logger.getLogger(RedisCache.class);
- private RedisTemplate<String, Object> redisTemplate;
- /**
- * 緩存名稱
- */
- private String name;
- /**
- * 緩存失效時間,時間到了會自動更新
- */
- private long liveTime = 0;
- public RedisTemplate<String, Object> getRedisTemplate() {
- return redisTemplate;
- }
- public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
- this.redisTemplate = redisTemplate;
- }
- public void setName(String name) {
- this.name = name;
- }
- @Override
- public String getName() {
- return this.name;
- }
- @Override
- public Object getNativeCache() {
- return this.redisTemplate;
- }
- /**
- * 獲取
- */
- @Override
- public ValueWrapper get(Object key) {
- final String keyf = (String)key;
- Object object = null;
- object = redisTemplate.execute(new RedisCallback<Object>() {
- public Object doInRedis(RedisConnection connection)
- throws DataAccessException {
- byte[] key = keyf.getBytes();
- byte[] value = connection.get(key);
- if (value == null) {
- return null;
- }
- return toObject(value);
- }
- });
- return object != null ? new SimpleValueWrapper(object) : null;
- }
- /**
- * 新建
- */
- @Override
- public void put(Object key, Object value) {
- final String keyf = (String)key;
- final Object valuef = value;
- redisTemplate.execute(new RedisCallback<Long>() {
- public Long doInRedis(RedisConnection connection)
- throws DataAccessException {
- byte[] keyb = keyf.getBytes();
- byte[] valueb = toByteArray(valuef);
- connection.set(keyb, valueb);
- if (getLiveTime() > 0) {
- connection.expire(keyb, getLiveTime());
- }
- return 1L;
- }
- });
- }
- /**
- * 刪除
- */
- @Override
- public void clear() {
- redisTemplate.execute(new RedisCallback<String>() {
- public String doInRedis(RedisConnection connection)
- throws DataAccessException {
- connection.flushDb();
- return "ok";
- }
- });
- }
- /**
- * 描述 : <Object轉byte[]>. <br>
- * <p>
- * <使用方法說明>
- * </p>
- *
- * @param obj
- * @return
- */
- private byte[] toByteArray(Object obj) {
- byte[] bytes = null;
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- try {
- ObjectOutputStream oos = new ObjectOutputStream(bos);
- oos.writeObject(obj);
- oos.flush();
- bytes = bos.toByteArray();
- oos.close();
- bos.close();
- } catch (IOException ex) {
- LOGGER.error(ex.getMessage(),ex);
- }
- return bytes;
- }
- /**
- * 描述 : <byte[]轉Object>. <br>
- * <p>
- * <使用方法說明>
- * </p>
- *
- * @param bytes
- * @return
- */
- private Object toObject(byte[] bytes) {
- Object obj = null;
- try {
- ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
- ObjectInputStream ois = new ObjectInputStream(bis);
- obj = ois.readObject();
- ois.close();
- bis.close();
- } catch (IOException ex) {
- LOGGER.error(ex.getMessage(),ex);
- } catch (ClassNotFoundException ex) {
- LOGGER.error(ex.getMessage(),ex);
- }
- return obj;
- }
- @Override
- public void evict(Object key) {
- final String keyf = (String)key;
- redisTemplate.execute(new RedisCallback<Long>() {
- public Long doInRedis(RedisConnection connection)
- throws DataAccessException {
- return connection.del(keyf.getBytes());
- }
- });
- }
- @Override
- public <T> T get(Object key, Class<T> type) {
- return null;
- }
- @Override
- public ValueWrapper putIfAbsent(Object key, Object value) {
- return null;
- }
- public long getLiveTime() {
- return liveTime;
- }
- public void setLiveTime(long liveTime) {
- this.liveTime = liveTime;
- }
- }
第三步:新建spring-redis.xml,配置Redis相關信息。
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:cache="http://www.springframework.org/schema/cache" xmlns:c="http://www.springframework.org/schema/c"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
- <!-- 開啓緩存註解 -->
- <cache:annotation-driven cache-manager="cacheManager" />
- <!-- jedis客戶端連接工廠 -->
- <bean id="jedisConnectionFactory"
- class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
- p:host-name="127.0.0.1" p:port="6379" p:password="123456" />
- <!-- redisTemplate模板 -->
- <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
- p:connection-factory-ref="jedisConnectionFactory" />
- <!-- spring自己的管理器,這裏定義了三個緩存位置名稱 ,既註解中的value -->
- <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
- <property name="caches">
- <set>
- <bean class="com.qcjy.common.cache.RedisCache"> <!-- 短期緩存 1個小時-->
- <property name="redisTemplate" ref="redisTemplate" />
- <property name="name" value="shortTimeCache" />
- <property name="liveTime" value="3600" />
- </bean>
- <bean class="com.qcjy.common.cache.RedisCache"> <!-- 長期緩存 4個小時-->
- <property name="redisTemplate" ref="redisTemplate" />
- <property name="name" value="longTimeCache" />
- <property name="liveTime" value="14400" />
- </bean>
- <bean class="com.qcjy.common.cache.RedisCache"> <!-- 永久緩存 -->
- <property name="redisTemplate" ref="redisTemplate" />
- <property name="name" value="nerverTimeCache" />
- <property name="liveTime" value="0" />
- </bean>
- </set>
- </property>
- </bean>
- </beans>
com.qcjy.common.cache.RedisCache 是我的項目自定義cache的類路徑,可根據自己項目類路徑變換。
- <!-- 集成Redis緩存框架 -->
- <import resource="spring-redis.xml" />
第五步:在方法上面添加註解
- /**
- * getProject:根據id獲取數據. <br/>
- * @author lcma
- * @param id
- * @return
- * @since JDK 1.7
- */
- @Override
- @Cacheable(value = "shortTimeCache", key = "'getProject'+#id")
- public Project getProject(String id) {
- return projectDao.getById(id);
- }