[size=medium]
http://my.oschina.net/damihui/blog/173490
1.使用MAVEN引入使用的包。
view sourceprint?01 <dependency>
02 <groupId>redis.clients</groupId>
03 <artifactId>jedis</artifactId>
04 <version>2.1.0</version>
05 <scope>provided</scope>
06 </dependency>
07 <dependency>
08 <groupId>org.springframework</groupId>
09 <artifactId>spring-core</artifactId>
10 <version>3.1.0.RELEASE</version>
11 <scope>provided</scope>
12 </dependency>
13 <dependency>
14 <groupId>org.springframework</groupId>
15 <artifactId>spring-context</artifactId>
16 <version>3.1.0.RELEASE</version>
17 <scope>provided</scope>
18 </dependency>
19 <dependency>
20 <groupId>org.springframework</groupId>
21 <artifactId>spring-context-support</artifactId>
22 <version>3.1.0.RELEASE</version>
23 <scope>provided</scope>
24 </dependency>
25 <dependency>
26 <groupId>org.springframework</groupId>
27 <artifactId>spring-beans</artifactId>
28 <version>3.1.0.RELEASE</version>
29 <scope>provided</scope>
30 </dependency>
31 <dependency>
32 <groupId>org.springframework</groupId>
33 <artifactId>org.springframework.context</artifactId>
34 <version>3.1.0.RELEASE</version>
35 <scope>provided</scope>
36 </dependency>
37 <dependency>
38 <groupId>org.springframework</groupId>
39 <artifactId>spring-test</artifactId>
40 <version>3.1.0.RELEASE</version>
41 <scope>test</scope>
42 </dependency>
43 <dependency>
44 <groupId>commons-io</groupId>
45 <artifactId>commons-io</artifactId>
46 <version>1.3.2</version>
47 </dependency>
48 <dependency>
49 <groupId>commons-lang</groupId>
50 <artifactId>commons-lang</artifactId>
51 <version>2.3</version>
52 <scope>provided</scope>
53 </dependency>
54 <dependency>
55 <groupId>junit</groupId>
56 <artifactId>junit</artifactId>
57 <version>4.10</version>
58 <scope>test</scope>
59 </dependency>
60 <dependency>
61 <groupId>org.aspectj</groupId>
62 <artifactId>aspectjweaver</artifactId>
63 <version>1.6.12</version>
64 <scope>provided</scope>
65 </dependency>
66 <dependency>
67 <groupId>net.sourceforge.cglib</groupId>
68 <artifactId>com.springsource.net.sf.cglib</artifactId>
69 <version>2.2.0</version>
70 <scope>provided</scope>
71 </dependency>
72 <dependency>
73 <groupId>log4j</groupId>
74 <artifactId>log4j</artifactId>
75 <version>1.2.8</version>
76 </dependency>
2.Jedis的连接池配置需要用到org.apache.commons.pool.impl.GenericObjectPool.Config.class,此类是 GenericObjectPool的一个内部类,使用spring xml配置时需要转换成以下自定义类。
view sourceprint?001 package com.antilost.redis.util;
002
003 import org.apache.commons.pool.impl.GenericObjectPool;
004
005 /**
006 * User: ***
007 * Date: 13-8-27
008 * Time: 下午3:49
009 */
010 public class GenericObjectPoolConfigWrapper {
011
012 private final GenericObjectPool.Config config;
013
014 public GenericObjectPoolConfigWrapper() {
015 this.config = new GenericObjectPool.Config();
016 }
017
018 public GenericObjectPool.Config getConfig() {
019 return config;
020 }
021
022 public int getMaxIdle() {
023 return this.config.maxIdle;
024 }
025
026 public void setMaxIdle(int maxIdle) {
027 this.config.maxIdle = maxIdle;
028 }
029
030 public int getMinIdle() {
031 return this.config.minIdle;
032 }
033
034 public void setMinIdle(int minIdle) {
035 this.config.minIdle = minIdle;
036 }
037
038 public int getMaxActive() {
039 return this.config.maxActive;
040 }
041
042 public void setMaxActive(int maxActive) {
043 this.config.maxActive = maxActive;
044 }
045
046 public long getMaxWait() {
047 return this.config.maxWait;
048 }
049
050 public void setMaxWait(long maxWait) {
051 this.config.maxWait = maxWait;
052 }
053
054 public byte getWhenExhaustedAction() {
055 return this.config.whenExhaustedAction;
056 }
057
058 public void setWhenExhaustedAction(byte whenExhaustedAction) {
059 this.config.whenExhaustedAction = whenExhaustedAction;
060 }
061
062 public boolean isTestOnBorrow() {
063 return this.config.testOnBorrow;
064 }
065
066 public void setTestOnBorrow(boolean testOnBorrow) {
067 this.config.testOnBorrow = testOnBorrow;
068 }
069
070 public boolean isTestOnReturn() {
071 return this.config.testOnReturn;
072 }
073
074 public void setTestOnReturn(boolean testOnReturn) {
075 this.config.testOnReturn = testOnReturn;
076 }
077
078 public boolean isTestWhileIdle() {
079 return this.config.testWhileIdle;
080 }
081
082 public void setTestWhileIdle(boolean testWhileIdle) {
083 this.config.testWhileIdle = testWhileIdle;
084 }
085
086 public long getTimeBetweenEvictionRunsMillis() {
087 return this.config.timeBetweenEvictionRunsMillis;
088 }
089
090 public void setTimeBetweenEvictionRunsMillis( long timeBetweenEvictionRunsMillis) {
091 this.config.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
092 }
093
094 public int getNumTestsPerEvictionRun() {
095 return this.config.numTestsPerEvictionRun;
096 }
097
098 public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
099 this.config.numTestsPerEvictionRun = numTestsPerEvictionRun;
100 }
101
102 public long getMinEvictableIdleTimeMillis() {
103 return this.config.minEvictableIdleTimeMillis;
104 }
105
106 public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
107 this.config.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
108 }
109
110 public long getSoftMinEvictableIdleTimeMillis() {
111 return this.config.softMinEvictableIdleTimeMillis;
112 }
113
114 public void setSoftMinEvictableIdleTimeMillis( long softMinEvictableIdleTimeMillis) {
115 this.config.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
116 }
117
118 public boolean isLifo() {
119 return this.config.lifo;
120 }
121
122 public void setLifo(boolean lifo) {
123 this.config.lifo = lifo;
124 }
125 }
3.在Spring配置文件中注入GenericObjectPoolConfigWrapper.java类
view sourceprint?01 <aop:aspectj-autoproxy/>
02 <context:annotation-config />
03 <context:property-placeholder location="classpath:jedis.properties" ignore-unresolvable="true"/>
04 <bean id="jedisPoolConfig" class="com.antilost.redis.util.GenericObjectPoolConfigWrapper">
05 <!--最大连接数-->
06 <property name="maxActive" value="${${redis.pool.maxActive}}" />
07 <!--最大空闲连接数-->
08 <property name="maxIdle" value="${${redis.pool.maxIdle}}" />
09 <!--初始化连接数-->
10 <property name="minIdle" value="${${redis.pool.minIdle}}"/>
11 <!--最大等待时间-->
12 <property name="maxWait" value="${${redis.pool.maxWait}}" />
13 <!--对拿到的connection进行validateObject校验-->
14 <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
15 <!--在进行returnObject对返回的connection进行validateObject校验-->
16 <property name="testOnReturn" value="${redis.pool.testOnReturn}" />
17 <!--定时对线程池中空闲的链接进行validateObject校验-->
18 <property name="testWhileIdle" value="true" />
19 </bean>
4.Redis的连接配置文件jedis.properties中,定义了各个环境的连接参数,具体配置如下
view sourceprint?01 redis.pool.maxActive=redis.pool.maxActive.${ServerType}
02 redis.pool.maxIdle=redis.pool.maxIdle.${ServerType}
03 redis.pool.maxWait=redis.pool.maxWait.${ServerType}
04 redis.pool.minIdle=redis.pool.minIdle.${ServerType}
05 redis.host=redis.host.${ServerType}
06 redis.port=redis.port.${ServerType}
07 redis.password=redis.password.${ServerType}
08 redis.pool.testOnBorrow=true
09 redis.pool.testOnReturn=true
10 redis.timeout=1000
11 #C
12 #REL
13 redis.pool.maxActive.REL=200
14 redis.pool.maxIdle.REL=50
15 redis.pool.minIdle.REL=10
16 redis.pool.maxWait.REL=300
17 redis.host.REL=192.168.*.*
18 redis.port.REL=6379
19 redis.password.REL=***
20
21 #VRF
22 redis.pool.maxActive.VRF=200
23 redis.pool.maxIdle.VRF=50
24 redis.pool.minIdle.VRF=10
25 redis.pool.maxWait.VRF=300
26 redis.host.VRF=192.168.*.*
27 redis.port.VRF=6379
28 redis.password.VRF=***
根据系统环境变量JVM中ServerType的值,取不同的配置,实现多环境(测试环境、生产环境)集成。
5.Redis连接池配置
view sourceprint?01 <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
02 <constructor-arg index="0">
03 <bean factory-bean="jedisPoolConfig" factory-method="getConfig"/>
04 </constructor-arg>
05 <constructor-arg index="1" value="${${redis.host}}"/>
06 <constructor-arg index="2" value="${${redis.port}}"/>
07 <!--timeout-->
08 <constructor-arg index="3" value="${redis.timeout}"/>
09 <constructor-arg index="4" value="${${redis.password}}"/>
10 </bean>
6.Redis 工具类 view sourceprint?001 public abstract class JCacheTools {
002 public abstract int getDBIndex();
003 /**
004 * 默认日志打印logger_default
005 */
006 public static Logger logger_default = Logger.getLogger("logger_jCache_default");
007 /**
008 * 失败日志logger,用于定期del指定的key
009 */
010 public static Logger logger_failure = Logger.getLogger("logger_jCache_failure");
011
012 @Resource
013 protected JedisPool jedisPool;
014
015 protected Jedis getJedis() throws JedisException {
016 Jedis jedis = null;
017 try {
018 jedis = jedisPool.getResource();
019 } catch (JedisException e) {
020 LogContext.instance().warn(logger_failure, "failed:jedisPool getResource.", e);
021 if(jedis!=null){
022 jedisPool.returnBrokenResource(jedis);
023 }
024 throw e;
025 }
026 return jedis;
027 }
028
029 protected void release(Jedis jedis, boolean isBroken) {
030 if (jedis != null) {
031 if (isBroken) {
032 jedisPool.returnBrokenResource(jedis);
033 } else {
034 jedisPool.returnResource(jedis);
035 }
036 }
037 }
038
039 protected String addStringToJedis(String key, String value, int cacheSeconds, String methodName) {
040 Jedis jedis = null;
041 boolean isBroken = false;
042 String lastVal = null;
043 try {
044 jedis = this.getJedis();
045 jedis.select(getDBIndex());
046 lastVal = jedis.getSet(key, value);
047 if(cacheSeconds!=0){
048 jedis.expire(key,cacheSeconds);
049 }
050 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
051 } catch (Exception e) {
052 isBroken = true;
053 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
054 } finally {
055 release(jedis, isBroken);
056 }
057 return lastVal;
058 }
059
060 protected void addStringToJedis(Map<String,String> batchData, int cacheSeconds, String methodName) {
061 Jedis jedis = null;
062 boolean isBroken = false;
063 try {
064 jedis = this.getJedis();
065 jedis.select(getDBIndex());
066 Pipeline pipeline = jedis.pipelined();
067 for(Map.Entry<String,String> element:batchData.entrySet()){
068 if(cacheSeconds!=0){
069 pipeline.setex(element.getKey(),cacheSeconds,element.getValue());
070 }else{
071 pipeline.set(element.getKey(),element.getValue());
072 }
073 }
074 pipeline.sync();
075 LogContext.instance().debug(logger_default, "succeed:" + methodName,batchData.size());
076 } catch (Exception e) {
077 isBroken = true;
078 e.printStackTrace();
079 } finally {
080 release(jedis, isBroken);
081 }
082 }
083
084 protected void addListToJedis(String key, List<String> list, int cacheSeconds, String methodName) {
085 if (list != null && list.size() > 0) {
086 Jedis jedis = null;
087 boolean isBroken = false;
088 try {
089 jedis = this.getJedis();
090 jedis.select(getDBIndex());
091 if (jedis.exists(key)) {
092 jedis.del(key);
093 }
094 for (String aList : list) {
095 jedis.rpush(key, aList);
096 }
097 if(cacheSeconds!=0){
098 jedis.expire(key, cacheSeconds);
099 }
100 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list.size());
101 } catch (JedisException e) {
102 isBroken = true;
103 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list.size(), e);
104 } catch (Exception e) {
105 isBroken = true;
106 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list.size(), e);
107 } finally {
108 release(jedis, isBroken);
109 }
110 }
111 }
112
113 protected void addToSetJedis(String key, String[] value, String methodName) {
114 Jedis jedis = null;
115 boolean isBroken = false;
116 try {
117 jedis = this.getJedis();
118 jedis.select(getDBIndex());
119 jedis.sadd(key,value);
120 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
121 } catch (Exception e) {
122 isBroken = true;
123 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
124 } finally {
125 release(jedis, isBroken);
126 }
127 }
128
129 protected void removeSetJedis(String key,String value, String methodName) {
130 Jedis jedis = null;
131 boolean isBroken = false;
132 try {
133 jedis = this.getJedis();
134 jedis.select(getDBIndex());
135 jedis.srem(key,value);
136 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
137 } catch (Exception e) {
138 isBroken = true;
139 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
140 } finally {
141 release(jedis, isBroken);
142 }
143 }
144
145 protected void pushDataToListJedis(String key, String data, int cacheSeconds, String methodName) {
146 Jedis jedis = null;
147 boolean isBroken = false;
148 try {
149 jedis = this.getJedis();
150 jedis.select(getDBIndex());
151 jedis.rpush(key, data);
152 if(cacheSeconds!=0){
153 jedis.expire(key,cacheSeconds);
154 }
155 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, data);
156 } catch (Exception e) {
157 isBroken = true;
158 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, data, e);
159 } finally {
160 release(jedis, isBroken);
161 }
162 }
163 protected void pushDataToListJedis(String key,List<String> batchData, int cacheSeconds, String methodName) {
164 Jedis jedis = null;
165 boolean isBroken = false;
166 try {
167 jedis = this.getJedis();
168 jedis.select(getDBIndex());
169 jedis.del(key);
170 jedis.lpush(key,batchData.toArray(new String[batchData.size()]));
171 if(cacheSeconds!=0)
172 jedis.expire(key,cacheSeconds);
173 LogContext.instance().debug(logger_default, "succeed:" + methodName,batchData!=null?batchData.size():0);
174 } catch (Exception e) {
175 isBroken = true;
176 LogContext.instance().warn(logger_failure, "failed:" + methodName, batchData!=null?batchData.size():0, e);
177 } finally {
178 release(jedis, isBroken);
179 }
180 }
181
182 /**
183 * 删除list中的元素
184 * @param key
185 * @param values
186 * @param methodName
187 */
188 protected void deleteDataFromListJedis(String key,List<String> values, String methodName) {
189 Jedis jedis = null;
190 boolean isBroken = false;
191 try {
192 jedis = this.getJedis();
193 jedis.select(getDBIndex());
194 Pipeline pipeline = jedis.pipelined();
195 if(values!=null && !values.isEmpty()){
196 for (String val:values){
197 pipeline.lrem(key,0,val);
198 }
199 }
200 pipeline.sync();
201 LogContext.instance().debug(logger_default, "succeed:" + methodName,values!=null?values.size():0);
202 } catch (Exception e) {
203 isBroken = true;
204 LogContext.instance().warn(logger_failure, "failed:" + methodName, values!=null?values.size():0, e);
205 } finally {
206 release(jedis, isBroken);
207 }
208 }
209
210 protected void addHashMapToJedis(String key, Map<String, String> map, int cacheSeconds, boolean isModified, String methodName) {
211 boolean isBroken = false;
212 Jedis jedis = null;
213 if (map != null && map.size() > 0) {
214 try {
215 jedis = this.getJedis();
216 jedis.select(getDBIndex());
217 jedis.hmset(key, map);
218 if (cacheSeconds >= 0)
219 jedis.expire(key, cacheSeconds);
220 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, map.size());
221 } catch (Exception e) {
222 isBroken = true;
223 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, map.size(), e);
224 } finally {
225 release(jedis, isBroken);
226 }
227 }
228 }
229
230 protected void addHashMapToJedis(String key, String field, String value, int cacheSeconds, String methodName) {
231 boolean isBroken = false;
232 Jedis jedis = null;
233 try {
234 jedis = this.getJedis();
235 if (jedis != null) {
236 jedis.select(getDBIndex());
237 jedis.hset(key, field, value);
238 jedis.expire(key, cacheSeconds);
239 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, field, value);
240 }
241 } catch (Exception e) {
242 isBroken = true;
243 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, field, value, e);
244 }finally {
245 release(jedis, isBroken);
246 }
247 }
248
249 protected void updateHashMapToJedis(String key, String incrementField, long incrementValue, String dateField, String dateValue, String methodName) {
250 boolean isBroken = false;
251 Jedis jedis = null;
252 try {
253 jedis = this.getJedis();
254 jedis.select(getDBIndex());
255 jedis.hincrBy(key, incrementField, incrementValue);
256 jedis.hset(key, dateField, dateValue);
257 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, incrementField, incrementValue);
258 } catch (Exception e) {
259 isBroken = true;
260 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, incrementField, incrementValue, e);
261 }finally {
262 release(jedis, isBroken);
263 }
264 }
265
266 public String getStringFromJedis(String key, String methodName) {
267 String value = null;
268 Jedis jedis = null;
269 boolean isBroken = false;
270 try {
271 jedis = this.getJedis();
272 jedis.select(getDBIndex());
273 if (jedis.exists(key)) {
274 value = jedis.get(key);
275 value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value)?value:null;
276 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
277 }
278 } catch (Exception e) {
279 isBroken = true;
280 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
281 } finally {
282 release(jedis, isBroken);
283 }
284 return value;
285 }
286
287 public List<String> getStringFromJedis(String[] keys, String methodName) {
288 Jedis jedis = null;
289 boolean isBroken = false;
290 try {
291 jedis = this.getJedis();
292 jedis.select(getDBIndex());
293 return jedis.mget(keys);
294 } catch (Exception e) {
295 isBroken = true;
296 LogContext.instance().warn(logger_failure, "failed:" + methodName, Arrays.toString(keys), e);
297 } finally {
298 release(jedis, isBroken);
299 }
300 return null;
301 }
302
303 protected List<String> getListFromJedis(String key, String methodName) throws JMSCacheException {
304 List<String> list = null;
305 boolean isBroken = false;
306 Jedis jedis = null;
307 try {
308 jedis = this.getJedis();
309 jedis.select(getDBIndex());
310 if (jedis.exists(key)) {
311 list = jedis.lrange(key, 0, -1);
312 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list != null ? list.size() : 0);
313 }
314 } catch (JedisException e) {
315 isBroken = true;
316 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list != null ? list.size() : 0, e);
317 } finally {
318 release(jedis, isBroken);
319 }
320 return list;
321 }
322
323 protected Set<String> getSetFromJedis(String key, String methodName) throws JMSCacheException {
324 Set<String> list = null;
325 boolean isBroken = false;
326 Jedis jedis = null;
327 try {
328 jedis = this.getJedis();
329 jedis.select(getDBIndex());
330 if (jedis.exists(key)) {
331 list = jedis.smembers(key);
332 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list != null ? list.size() : 0);
333 }
334 } catch (Exception e) {
335 isBroken = true;
336 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list != null ? list.size() : 0, e);
337 } finally {
338 release(jedis, isBroken);
339 }
340 return list;
341 }
342
343 protected Map<String, String> getHashMapFromJedis(String key, String methodName) {
344 Map<String, String> hashMap = null;
345 boolean isBroken = false;
346 Jedis jedis = null;
347 try {
348 jedis = this.getJedis();
349 jedis.select(getDBIndex());
350 hashMap = jedis.hgetAll(key);
351 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, hashMap != null ? hashMap.size() : 0);
352 } catch (Exception e) {
353 isBroken = true;
354 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, hashMap != null ? hashMap.size() : 0, e);
355 } finally {
356 release(jedis, isBroken);
357 }
358 return hashMap;
359 }
360
361 protected String getHashMapValueFromJedis(String key, String field, String methodName) {
362 String value = null;
363 boolean isBroken = false;
364 Jedis jedis = null;
365 try {
366 jedis = this.getJedis();
367 if (jedis != null) {
368 jedis.select(getDBIndex());
369 if (jedis.exists(key)) {
370 value = jedis.hget(key, field);
371 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, field, value);
372 }
373 }
374 } catch (Exception e) {
375 isBroken = true;
376 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, field, value, e);
377 } finally {
378 release(jedis, isBroken);
379 }
380 return value;
381 }
382
383 public Long getIdentifyId(String identifyName ,String methodName) {
384 boolean isBroken = false;
385 Jedis jedis = null;
386 Long identify=null;
387 try {
388 jedis = this.getJedis();
389 if (jedis != null) {
390 jedis.select(getDBIndex());
391 identify = jedis.incr(identifyName);
392 if(identify==0){
393 return jedis.incr(identifyName);
394 }else {
395 return identify;
396 }
397 }
398 } catch (Exception e) {
399 isBroken = true;
400 LogContext.instance().warn(logger_failure, "failed:" + methodName, identifyName, "", identify, e);
401 } finally {
402 release(jedis, isBroken);
403 }
404 return null;
405 }
406
407
408 /**
409 * 删除某db的某个key值
410 * @param key
411 * @return
412 */
413 public Long delKeyFromJedis(String key) {
414 boolean isBroken = false;
415 Jedis jedis = null;
416 long result = 0;
417 try {
418 jedis = this.getJedis();
419 jedis.select(getDBIndex());
420 LogContext.instance().debug(logger_default, "succeed:delKeyFromJedis");
421 return jedis.del(key);
422 } catch (Exception e) {
423 isBroken = true;
424 LogContext.instance().warn(logger_failure, "failed:delKeyFromJedis", e);
425 } finally {
426 release(jedis, isBroken);
427 }
428 return result;
429 }
430
431 /**
432 * 根据dbIndex flushDB每个shard
433 *
434 * @param dbIndex
435 */
436 public void flushDBFromJedis(int dbIndex) {
437 Jedis jedis = null;
438 boolean isBroken = false;
439 try {
440 jedis = this.getJedis();
441 jedis.select(dbIndex);
442 jedis.flushDB();
443 LogContext.instance().debug(logger_default, "succeed:flushDBFromJedis");
444 } catch (Exception e) {
445 isBroken = true;
446 LogContext.instance().warn(logger_failure, "failed:flushDBFromJedis", e);
447 } finally {
448 release(jedis, isBroken);
449 }
450 }
451
452 public boolean existKey(String key, String methodName) {
453 Jedis jedis = null;
454 boolean isBroken = false;
455 try {
456 jedis = this.getJedis();
457 jedis.select(getDBIndex());
458 LogContext.instance().debug(logger_default, "succeed:"+methodName);
459 return jedis.exists(key);
460 } catch (Exception e) {
461 isBroken = true;
462 LogContext.instance().warn(logger_failure, "failed:"+methodName, e);
463 } finally {
464 release(jedis, isBroken);
465 }
466 return false;
467 }
468
469 } [/size]
http://my.oschina.net/damihui/blog/173490
1.使用MAVEN引入使用的包。
view sourceprint?01 <dependency>
02 <groupId>redis.clients</groupId>
03 <artifactId>jedis</artifactId>
04 <version>2.1.0</version>
05 <scope>provided</scope>
06 </dependency>
07 <dependency>
08 <groupId>org.springframework</groupId>
09 <artifactId>spring-core</artifactId>
10 <version>3.1.0.RELEASE</version>
11 <scope>provided</scope>
12 </dependency>
13 <dependency>
14 <groupId>org.springframework</groupId>
15 <artifactId>spring-context</artifactId>
16 <version>3.1.0.RELEASE</version>
17 <scope>provided</scope>
18 </dependency>
19 <dependency>
20 <groupId>org.springframework</groupId>
21 <artifactId>spring-context-support</artifactId>
22 <version>3.1.0.RELEASE</version>
23 <scope>provided</scope>
24 </dependency>
25 <dependency>
26 <groupId>org.springframework</groupId>
27 <artifactId>spring-beans</artifactId>
28 <version>3.1.0.RELEASE</version>
29 <scope>provided</scope>
30 </dependency>
31 <dependency>
32 <groupId>org.springframework</groupId>
33 <artifactId>org.springframework.context</artifactId>
34 <version>3.1.0.RELEASE</version>
35 <scope>provided</scope>
36 </dependency>
37 <dependency>
38 <groupId>org.springframework</groupId>
39 <artifactId>spring-test</artifactId>
40 <version>3.1.0.RELEASE</version>
41 <scope>test</scope>
42 </dependency>
43 <dependency>
44 <groupId>commons-io</groupId>
45 <artifactId>commons-io</artifactId>
46 <version>1.3.2</version>
47 </dependency>
48 <dependency>
49 <groupId>commons-lang</groupId>
50 <artifactId>commons-lang</artifactId>
51 <version>2.3</version>
52 <scope>provided</scope>
53 </dependency>
54 <dependency>
55 <groupId>junit</groupId>
56 <artifactId>junit</artifactId>
57 <version>4.10</version>
58 <scope>test</scope>
59 </dependency>
60 <dependency>
61 <groupId>org.aspectj</groupId>
62 <artifactId>aspectjweaver</artifactId>
63 <version>1.6.12</version>
64 <scope>provided</scope>
65 </dependency>
66 <dependency>
67 <groupId>net.sourceforge.cglib</groupId>
68 <artifactId>com.springsource.net.sf.cglib</artifactId>
69 <version>2.2.0</version>
70 <scope>provided</scope>
71 </dependency>
72 <dependency>
73 <groupId>log4j</groupId>
74 <artifactId>log4j</artifactId>
75 <version>1.2.8</version>
76 </dependency>
2.Jedis的连接池配置需要用到org.apache.commons.pool.impl.GenericObjectPool.Config.class,此类是 GenericObjectPool的一个内部类,使用spring xml配置时需要转换成以下自定义类。
view sourceprint?001 package com.antilost.redis.util;
002
003 import org.apache.commons.pool.impl.GenericObjectPool;
004
005 /**
006 * User: ***
007 * Date: 13-8-27
008 * Time: 下午3:49
009 */
010 public class GenericObjectPoolConfigWrapper {
011
012 private final GenericObjectPool.Config config;
013
014 public GenericObjectPoolConfigWrapper() {
015 this.config = new GenericObjectPool.Config();
016 }
017
018 public GenericObjectPool.Config getConfig() {
019 return config;
020 }
021
022 public int getMaxIdle() {
023 return this.config.maxIdle;
024 }
025
026 public void setMaxIdle(int maxIdle) {
027 this.config.maxIdle = maxIdle;
028 }
029
030 public int getMinIdle() {
031 return this.config.minIdle;
032 }
033
034 public void setMinIdle(int minIdle) {
035 this.config.minIdle = minIdle;
036 }
037
038 public int getMaxActive() {
039 return this.config.maxActive;
040 }
041
042 public void setMaxActive(int maxActive) {
043 this.config.maxActive = maxActive;
044 }
045
046 public long getMaxWait() {
047 return this.config.maxWait;
048 }
049
050 public void setMaxWait(long maxWait) {
051 this.config.maxWait = maxWait;
052 }
053
054 public byte getWhenExhaustedAction() {
055 return this.config.whenExhaustedAction;
056 }
057
058 public void setWhenExhaustedAction(byte whenExhaustedAction) {
059 this.config.whenExhaustedAction = whenExhaustedAction;
060 }
061
062 public boolean isTestOnBorrow() {
063 return this.config.testOnBorrow;
064 }
065
066 public void setTestOnBorrow(boolean testOnBorrow) {
067 this.config.testOnBorrow = testOnBorrow;
068 }
069
070 public boolean isTestOnReturn() {
071 return this.config.testOnReturn;
072 }
073
074 public void setTestOnReturn(boolean testOnReturn) {
075 this.config.testOnReturn = testOnReturn;
076 }
077
078 public boolean isTestWhileIdle() {
079 return this.config.testWhileIdle;
080 }
081
082 public void setTestWhileIdle(boolean testWhileIdle) {
083 this.config.testWhileIdle = testWhileIdle;
084 }
085
086 public long getTimeBetweenEvictionRunsMillis() {
087 return this.config.timeBetweenEvictionRunsMillis;
088 }
089
090 public void setTimeBetweenEvictionRunsMillis( long timeBetweenEvictionRunsMillis) {
091 this.config.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
092 }
093
094 public int getNumTestsPerEvictionRun() {
095 return this.config.numTestsPerEvictionRun;
096 }
097
098 public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
099 this.config.numTestsPerEvictionRun = numTestsPerEvictionRun;
100 }
101
102 public long getMinEvictableIdleTimeMillis() {
103 return this.config.minEvictableIdleTimeMillis;
104 }
105
106 public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
107 this.config.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
108 }
109
110 public long getSoftMinEvictableIdleTimeMillis() {
111 return this.config.softMinEvictableIdleTimeMillis;
112 }
113
114 public void setSoftMinEvictableIdleTimeMillis( long softMinEvictableIdleTimeMillis) {
115 this.config.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
116 }
117
118 public boolean isLifo() {
119 return this.config.lifo;
120 }
121
122 public void setLifo(boolean lifo) {
123 this.config.lifo = lifo;
124 }
125 }
3.在Spring配置文件中注入GenericObjectPoolConfigWrapper.java类
view sourceprint?01 <aop:aspectj-autoproxy/>
02 <context:annotation-config />
03 <context:property-placeholder location="classpath:jedis.properties" ignore-unresolvable="true"/>
04 <bean id="jedisPoolConfig" class="com.antilost.redis.util.GenericObjectPoolConfigWrapper">
05 <!--最大连接数-->
06 <property name="maxActive" value="${${redis.pool.maxActive}}" />
07 <!--最大空闲连接数-->
08 <property name="maxIdle" value="${${redis.pool.maxIdle}}" />
09 <!--初始化连接数-->
10 <property name="minIdle" value="${${redis.pool.minIdle}}"/>
11 <!--最大等待时间-->
12 <property name="maxWait" value="${${redis.pool.maxWait}}" />
13 <!--对拿到的connection进行validateObject校验-->
14 <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
15 <!--在进行returnObject对返回的connection进行validateObject校验-->
16 <property name="testOnReturn" value="${redis.pool.testOnReturn}" />
17 <!--定时对线程池中空闲的链接进行validateObject校验-->
18 <property name="testWhileIdle" value="true" />
19 </bean>
4.Redis的连接配置文件jedis.properties中,定义了各个环境的连接参数,具体配置如下
view sourceprint?01 redis.pool.maxActive=redis.pool.maxActive.${ServerType}
02 redis.pool.maxIdle=redis.pool.maxIdle.${ServerType}
03 redis.pool.maxWait=redis.pool.maxWait.${ServerType}
04 redis.pool.minIdle=redis.pool.minIdle.${ServerType}
05 redis.host=redis.host.${ServerType}
06 redis.port=redis.port.${ServerType}
07 redis.password=redis.password.${ServerType}
08 redis.pool.testOnBorrow=true
09 redis.pool.testOnReturn=true
10 redis.timeout=1000
11 #C
12 #REL
13 redis.pool.maxActive.REL=200
14 redis.pool.maxIdle.REL=50
15 redis.pool.minIdle.REL=10
16 redis.pool.maxWait.REL=300
17 redis.host.REL=192.168.*.*
18 redis.port.REL=6379
19 redis.password.REL=***
20
21 #VRF
22 redis.pool.maxActive.VRF=200
23 redis.pool.maxIdle.VRF=50
24 redis.pool.minIdle.VRF=10
25 redis.pool.maxWait.VRF=300
26 redis.host.VRF=192.168.*.*
27 redis.port.VRF=6379
28 redis.password.VRF=***
根据系统环境变量JVM中ServerType的值,取不同的配置,实现多环境(测试环境、生产环境)集成。
5.Redis连接池配置
view sourceprint?01 <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
02 <constructor-arg index="0">
03 <bean factory-bean="jedisPoolConfig" factory-method="getConfig"/>
04 </constructor-arg>
05 <constructor-arg index="1" value="${${redis.host}}"/>
06 <constructor-arg index="2" value="${${redis.port}}"/>
07 <!--timeout-->
08 <constructor-arg index="3" value="${redis.timeout}"/>
09 <constructor-arg index="4" value="${${redis.password}}"/>
10 </bean>
6.Redis 工具类 view sourceprint?001 public abstract class JCacheTools {
002 public abstract int getDBIndex();
003 /**
004 * 默认日志打印logger_default
005 */
006 public static Logger logger_default = Logger.getLogger("logger_jCache_default");
007 /**
008 * 失败日志logger,用于定期del指定的key
009 */
010 public static Logger logger_failure = Logger.getLogger("logger_jCache_failure");
011
012 @Resource
013 protected JedisPool jedisPool;
014
015 protected Jedis getJedis() throws JedisException {
016 Jedis jedis = null;
017 try {
018 jedis = jedisPool.getResource();
019 } catch (JedisException e) {
020 LogContext.instance().warn(logger_failure, "failed:jedisPool getResource.", e);
021 if(jedis!=null){
022 jedisPool.returnBrokenResource(jedis);
023 }
024 throw e;
025 }
026 return jedis;
027 }
028
029 protected void release(Jedis jedis, boolean isBroken) {
030 if (jedis != null) {
031 if (isBroken) {
032 jedisPool.returnBrokenResource(jedis);
033 } else {
034 jedisPool.returnResource(jedis);
035 }
036 }
037 }
038
039 protected String addStringToJedis(String key, String value, int cacheSeconds, String methodName) {
040 Jedis jedis = null;
041 boolean isBroken = false;
042 String lastVal = null;
043 try {
044 jedis = this.getJedis();
045 jedis.select(getDBIndex());
046 lastVal = jedis.getSet(key, value);
047 if(cacheSeconds!=0){
048 jedis.expire(key,cacheSeconds);
049 }
050 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
051 } catch (Exception e) {
052 isBroken = true;
053 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
054 } finally {
055 release(jedis, isBroken);
056 }
057 return lastVal;
058 }
059
060 protected void addStringToJedis(Map<String,String> batchData, int cacheSeconds, String methodName) {
061 Jedis jedis = null;
062 boolean isBroken = false;
063 try {
064 jedis = this.getJedis();
065 jedis.select(getDBIndex());
066 Pipeline pipeline = jedis.pipelined();
067 for(Map.Entry<String,String> element:batchData.entrySet()){
068 if(cacheSeconds!=0){
069 pipeline.setex(element.getKey(),cacheSeconds,element.getValue());
070 }else{
071 pipeline.set(element.getKey(),element.getValue());
072 }
073 }
074 pipeline.sync();
075 LogContext.instance().debug(logger_default, "succeed:" + methodName,batchData.size());
076 } catch (Exception e) {
077 isBroken = true;
078 e.printStackTrace();
079 } finally {
080 release(jedis, isBroken);
081 }
082 }
083
084 protected void addListToJedis(String key, List<String> list, int cacheSeconds, String methodName) {
085 if (list != null && list.size() > 0) {
086 Jedis jedis = null;
087 boolean isBroken = false;
088 try {
089 jedis = this.getJedis();
090 jedis.select(getDBIndex());
091 if (jedis.exists(key)) {
092 jedis.del(key);
093 }
094 for (String aList : list) {
095 jedis.rpush(key, aList);
096 }
097 if(cacheSeconds!=0){
098 jedis.expire(key, cacheSeconds);
099 }
100 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list.size());
101 } catch (JedisException e) {
102 isBroken = true;
103 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list.size(), e);
104 } catch (Exception e) {
105 isBroken = true;
106 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list.size(), e);
107 } finally {
108 release(jedis, isBroken);
109 }
110 }
111 }
112
113 protected void addToSetJedis(String key, String[] value, String methodName) {
114 Jedis jedis = null;
115 boolean isBroken = false;
116 try {
117 jedis = this.getJedis();
118 jedis.select(getDBIndex());
119 jedis.sadd(key,value);
120 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
121 } catch (Exception e) {
122 isBroken = true;
123 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
124 } finally {
125 release(jedis, isBroken);
126 }
127 }
128
129 protected void removeSetJedis(String key,String value, String methodName) {
130 Jedis jedis = null;
131 boolean isBroken = false;
132 try {
133 jedis = this.getJedis();
134 jedis.select(getDBIndex());
135 jedis.srem(key,value);
136 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
137 } catch (Exception e) {
138 isBroken = true;
139 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
140 } finally {
141 release(jedis, isBroken);
142 }
143 }
144
145 protected void pushDataToListJedis(String key, String data, int cacheSeconds, String methodName) {
146 Jedis jedis = null;
147 boolean isBroken = false;
148 try {
149 jedis = this.getJedis();
150 jedis.select(getDBIndex());
151 jedis.rpush(key, data);
152 if(cacheSeconds!=0){
153 jedis.expire(key,cacheSeconds);
154 }
155 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, data);
156 } catch (Exception e) {
157 isBroken = true;
158 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, data, e);
159 } finally {
160 release(jedis, isBroken);
161 }
162 }
163 protected void pushDataToListJedis(String key,List<String> batchData, int cacheSeconds, String methodName) {
164 Jedis jedis = null;
165 boolean isBroken = false;
166 try {
167 jedis = this.getJedis();
168 jedis.select(getDBIndex());
169 jedis.del(key);
170 jedis.lpush(key,batchData.toArray(new String[batchData.size()]));
171 if(cacheSeconds!=0)
172 jedis.expire(key,cacheSeconds);
173 LogContext.instance().debug(logger_default, "succeed:" + methodName,batchData!=null?batchData.size():0);
174 } catch (Exception e) {
175 isBroken = true;
176 LogContext.instance().warn(logger_failure, "failed:" + methodName, batchData!=null?batchData.size():0, e);
177 } finally {
178 release(jedis, isBroken);
179 }
180 }
181
182 /**
183 * 删除list中的元素
184 * @param key
185 * @param values
186 * @param methodName
187 */
188 protected void deleteDataFromListJedis(String key,List<String> values, String methodName) {
189 Jedis jedis = null;
190 boolean isBroken = false;
191 try {
192 jedis = this.getJedis();
193 jedis.select(getDBIndex());
194 Pipeline pipeline = jedis.pipelined();
195 if(values!=null && !values.isEmpty()){
196 for (String val:values){
197 pipeline.lrem(key,0,val);
198 }
199 }
200 pipeline.sync();
201 LogContext.instance().debug(logger_default, "succeed:" + methodName,values!=null?values.size():0);
202 } catch (Exception e) {
203 isBroken = true;
204 LogContext.instance().warn(logger_failure, "failed:" + methodName, values!=null?values.size():0, e);
205 } finally {
206 release(jedis, isBroken);
207 }
208 }
209
210 protected void addHashMapToJedis(String key, Map<String, String> map, int cacheSeconds, boolean isModified, String methodName) {
211 boolean isBroken = false;
212 Jedis jedis = null;
213 if (map != null && map.size() > 0) {
214 try {
215 jedis = this.getJedis();
216 jedis.select(getDBIndex());
217 jedis.hmset(key, map);
218 if (cacheSeconds >= 0)
219 jedis.expire(key, cacheSeconds);
220 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, map.size());
221 } catch (Exception e) {
222 isBroken = true;
223 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, map.size(), e);
224 } finally {
225 release(jedis, isBroken);
226 }
227 }
228 }
229
230 protected void addHashMapToJedis(String key, String field, String value, int cacheSeconds, String methodName) {
231 boolean isBroken = false;
232 Jedis jedis = null;
233 try {
234 jedis = this.getJedis();
235 if (jedis != null) {
236 jedis.select(getDBIndex());
237 jedis.hset(key, field, value);
238 jedis.expire(key, cacheSeconds);
239 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, field, value);
240 }
241 } catch (Exception e) {
242 isBroken = true;
243 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, field, value, e);
244 }finally {
245 release(jedis, isBroken);
246 }
247 }
248
249 protected void updateHashMapToJedis(String key, String incrementField, long incrementValue, String dateField, String dateValue, String methodName) {
250 boolean isBroken = false;
251 Jedis jedis = null;
252 try {
253 jedis = this.getJedis();
254 jedis.select(getDBIndex());
255 jedis.hincrBy(key, incrementField, incrementValue);
256 jedis.hset(key, dateField, dateValue);
257 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, incrementField, incrementValue);
258 } catch (Exception e) {
259 isBroken = true;
260 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, incrementField, incrementValue, e);
261 }finally {
262 release(jedis, isBroken);
263 }
264 }
265
266 public String getStringFromJedis(String key, String methodName) {
267 String value = null;
268 Jedis jedis = null;
269 boolean isBroken = false;
270 try {
271 jedis = this.getJedis();
272 jedis.select(getDBIndex());
273 if (jedis.exists(key)) {
274 value = jedis.get(key);
275 value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value)?value:null;
276 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
277 }
278 } catch (Exception e) {
279 isBroken = true;
280 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
281 } finally {
282 release(jedis, isBroken);
283 }
284 return value;
285 }
286
287 public List<String> getStringFromJedis(String[] keys, String methodName) {
288 Jedis jedis = null;
289 boolean isBroken = false;
290 try {
291 jedis = this.getJedis();
292 jedis.select(getDBIndex());
293 return jedis.mget(keys);
294 } catch (Exception e) {
295 isBroken = true;
296 LogContext.instance().warn(logger_failure, "failed:" + methodName, Arrays.toString(keys), e);
297 } finally {
298 release(jedis, isBroken);
299 }
300 return null;
301 }
302
303 protected List<String> getListFromJedis(String key, String methodName) throws JMSCacheException {
304 List<String> list = null;
305 boolean isBroken = false;
306 Jedis jedis = null;
307 try {
308 jedis = this.getJedis();
309 jedis.select(getDBIndex());
310 if (jedis.exists(key)) {
311 list = jedis.lrange(key, 0, -1);
312 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list != null ? list.size() : 0);
313 }
314 } catch (JedisException e) {
315 isBroken = true;
316 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list != null ? list.size() : 0, e);
317 } finally {
318 release(jedis, isBroken);
319 }
320 return list;
321 }
322
323 protected Set<String> getSetFromJedis(String key, String methodName) throws JMSCacheException {
324 Set<String> list = null;
325 boolean isBroken = false;
326 Jedis jedis = null;
327 try {
328 jedis = this.getJedis();
329 jedis.select(getDBIndex());
330 if (jedis.exists(key)) {
331 list = jedis.smembers(key);
332 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list != null ? list.size() : 0);
333 }
334 } catch (Exception e) {
335 isBroken = true;
336 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list != null ? list.size() : 0, e);
337 } finally {
338 release(jedis, isBroken);
339 }
340 return list;
341 }
342
343 protected Map<String, String> getHashMapFromJedis(String key, String methodName) {
344 Map<String, String> hashMap = null;
345 boolean isBroken = false;
346 Jedis jedis = null;
347 try {
348 jedis = this.getJedis();
349 jedis.select(getDBIndex());
350 hashMap = jedis.hgetAll(key);
351 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, hashMap != null ? hashMap.size() : 0);
352 } catch (Exception e) {
353 isBroken = true;
354 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, hashMap != null ? hashMap.size() : 0, e);
355 } finally {
356 release(jedis, isBroken);
357 }
358 return hashMap;
359 }
360
361 protected String getHashMapValueFromJedis(String key, String field, String methodName) {
362 String value = null;
363 boolean isBroken = false;
364 Jedis jedis = null;
365 try {
366 jedis = this.getJedis();
367 if (jedis != null) {
368 jedis.select(getDBIndex());
369 if (jedis.exists(key)) {
370 value = jedis.hget(key, field);
371 LogContext.instance().debug(logger_default, "succeed:" + methodName, key, field, value);
372 }
373 }
374 } catch (Exception e) {
375 isBroken = true;
376 LogContext.instance().warn(logger_failure, "failed:" + methodName, key, field, value, e);
377 } finally {
378 release(jedis, isBroken);
379 }
380 return value;
381 }
382
383 public Long getIdentifyId(String identifyName ,String methodName) {
384 boolean isBroken = false;
385 Jedis jedis = null;
386 Long identify=null;
387 try {
388 jedis = this.getJedis();
389 if (jedis != null) {
390 jedis.select(getDBIndex());
391 identify = jedis.incr(identifyName);
392 if(identify==0){
393 return jedis.incr(identifyName);
394 }else {
395 return identify;
396 }
397 }
398 } catch (Exception e) {
399 isBroken = true;
400 LogContext.instance().warn(logger_failure, "failed:" + methodName, identifyName, "", identify, e);
401 } finally {
402 release(jedis, isBroken);
403 }
404 return null;
405 }
406
407
408 /**
409 * 删除某db的某个key值
410 * @param key
411 * @return
412 */
413 public Long delKeyFromJedis(String key) {
414 boolean isBroken = false;
415 Jedis jedis = null;
416 long result = 0;
417 try {
418 jedis = this.getJedis();
419 jedis.select(getDBIndex());
420 LogContext.instance().debug(logger_default, "succeed:delKeyFromJedis");
421 return jedis.del(key);
422 } catch (Exception e) {
423 isBroken = true;
424 LogContext.instance().warn(logger_failure, "failed:delKeyFromJedis", e);
425 } finally {
426 release(jedis, isBroken);
427 }
428 return result;
429 }
430
431 /**
432 * 根据dbIndex flushDB每个shard
433 *
434 * @param dbIndex
435 */
436 public void flushDBFromJedis(int dbIndex) {
437 Jedis jedis = null;
438 boolean isBroken = false;
439 try {
440 jedis = this.getJedis();
441 jedis.select(dbIndex);
442 jedis.flushDB();
443 LogContext.instance().debug(logger_default, "succeed:flushDBFromJedis");
444 } catch (Exception e) {
445 isBroken = true;
446 LogContext.instance().warn(logger_failure, "failed:flushDBFromJedis", e);
447 } finally {
448 release(jedis, isBroken);
449 }
450 }
451
452 public boolean existKey(String key, String methodName) {
453 Jedis jedis = null;
454 boolean isBroken = false;
455 try {
456 jedis = this.getJedis();
457 jedis.select(getDBIndex());
458 LogContext.instance().debug(logger_default, "succeed:"+methodName);
459 return jedis.exists(key);
460 } catch (Exception e) {
461 isBroken = true;
462 LogContext.instance().warn(logger_failure, "failed:"+methodName, e);
463 } finally {
464 release(jedis, isBroken);
465 }
466 return false;
467 }
468
469 } [/size]