Skip to content

Commit ed35069

Browse files
author
邱家榆
committed
增加JedisCluster的支持
1 parent 76e7843 commit ed35069

File tree

8 files changed

+196
-22
lines changed

8 files changed

+196
-22
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<modelVersion>4.0.0</modelVersion>
33
<groupId>com.github.qiujiayu</groupId>
44
<artifactId>autoload-cache</artifactId>
5-
<version>4.16</version>
5+
<version>4.17</version>
66
<packaging>jar</packaging>
77
<name>AutoLoadCache</name>
88
<description>User AOP and annotation to do with cache.</description>

src/main/java/com/jarvis/cache/admin/servlet/AdminServlet.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,7 @@ private void printHtmlHead(HttpServletResponse resp, String cacheManagerName) th
161161
html.append("<html>").append("<head>").append("<title>Cache Admin</title>");
162162
html.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
163163
html.append("<style type=\"text/css\">");
164-
html.append(
165-
"th {text-align: center; line-height: 24px; border-top: 1px solid #555555; border-bottom: 1px solid #555555; border-right: 1px solid #555555; word-wrap: break-word; }");
164+
html.append("th {text-align: center; line-height: 24px; border-top: 1px solid #555555; border-bottom: 1px solid #555555; border-right: 1px solid #555555; word-wrap: break-word; }");
166165
html.append("table { border-left: 1px solid #555555; }");
167166
html.append("td { border-right: 1px solid #555555; border-bottom: 1px solid #555555; text-align: center; line-height: 24px; word-wrap: break-word; }");
168167
html.append("</style>");
@@ -223,8 +222,7 @@ private void printForm(HttpServletResponse resp, String cacheManagerName, String
223222
html.append("</select>");
224223
html.append("<input type=\"submit\" value=\"更改缓存\"></input>");
225224
html.append("</form>");
226-
html.append(
227-
"cache key:<input type=\"text\" id=\"deleteCacheKey\"/> <input type=\"button\" onclick=\"removeCache(document.getElementById('deleteCacheKey').value)\" value=\"删除缓存\"/>");
225+
html.append("cache key:<input type=\"text\" id=\"deleteCacheKey\"/> <input type=\"button\" onclick=\"removeCache(document.getElementById('deleteCacheKey').value)\" value=\"删除缓存\"/>");
228226
html.append("<form id=\"updateCacheForm\" action=\"\" method=\"get\" target=\"_blank\">");
229227
html.append("<input type=\"hidden\" id=\"act\" name=\"act\" value=\"\" />");
230228
html.append("<input type=\"hidden\" id=\"cacheKey\" name=\"cacheKey\" value=\"\" />");
@@ -280,8 +278,7 @@ private void printList(HttpServletRequest req, HttpServletResponse resp, Abstrac
280278
html.append(" <td>" + getDateFormat(tmpTO.getFirstRequestTime()) + "</td>");
281279
html.append(" <td>" + tmpTO.getRequestTimes() + "次</td>");
282280
html.append(" <td>" + getDateFormat(tmpTO.getLastLoadTime() + tmpTO.getCache().expire() * 1000) + "(" + tmpTO.getCache().expire() + "秒)</td>");
283-
html.append(
284-
" <td>" + getDateFormat(tmpTO.getLastRequestTime() + tmpTO.getCache().requestTimeout() * 1000) + "(" + tmpTO.getCache().requestTimeout() + "秒)</td>");
281+
html.append(" <td>" + getDateFormat(tmpTO.getLastRequestTime() + tmpTO.getCache().requestTimeout() * 1000) + "(" + tmpTO.getCache().requestTimeout() + "秒)</td>");
285282
html.append(" <td>" + getDateFormat(tmpTO.getLastLoadTime()) + "</td>");
286283
html.append(" <td>" + tmpTO.getLoadCnt() + "次</td>");
287284
html.append(" <td>" + tmpTO.getAverageUseTime() + "毫秒</td>");
@@ -290,8 +287,8 @@ private void printList(HttpServletRequest req, HttpServletResponse resp, Abstrac
290287
html.append(" <td><a href=\"javascript:void()\" onclick=\"resetLastLoadTime('" + _key + "','" + _hfield + "')\">重置最后加载时间</a></td>");
291288
html.append("<td>");
292289
if(null != tmpTO.getArgs() && tmpTO.getArgs().length > 0) {
293-
html.append("<a href=\"" + req.getContextPath() + req.getServletPath() + "?act=showArgs&cacheManagerName=" + cacheManagerName + "&cacheKey=" + _key
294-
+ "&hfield=" + _hfield + "\" target=\"_blank\">show args values</a>");
290+
html.append("<a href=\"" + req.getContextPath() + req.getServletPath() + "?act=showArgs&cacheManagerName=" + cacheManagerName + "&cacheKey=" + _key + "&hfield=" + _hfield
291+
+ "\" target=\"_blank\">show args values</a>");
295292
}
296293
html.append("</td>");
297294
html.append(" </tr>");

src/main/java/com/jarvis/cache/comparator/AutoLoadOldestComparator.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55
import com.jarvis.cache.to.AutoLoadTO;
66

77
/**
8-
* 排序算法:越接近过期时间,越耗时的排在最前,即: System.currentTimeMillis() - autoLoadTO.getLastLoadTime()-autoLoadTO.getExpire()*1000 值越大,排在越前
9-
* autoLoadTO.getAverageUseTime() 值越大,排在越前
8+
* 排序算法:越接近过期时间,越耗时的排在最前,即: System.currentTimeMillis() - autoLoadTO.getLastLoadTime()-autoLoadTO.getExpire()*1000 值越大,排在越前 autoLoadTO.getAverageUseTime() 值越大,排在越前
109
* @author jiayu.qiu
1110
*/
1211
public class AutoLoadOldestComparator implements Comparator<AutoLoadTO> {

src/main/java/com/jarvis/cache/map/CachePointCut.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
* @author jiayu.qiu
2020
*/
2121
public class CachePointCut extends AbstractCacheManager {
22-
22+
2323
private static final Logger logger=Logger.getLogger(CachePointCut.class);
2424

2525
private final ConcurrentHashMap<String, Object> cache=new ConcurrentHashMap<String, Object>();
@@ -117,7 +117,7 @@ public void setCache(final CacheKeyTO cacheKeyTO, final CacheWrapper<Object> res
117117
if(tmpObj instanceof ConcurrentHashMap) {
118118
hash=(ConcurrentHashMap<String, SoftReference<CacheWrapper<Object>>>)tmpObj;
119119
} else {
120-
logger.error(method.getClass().getName()+"."+method.getName()+"中key为"+cacheKey+"的缓存,已经被占用,请删除缓存再试。");
120+
logger.error(method.getClass().getName() + "." + method.getName() + "中key为" + cacheKey + "的缓存,已经被占用,请删除缓存再试。");
121121
return;
122122
}
123123
}
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
package com.jarvis.cache.redis;
2+
3+
import java.lang.reflect.Method;
4+
import java.lang.reflect.Type;
5+
6+
import org.apache.log4j.Logger;
7+
8+
import com.jarvis.cache.AbstractCacheManager;
9+
import com.jarvis.cache.exception.CacheCenterConnectionException;
10+
import com.jarvis.cache.script.AbstractScriptParser;
11+
import com.jarvis.cache.serializer.ISerializer;
12+
import com.jarvis.cache.serializer.StringSerializer;
13+
import com.jarvis.cache.to.AutoLoadConfig;
14+
import com.jarvis.cache.to.CacheKeyTO;
15+
import com.jarvis.cache.to.CacheWrapper;
16+
17+
import redis.clients.jedis.JedisCluster;
18+
import redis.clients.jedis.ShardedJedis;
19+
20+
/**
21+
* Redis缓存管理
22+
* @author jiayu.qiu
23+
*/
24+
public class JedisClusterCacheManager extends AbstractCacheManager {
25+
26+
private static final Logger logger=Logger.getLogger(JedisClusterCacheManager.class);
27+
28+
private static final StringSerializer keySerializer=new StringSerializer();
29+
30+
private JedisCluster jedisCluster;
31+
32+
/**
33+
* Hash的缓存时长:等于0时永久缓存;大于0时,主要是为了防止一些已经不用的缓存占用内存;hashExpire小于0时,则使用@Cache中设置的expire值(默认值为-1)。
34+
*/
35+
private int hashExpire=-1;
36+
37+
/**
38+
* 是否通过脚本来设置 Hash的缓存时长
39+
*/
40+
private boolean hashExpireByScript=false;
41+
42+
public JedisClusterCacheManager(AutoLoadConfig config, ISerializer<Object> serializer, AbstractScriptParser scriptParser) {
43+
super(config, serializer, scriptParser);
44+
}
45+
46+
private void returnResource(ShardedJedis shardedJedis) {
47+
shardedJedis.close();
48+
}
49+
50+
@Override
51+
public void setCache(final CacheKeyTO cacheKeyTO, final CacheWrapper<Object> result, final Method method, final Object args[]) throws CacheCenterConnectionException {
52+
if(null == jedisCluster || null == cacheKeyTO) {
53+
return;
54+
}
55+
String cacheKey=cacheKeyTO.getCacheKey();
56+
if(null == cacheKey || cacheKey.length() == 0) {
57+
return;
58+
}
59+
ShardedJedis shardedJedis=null;
60+
try {
61+
int expire=result.getExpire();
62+
String hfield=cacheKeyTO.getHfield();
63+
if(null == hfield || hfield.length() == 0) {
64+
if(expire == 0) {
65+
66+
jedisCluster.set(keySerializer.serialize(cacheKey), getSerializer().serialize(result));
67+
} else {
68+
jedisCluster.setex(keySerializer.serialize(cacheKey), expire, getSerializer().serialize(result));
69+
}
70+
} else {
71+
hashSet(cacheKey, hfield, result);
72+
}
73+
} catch(Exception ex) {
74+
logger.error(ex.getMessage(), ex);
75+
} finally {
76+
returnResource(shardedJedis);
77+
}
78+
}
79+
80+
private void hashSet(String cacheKey, String hfield, CacheWrapper<Object> result) throws Exception {
81+
byte[] key=keySerializer.serialize(cacheKey);
82+
byte[] field=keySerializer.serialize(hfield);
83+
byte[] val=getSerializer().serialize(result);
84+
int hExpire;
85+
if(hashExpire < 0) {
86+
hExpire=result.getExpire();
87+
} else {
88+
hExpire=hashExpire;
89+
}
90+
if(hExpire == 0) {
91+
jedisCluster.hset(key, field, val);
92+
} else {
93+
jedisCluster.hset(key, field, val);
94+
jedisCluster.expire(key, hExpire);
95+
}
96+
}
97+
98+
@SuppressWarnings("unchecked")
99+
@Override
100+
public CacheWrapper<Object> get(final CacheKeyTO cacheKeyTO, final Method method, final Object args[]) throws CacheCenterConnectionException {
101+
if(null == jedisCluster || null == cacheKeyTO) {
102+
return null;
103+
}
104+
String cacheKey=cacheKeyTO.getCacheKey();
105+
if(null == cacheKey || cacheKey.length() == 0) {
106+
return null;
107+
}
108+
CacheWrapper<Object> res=null;
109+
ShardedJedis shardedJedis=null;
110+
try {
111+
byte bytes[]=null;
112+
String hfield=cacheKeyTO.getHfield();
113+
if(null == hfield || hfield.length() == 0) {
114+
bytes=jedisCluster.get(keySerializer.serialize(cacheKey));
115+
} else {
116+
bytes=jedisCluster.hget(keySerializer.serialize(cacheKey), keySerializer.serialize(hfield));
117+
}
118+
Type returnType=method.getGenericReturnType();
119+
res=(CacheWrapper<Object>)getSerializer().deserialize(bytes, returnType);
120+
} catch(Exception ex) {
121+
logger.error(ex.getMessage(), ex);
122+
} finally {
123+
returnResource(shardedJedis);
124+
}
125+
return res;
126+
}
127+
128+
/**
129+
* 根据缓存Key删除缓存
130+
* @param cacheKeyTO 缓存Key
131+
*/
132+
@Override
133+
public void delete(CacheKeyTO cacheKeyTO) throws CacheCenterConnectionException {
134+
if(null == jedisCluster || null == cacheKeyTO) {
135+
return;
136+
}
137+
String cacheKey=cacheKeyTO.getCacheKey();
138+
if(null == cacheKey || cacheKey.length() == 0) {
139+
return;
140+
}
141+
logger.debug("delete cache:" + cacheKey);
142+
try {
143+
String hfield=cacheKeyTO.getHfield();
144+
if(null == hfield || hfield.length() == 0) {
145+
jedisCluster.del(keySerializer.serialize(cacheKey));
146+
} else {
147+
jedisCluster.hdel(keySerializer.serialize(cacheKey), keySerializer.serialize(hfield));
148+
}
149+
this.getAutoLoadHandler().resetAutoLoadLastLoadTime(cacheKeyTO);
150+
} catch(Exception ex) {
151+
logger.error(ex.getMessage(), ex);
152+
} finally {
153+
}
154+
}
155+
156+
public JedisCluster getJedisCluster() {
157+
return jedisCluster;
158+
}
159+
160+
public void setJedisCluster(JedisCluster jedisCluster) {
161+
this.jedisCluster=jedisCluster;
162+
}
163+
164+
public int getHashExpire() {
165+
return hashExpire;
166+
}
167+
168+
public void setHashExpire(int hashExpire) {
169+
if(hashExpire < 0) {
170+
return;
171+
}
172+
this.hashExpire=hashExpire;
173+
}
174+
175+
public boolean isHashExpireByScript() {
176+
return hashExpireByScript;
177+
}
178+
179+
public void setHashExpireByScript(boolean hashExpireByScript) {
180+
this.hashExpireByScript=hashExpireByScript;
181+
}
182+
}

src/main/java/com/jarvis/cache/reflect/generics/ParameterizedTypeImpl.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,17 +64,15 @@ public boolean equals(Object paramObject) {
6464
Type localType1=localParameterizedType.getOwnerType();
6565
Type localType2=localParameterizedType.getRawType();
6666

67-
return (this.ownerType == null ? localType1 == null : this.ownerType.equals(localType1))
68-
&& (this.rawType == null ? localType2 == null : this.rawType.equals(localType2))
67+
return (this.ownerType == null ? localType1 == null : this.ownerType.equals(localType1)) && (this.rawType == null ? localType2 == null : this.rawType.equals(localType2))
6968
&& (Arrays.equals(this.actualTypeArguments, localParameterizedType.getActualTypeArguments()));
7069
}
7170

7271
return false;
7372
}
7473

7574
public int hashCode() {
76-
return Arrays.hashCode(this.actualTypeArguments) ^ (this.ownerType == null ? 0 : this.ownerType.hashCode())
77-
^ (this.rawType == null ? 0 : this.rawType.hashCode());
75+
return Arrays.hashCode(this.actualTypeArguments) ^ (this.ownerType == null ? 0 : this.ownerType.hashCode()) ^ (this.rawType == null ? 0 : this.rawType.hashCode());
7876
}
7977

8078
public String toString() {

src/main/java/com/jarvis/cache/serializer/StringSerializer.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55
import java.nio.charset.Charset;
66

77
/**
8-
* Simple String to byte[] (and back) serializer. Converts Strings into bytes and vice-versa using the specified charset (by default
9-
* UTF-8).
8+
* Simple String to byte[] (and back) serializer. Converts Strings into bytes and vice-versa using the specified charset (by default UTF-8).
109
* <p>
1110
* Useful when the interaction with the Redis happens mainly through Strings.
1211
* </p>

src/main/java/com/jarvis/lib/util/BeanUtil.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,8 @@ public class BeanUtil {
2828
* @return boolean true or false
2929
*/
3030
public static boolean isPrimitive(Object obj) {
31-
boolean rv=obj.getClass().isPrimitive() || obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Byte
32-
|| obj instanceof Character || obj instanceof Boolean || obj instanceof Short || obj instanceof Float || obj instanceof Double || obj instanceof BigDecimal
33-
|| obj instanceof BigInteger;
31+
boolean rv=obj.getClass().isPrimitive() || obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Byte || obj instanceof Character || obj instanceof Boolean
32+
|| obj instanceof Short || obj instanceof Float || obj instanceof Double || obj instanceof BigDecimal || obj instanceof BigInteger;
3433
return rv;
3534
}
3635

0 commit comments

Comments
 (0)