前因
處室的一個(gè)項(xiàng)目布卡,會(huì)有大量的數(shù)據(jù)需要頻繁被使用(查詢),很少做新增修改刪除的操作卧惜,這種數(shù)據(jù)很適合使用Redis進(jìn)行緩存厘灼,所以新的版本想把Redis引入進(jìn)來。
細(xì)化
使用Redis倒是難度不大咽瓷,但是怎么樣舒服的使用Redis就要多考慮一下了:
1手幢、可以使用Jedis直接對(duì)Redis操作,這樣的好處是全部自主掌控忱详,可以在自己需要的地方增加對(duì)Redis的操作围来,壞處也顯而易見,就是對(duì)現(xiàn)有代碼改造比較大匈睁;另外一種方法是监透,通過Mybatis的二級(jí)緩存實(shí)現(xiàn),優(yōu)點(diǎn)是航唆,對(duì)現(xiàn)有代碼改造少胀蛮,缺點(diǎn)也有,下面說糯钙。
2粪狼、單位對(duì)Redis的支持力度一般,不像有些公司會(huì)搭建平臺(tái)級(jí)的Redis任岸,我們都是每個(gè)項(xiàng)目自己搭建自己的Redis環(huán)境再榄。所以很多同事會(huì)對(duì)Redis的高可用性報(bào)以懷疑(主要因?yàn)椴皇煜ぃ砸WCRedis掛了之后享潜,系統(tǒng)可以照常使用(讀DB)困鸥。進(jìn)而要求做一個(gè)開關(guān),可以選擇性的使用Redis剑按〖簿停總結(jié),兩個(gè)問題:
1)設(shè)置開關(guān)艺蝴;關(guān)閉時(shí)猬腰,不使用Redis。
2)開關(guān)打開后猜敢,系統(tǒng)在運(yùn)行過程中姑荷,Redis掛了侮攀,系統(tǒng)應(yīng)該照常運(yùn)行。
3厢拭、領(lǐng)導(dǎo)想把Redis做成整個(gè)處室所有系統(tǒng)公用的,所以在Redis中的Key需要做一定的處理撇叁。
實(shí)現(xiàn)
吐槽一下供鸠,單位的網(wǎng)...連不上...github
1、pom.xml
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-redis</artifactId>
<version>1.0.0-beta2</version>
</dependency>
2陨闹、redis.properties楞捂,放到resource目錄下
redis.ip=localhost redis地址
redis.port=6379 redis端口
jedis.pool.maxActive=3000 最大連接數(shù)
jedis.pool.maxIdle=1000 空閑時(shí)最大連接數(shù)
jedis.pool.maxWait=1500 最大等待時(shí)間
jedis.pool.testOnBorrow=true
jedis.pool.testOnReturn=true
redis.switch = true 開關(guān)
redis.key = SOA redis的KEY,以這個(gè)開頭,區(qū)分系統(tǒng)
3趋厉、實(shí)現(xiàn)org.apache.ibatis.cache.Cache接口
見文章最下方
4寨闹、mybatis-config.xml開啟二級(jí)緩存
<setting name="cacheEnabled" value="true" />
5、mybatis的Mapper配置文件中增加配置:
<cache type="com.taikang.tms.cache.RedisCache" />
<select id="selectAllConfig" resultMap="dataSourceConfig" useCache="false">
select id,managecom,dataSourceName,managename from dataSourceConfig
</select>
其中useCache="false"表示君账,這個(gè)查詢SQL不進(jìn)行緩存繁堡。
<select id="selectConfigByManagecom" resultMap="dataSourceConfig" parameterType="String" useCache="true">
select id,managecom,dataSourceName,managename from dataSourceConfig where managecom=#{managecom}
</select>
useCache="true",這個(gè)查詢SQL的結(jié)果進(jìn)行緩存乡数。(第一個(gè)sql是查詢?nèi)客痔悖话氵@種sql我們不做緩存)
其余的insert、update净赴、delete操作绳矩,可以進(jìn)行如下配置:
flushCache="true/false",當(dāng)設(shè)置成true的時(shí)候玖翅,執(zhí)行sql會(huì)把redis中的緩存刪除(調(diào)用Cache實(shí)現(xiàn)類的clear()方法)翼馆,設(shè)置成false,則不做操作金度。
所以到這里也可以清楚的理解何時(shí)進(jìn)行緩存应媚、何時(shí)進(jìn)行刪除緩存了:
程序剛啟動(dòng)的時(shí)候,Redis中是空的猜极。
每次執(zhí)行select的時(shí)候珍特,首先會(huì)去redis讀取,讀取不到的話魔吐,再去db中查詢扎筒,查詢結(jié)束后,將結(jié)果存入redis中酬姆,注意嗜桌,如果sql查詢無結(jié)果,也會(huì)放入redis中辞色。
執(zhí)行insert骨宠、update、delete語句的時(shí)候,清除對(duì)應(yīng)的redis中的值层亿。
上面說到使用這種方式的缺點(diǎn)....就是...框架自動(dòng)生成的key看的很不爽桦卒,比如:
-189751634:3770288340:DataSourceConfigMapper.selectConfigByManagecom:0:2147483647:select id,managecom,dataSourceName,managename from dataSourceConfig where managecom=?:C
這是一個(gè)Key,從這個(gè)也能看出來匿又,有一部分是select的查詢語句方灾。前面的數(shù)字看起來就不爽了,沒有翻源碼碌更,不知道是啥含義裕偿。
這里還有一個(gè)坑需要注意,就是緩存刪除痛单,前面說過執(zhí)行mybatis配置文件中的insert嘿棘、update、delete操作的時(shí)候會(huì)刪除緩存旭绒,不過有些系統(tǒng)....會(huì)直接登錄到數(shù)據(jù)庫上做一些操作吧鸟妙,這種操作,緩存肯定是無法刪除的挥吵。
我們系統(tǒng)做的更簡單圆仔,因?yàn)槲覀兿到y(tǒng)中,這些需要緩存的數(shù)據(jù)基本上都是通過SQL語句初始化進(jìn)去的蔫劣,不需要前臺(tái)有維護(hù)頁面坪郭,所以...每次維護(hù)數(shù)據(jù)之和,手動(dòng)去redis中進(jìn)行flushdb脉幢⊥嵛郑或者考慮啟動(dòng)服務(wù)的時(shí)候刪除,或者前臺(tái)做一個(gè)按鈕什么的嫌松,點(diǎn)擊一下刪除redis中的緩存沪曙。
單位的網(wǎng)....不能連接github,今天嘗試了一下使用其他的代碼托管網(wǎng)站萎羔,也都失敗了液走,并且我沒有找到簡書上如何上傳附件,這次拼了贾陷,直接上代碼:
RedisCache.java
package com.taikang.tms.cache;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.taikang.tms.util.JedisUtils;
import com.taikang.tms.util.ConfigUtils;
public class RedisCache implements Cache {
private static Logger logger = LoggerFactory.getLogger(RedisCache.class);
private String cacheId;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
public RedisCache(String cacheId) {
if (cacheId == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.cacheId = ConfigUtils.key + "." + cacheId;
logger.info("NTSRedisCache cacheId ========== " + cacheId);
if(ConfigUtils.redisSwitch){
JedisUtils.getInstance();
}
}
@Override
public String getId() {
return cacheId;
}
@Override
public void putObject(Object key, Object value) {
//TODO:開關(guān)采用一個(gè)靜態(tài)變量缘眶,每個(gè)需要使用redis的地方,都判斷這個(gè)變量髓废,比較繁瑣
logger.info("NTSRedisCache putObject = " + cacheId);
if(ConfigUtils.redisSwitch){
JedisUtils.put(cacheId, key, value);
}
}
@Override
public Object getObject(Object key) {
logger.info("NTSRedisCache getObject = " + cacheId);
if(ConfigUtils.redisSwitch){
return JedisUtils.get(cacheId, key);
}else{
return null;
}
}
@Override
public Object removeObject(Object key) {
logger.info("NTSRedisCache removeObject = " + cacheId);
if(ConfigUtils.redisSwitch){
return JedisUtils.remove(cacheId, key);
}else{
return null;
}
}
@Override
public void clear() {
logger.info("NTSRedisCache clear = " + cacheId);
if(ConfigUtils.redisSwitch){
JedisUtils.removeAll(cacheId);
}
}
@Override
public int getSize() {
logger.info("NTSRedisCache getSize = " + cacheId);
if(ConfigUtils.redisSwitch){
return JedisUtils.getSize(cacheId);
}else{
return -1;
}
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
}
所用到的幾個(gè)工具類:
ConfigUtils.java
package com.taikang.tms.util;
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;
public class ConfigUtils {
private static Logger logger = LoggerFactory.getLogger(ConfigUtils.class);
public static boolean redisSwitch ;
public static int maxIdle ;
public static boolean testOnBorrow;
public static boolean testOnReturn;
public static String ip;
public static int port;
public static String key;
public static int fail_count = 0 ;
static {
Properties props = new Properties();
try {
props.load(JedisUtils.class.getResourceAsStream("/properties/redis.properties"));
redisSwitch = Boolean.valueOf(props.getProperty("redis.switch"));
maxIdle = Integer.valueOf(props.getProperty("jedis.pool.maxIdle"));
testOnBorrow = Boolean.valueOf(props.getProperty("jedis.pool.testOnBorrow"));
testOnReturn = Boolean.valueOf(props.getProperty("jedis.pool.testOnReturn"));
ip = props.getProperty("redis.ip") ;
port = Integer.valueOf(props.getProperty("redis.port"));
key = props.getProperty("redis.key") ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void setSwitch(boolean redisSwitch){
if(true == ConfigUtils.redisSwitch && false == redisSwitch){
//switch : open --> close
logger.info("switch : open --> close");
JedisUtils.closeJedisPool();
}else if(false == ConfigUtils.redisSwitch && true == redisSwitch){
//switch : close --> open
logger.info("switch : close --> open");
JedisUtils.getInstance();
}
ConfigUtils.redisSwitch = redisSwitch ;
}
//TODO:當(dāng)redis連接異常超過一定數(shù)量之后巷懈, 不再走redis,但是沒有一個(gè)機(jī)制,當(dāng)redis恢復(fù)之后會(huì)重新使用redis
public static void setFailCount(){
if(redisSwitch){
fail_count += 1;
//TODO:失敗數(shù)量配置到配置文件中
if(fail_count > 10){
logger.info(" setSwitch(false) ");
setSwitch(false);
}
}
}
public static void setSucc(){
if(fail_count > 0 ){
fail_count = 0 ;
}
if(!redisSwitch){
setSwitch(true);
}
}
}
JedisUtils.java
package com.taikang.tms.util;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import org.mybatis.caches.redis.RedisCallback;
import org.mybatis.caches.redis.SerializeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class JedisUtils {
private static Logger logger = LoggerFactory.getLogger(JedisUtils.class);
private static JedisPool JEDISPOOL;
public static void getInstance(){
if(JEDISPOOL == null){
logger.info(" JedisUtils getInstance ");
Properties props = new Properties();
try {
//TODO:配置文件固定慌洪,換成使用spring加載的方式
JedisPoolConfig conf = new JedisPoolConfig();
conf.setMaxIdle(ConfigUtils.maxIdle);
conf.setTestOnBorrow(ConfigUtils.testOnBorrow);
conf.setTestOnReturn(ConfigUtils.testOnReturn);
JEDISPOOL = new JedisPool(conf, ConfigUtils.ip, ConfigUtils.port);
} catch (Exception e) {
logger.error("加載[jedis.properties]異常[" + e.getMessage() + "]", e);
}
}
}
public static Jedis getJedis() {
try{
return JEDISPOOL.getResource();
}catch (Exception e) {
//throw new JedisConnectionException("Could not get a resource from the pool");
return null;
}
}
public static void recycleJedis(Jedis jedis) {
if(jedis != null){
jedis.close();
}
}
public static void closeJedisPool(){
if(JEDISPOOL != null){
JEDISPOOL.close();
}
}
/**
* Redis存儲(chǔ)Object序列化流
* */
public static void put(String id , Object key, Object value) {
Jedis jedis = getJedis();
try{
logger.info(" redis put ... key = [" + key + "]");
//jedis.set(SerializeUtils.serialize(key), SerializeUtils.serialize(value));
jedis.hset(id.toString().getBytes(), key.toString().getBytes(), SerializeUtils.serialize(value));
//TODO:考慮用切片處理
ConfigUtils.setSucc();
}catch(Exception e){
//TODO:異常放在utils中捕捉顶燕,還是在NTSRedisCache捕捉
//TODO:統(tǒng)一異常處理方法
ConfigUtils.setFailCount();
logger.error("Redis執(zhí)行異常[" + e.getMessage() + "]" , e);
}finally {
recycleJedis(jedis);
}
}
public static <T> T get(String id , Object key) {
Jedis jedis = getJedis();
try{
//T value = SerializeUtils.unserialize(jedis.get(SerializeUtils.serialize(key)));
T value = SerializeUtils.unserialize(jedis.hget(id.toString().getBytes(), key.toString().getBytes()));
logger.info(" redis get ... key = [" + key + "] , value = [" + value + "]");
ConfigUtils.setSucc();
return value;
}catch(Exception e){
ConfigUtils.setFailCount();
logger.error("Redis執(zhí)行異常[" + e.getMessage() + "]" , e);
}finally {
recycleJedis(jedis);
}
return null;
}
public static Long remove(String id , Object key) {
Jedis jedis = getJedis();
try{
Long num = jedis.hdel(id.toString(), key.toString());;
//Long num = jedis.del(SerializeUtils.serialize(key));
ConfigUtils.setSucc();
return num;
}catch(Exception e){
ConfigUtils.setFailCount();
logger.error("Redis執(zhí)行異常[" + e.getMessage() + "]" , e);
}finally {
recycleJedis(jedis);
}
return 0L;
}
public static void removeAll(String id) {
Jedis jedis = getJedis();
try{
jedis.del(id.toString());
//jedis.flushDB();
ConfigUtils.setSucc();
}catch(Exception e){
ConfigUtils.setFailCount();
logger.error("Redis執(zhí)行異常[" + e.getMessage() + "]" , e);
}finally {
recycleJedis(jedis);
}
}
public static int getSize(String id) {
return 0;
/*Jedis jedis = getJedis();
try{
Map<byte[], byte[]> result = jedis.hgetAll(id.toString().getBytes());
return result.size();
}catch(Exception e){
ConfigUtils.setFailCount();
logger.error("Redis執(zhí)行異常[" + e.getMessage() + "]" , e);
}finally {
recycleJedis(jedis);
}
return -1 ;*/
}
}
SerializeUtils.java
package com.taikang.tms.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtils {
//private static final Logger logger = Logger.getLogger(SerializeUtils.class);
private static void close(ObjectOutputStream objectOutputStream, ByteArrayOutputStream byteArrayOutputStream) {
try {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
//logger.error("關(guān)閉IO資源異常[" + e.getMessage() + "]", e);
}
}
private static void close(ObjectInputStream objectInputStream, ByteArrayInputStream byteArrayInputStream) {
try {
if (objectInputStream != null) {
objectInputStream.close();
}
if (byteArrayInputStream != null) {
byteArrayInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
//logger.error("關(guān)閉IO資源異常[" + e.getMessage() + "]", e);
}
}
public static byte[] serialize(Object object) {
ObjectOutputStream objectOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
byte[] bytes = byteArrayOutputStream.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
//logger.error("序列化對(duì)象異常[" + e.getMessage() + "]", e);
} finally {
close(objectOutputStream, byteArrayOutputStream);
}
return null;
}
@SuppressWarnings("unchecked")
public static <T> T unserialize(byte[] bytes) {
if (bytes == null)
return null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
byteArrayInputStream = new ByteArrayInputStream(bytes);
objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (T) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(objectInputStream, byteArrayInputStream);
}
return null;
}
}
測(cè)試用例...就不貼了敞映,我繼續(xù)找找單位可以使用的代碼托管軟件..話說辽幌,今天連各種SVN都試過了嗤瞎。