Redis大家都耳熟能詳,怎麼使用我沒太多發言權,14年就接觸使用了redis,當時作爲一個小菜鳥,沿用公司封裝的redis做了一個redis定義規劃使用,4年後當重新來看redis的時候,發現自己還是一知半解,結合網上的資料,總算是可以用了,但是個人覺得問題還諸多,先記錄一下吧。
假裝是前言
時下我仍然還是喜歡用maven作爲項目管理工具,我比較喜歡這樣的配置風格,再加上使用了很多年了,相對來說更熟悉。(現在有個叫gradle的,大家有興趣的可以瞭解一下)
一、配置篇
1.增加redis的相關maven配置
<!-- redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<!-- redis end -->
這個jedis的版本似乎有點要求,和不同的spring版本搭配有點差別,我這裏的spring版本是 4.3.9.RELEASE
2.增加Redis工具類RedisCacheUtil
package 你的包路徑;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.Callable;
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;
/**
* Redis操作工具類
* @author Vin Tan
* @date 2018年2月24日下午3:15:13
*/
public class RedisCacheUtil implements Cache{
private RedisTemplate<String, Object> redisTemplate;
private String name;
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) {
System.out.println("get key");
final String keyf = key.toString();
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) {
System.out.println("put key");
final String keyf = key.toString();
final Object valuef = value;
final long liveTime = 86400;
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 (liveTime > 0) {
connection.expire(keyb, liveTime);
}
return 1L;
}
});
}
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) {
ex.printStackTrace();
}
return bytes;
}
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) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}
@Override
public void evict(Object key) {
System.out.println("del key");
final String keyf = key.toString();
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
return connection.del(keyf.getBytes());
}
});
}
@Override
public void clear() {
// TODO Auto-generated method stub
System.out.println("clear key");
redisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection)
throws DataAccessException {
connection.flushDb();
return "ok";
}
});
}
@Override
public <T> T get(Object key, Class<T> type) {
// TODO Auto-generated method stub
return null;
}
@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T get(Object arg0, Callable<T> arg1) {
// TODO Auto-generated method stub
return null;
}
}
自行修改下包路徑吧,當然這個類我也是抄的,這個類主要作用就是讀寫刪了,操作redis用的
3.增加redis屬性文件redis.properties
redis.host=127.0.0.1
redis.port=6379
#一個pool最多可有多少個狀態爲idle(空閒)的jedis實例
redis.maxIdle=30
redis.minIdle=6
redis.maxWait=3000
#一個pool可分配多少個jedis實例
redis.maxTotal=2048
redis.expiration=30000
這個配置的解釋就不多贅述吧,但是注意一點,不同版本的redis的這個key值有所變化,自己去發現吧
4.增加redis-Spring配置文件spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
<context:property-placeholder location="classpath*:config/redis.properties" />
<!-- 啓用緩存註解功能,這個是必須的,否則註解不會生效,另外,該註解一定要聲明在spring主配置文件中才會生效 -->
<cache:annotation-driven cache-manager="cacheManager" />
<!-- redis 相關配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="true" />
</bean>
<bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="JedisConnectionFactory" />
</bean>
<!-- spring自己的緩存管理器,這裏定義了緩存位置名稱 ,即註解中的value -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<!-- 這裏可以配置多個redis -->
<bean class="com..logic.utils.RedisCacheUtil">
<property name="redisTemplate" ref="redisTemplate" />
<property name="name" value="common" />
<!-- common名稱要在類或方法的註解中使用 -->
</bean>
</set>
</property>
</bean>
</beans>
注意把自己的RedisCacheUtil的包路徑重新填寫一下,別照抄了,你懂的。
到此該配的都配好了,按以前的做法,肯定是再把spring-redis.xml配置到web.xml中一起加載,但是我在網上看到一個帖子說那樣是不行的,我也試了確實不行,說是需要把srping-redis.xml配置到主spring文件中加載才行,
所以呢,大家只需要在主spring文件中加上以下這行代碼即可
<!-- 引入同文件夾下的redis屬性配置文件 -->
<import resource="spring-redis.xml"/>
二、使用篇
接下來說下如何使用吧,使用之前,大家需要先永遠redis服務器,一般都是在linux上搭建redis服務器,這塊自行準備完成,不難。
14年那會我記得我用的redis是公司封裝了,利用的是AOP攔截機制,切入式讀寫緩存,現在再看,發現想利用當時的方式已經不那麼好用了,不得不感慨Spring的強大,spring耍皮,直接和cache玩註解了,作爲一個研究技術不那麼深的我來說,好吧,你牛皮。spring可以和各類緩存搭配使用,像Ecahe,Redis等。
關於Spring和Cahe的註解說明我這裏也找了一個帖子,大家可以看看:
https://www.cnblogs.com/fashflying/p/6908028.html
整體來說,Srping提供了3種緩存註解
@Cacheable、@CacheEvict、@CachePut
用法自行看那個帖子吧,根據自身業務需求選擇相應的註解即可
but,
這個註解有個很不爽的問題,在同一個類中的方法中二次調用本類中的其他方法,第二次調用的方法結果是不能被緩存的!!!WTF?這就很尷尬啊。。。(本人才疏學淺,無法理解,希望有大神給解釋說明一下)
總之就是,你在一個方法中,可以緩存你第一次的結果,如果你在方法中再次調用同類中的另外的方法是不能緩存的。大概場景就是:你在一個service實現類中調用方法的時候,只能緩存第一次的結果,在該類中第二次調用的方法是不會觸發緩存的。
對應的解決方案是:你在crontroller中分別調用2個不同service類的方法。
1.在serviceImpl中使用redis
@Cacheable(value="common",key="'status0'")
public String querySomeTime(Map<String, Object> map) {
return mapper.query(map);
}
@Cacheable(value="common",key="'id_'+#userId")
public User getUser(String userId){
return userMapper.getUser(userId);
}
關鍵就是@Cacheable註解,
value值:對應spring-redis.xml中cacheManager中配置的name。
key值:redis的key值,請保證唯一,否則會被覆蓋。可以通過#參數的方式獲取傳入的參數作爲key值
2.驗證緩存
可以通過斷點的方式看程序執行過程,是否是走數據庫還是直接從緩存服務器取。
結合緩存服務器查看緩存數量,通過命令直接從緩存服務器獲取對應的key-value。
三、總結
Redis是一個很強大的可基於內存亦可持久化的日誌型、Key-Value數據庫,應對大數據,大訪問量的時候,它也能hold住,掌握使用redis也是一項必備技能喲。
正如前面所說,註解方式存在我說的那種弊端,按理來說,這麼明顯的問題應該是不應該還存在的,或許是因爲我理解的不夠透徹,或許是真的存在,希望後續會有所結論。同時,如果你剛好看到又恰好有這方面的經驗,敬請賜教,不甚感激。
瞭解更多,可以關注公衆號:tanjava