`

Jedis连接池配置

 
阅读更多

摘要: 项目使用spring3.1版本,需要分环境(RND/Relesas/...)在Spring中配置Jedis连接池。此配置未使用Redis的分片。 

1.使用MAVEN引入使用的包。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.1.0.RELEASE</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.1.0.RELEASE</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>3.1.0.RELEASE</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>3.1.0.RELEASE</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>org.springframework.context</artifactId>
    <version>3.1.0.RELEASE</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.1.0.RELEASE</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.3</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.12</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>net.sourceforge.cglib</groupId>
    <artifactId>com.springsource.net.sf.cglib</artifactId>
    <version>2.2.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.8</version>
</dependency>

2.Jedis的连接池配置需要用到org.apache.commons.pool.impl.GenericObjectPool.Config.class,此类是 GenericObjectPool的一个内部类,使用spring xml配置时需要转换成以下自定义类。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package com.antilost.redis.util;
 
import org.apache.commons.pool.impl.GenericObjectPool;
 
/**
 * User: ***
 * Date: 13-8-27
 * Time: 下午3:49
 */
public class GenericObjectPoolConfigWrapper {
 
    private final GenericObjectPool.Config config;
 
    public GenericObjectPoolConfigWrapper() {
        this.config = new GenericObjectPool.Config();
    }
 
    public GenericObjectPool.Config getConfig() {
        return config;
    }
 
    public int getMaxIdle() {
        return this.config.maxIdle;
    }
 
    public void setMaxIdle(int maxIdle) {
        this.config.maxIdle = maxIdle;
    }
 
    public int getMinIdle() {
        return this.config.minIdle;
    }
 
    public void setMinIdle(int minIdle) {
        this.config.minIdle = minIdle;
    }
 
    public int getMaxActive() {
        return this.config.maxActive;
    }
 
    public void setMaxActive(int maxActive) {
        this.config.maxActive = maxActive;
    }
 
    public long getMaxWait() {
        return this.config.maxWait;
    }
 
    public void setMaxWait(long maxWait) {
        this.config.maxWait = maxWait;
    }
 
    public byte getWhenExhaustedAction() {
        return this.config.whenExhaustedAction;
    }
 
    public void setWhenExhaustedAction(byte whenExhaustedAction) {
        this.config.whenExhaustedAction = whenExhaustedAction;
    }
 
    public boolean isTestOnBorrow() {
        return this.config.testOnBorrow;
    }
 
    public void setTestOnBorrow(boolean testOnBorrow) {
        this.config.testOnBorrow = testOnBorrow;
    }
 
    public boolean isTestOnReturn() {
        return this.config.testOnReturn;
    }
 
    public void setTestOnReturn(boolean testOnReturn) {
        this.config.testOnReturn = testOnReturn;
    }
 
    public boolean isTestWhileIdle() {
        return this.config.testWhileIdle;
    }
 
    public void setTestWhileIdle(boolean testWhileIdle) {
        this.config.testWhileIdle = testWhileIdle;
    }
 
    public long getTimeBetweenEvictionRunsMillis() {
        return this.config.timeBetweenEvictionRunsMillis;
    }
 
    public void setTimeBetweenEvictionRunsMillis( long timeBetweenEvictionRunsMillis) {
        this.config.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    }
 
    public int getNumTestsPerEvictionRun() {
        return this.config.numTestsPerEvictionRun;
    }
 
    public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
        this.config.numTestsPerEvictionRun = numTestsPerEvictionRun;
    }
 
    public long getMinEvictableIdleTimeMillis() {
        return this.config.minEvictableIdleTimeMillis;
    }
 
    public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
        this.config.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
    }
 
    public long getSoftMinEvictableIdleTimeMillis() {
        return this.config.softMinEvictableIdleTimeMillis;
    }
 
    public void setSoftMinEvictableIdleTimeMillis( long softMinEvictableIdleTimeMillis) {
        this.config.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
    }
 
    public boolean isLifo() {
        return this.config.lifo;
    }
 
    public void setLifo(boolean lifo) {
        this.config.lifo = lifo;
    }
}

3.在Spring配置文件中注入GenericObjectPoolConfigWrapper.java类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<aop:aspectj-autoproxy/>
<context:annotation-config />
<context:property-placeholder location="classpath:jedis.properties" ignore-unresolvable="true"/>
<bean id="jedisPoolConfig" class="com.antilost.redis.util.GenericObjectPoolConfigWrapper">
        <!--最大连接数-->
    <property name="maxActive" value="${${redis.pool.maxActive}}" />
        <!--最大空闲连接数-->
    <property name="maxIdle" value="${${redis.pool.maxIdle}}" />
        <!--初始化连接数-->
    <property name="minIdle" value="${${redis.pool.minIdle}}"/>
        <!--最大等待时间-->
    <property name="maxWait" value="${${redis.pool.maxWait}}" />
        <!--对拿到的connection进行validateObject校验-->
    <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
        <!--在进行returnObject对返回的connection进行validateObject校验-->
    <property name="testOnReturn" value="${redis.pool.testOnReturn}" />
        <!--定时对线程池中空闲的链接进行validateObject校验-->
        <property name="testWhileIdle" value="true" />
</bean>

4.Redis的连接配置文件jedis.properties中,定义了各个环境的连接参数,具体配置如下

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
redis.pool.maxActive=redis.pool.maxActive.${ServerType}
redis.pool.maxIdle=redis.pool.maxIdle.${ServerType}
redis.pool.maxWait=redis.pool.maxWait.${ServerType}
redis.pool.minIdle=redis.pool.minIdle.${ServerType}
redis.host=redis.host.${ServerType}
redis.port=redis.port.${ServerType}
redis.password=redis.password.${ServerType}
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.timeout=1000
#C
#REL
redis.pool.maxActive.REL=200
redis.pool.maxIdle.REL=50
redis.pool.minIdle.REL=10
redis.pool.maxWait.REL=300
redis.host.REL=192.168.*.*
redis.port.REL=6379
redis.password.REL=***
 
#VRF
redis.pool.maxActive.VRF=200
redis.pool.maxIdle.VRF=50
redis.pool.minIdle.VRF=10
redis.pool.maxWait.VRF=300
redis.host.VRF=192.168.*.*
redis.port.VRF=6379
redis.password.VRF=***
根据系统环境变量JVM中ServerType的值,取不同的配置,实现多环境(测试环境、生产环境)集成。

 

5.Redis连接池配置

1
2
3
4
5
6
7
8
9
10
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
     <constructor-arg index="0">
            <bean factory-bean="jedisPoolConfig" factory-method="getConfig"/>
     </constructor-arg>
        <constructor-arg index="1" value="${${redis.host}}"/>
        <constructor-arg index="2" value="${${redis.port}}"/>
        <!--timeout-->
        <constructor-arg index="3" value="${redis.timeout}"/>
        <constructor-arg index="4" value="${${redis.password}}"/>
</bean>
6.Redis 工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
public abstract class JCacheTools {
    public abstract int getDBIndex();
    /**
     * 默认日志打印logger_default
     */
    public static Logger logger_default = Logger.getLogger("logger_jCache_default");
    /**
     * 失败日志logger,用于定期del指定的key
     */
    public static Logger logger_failure = Logger.getLogger("logger_jCache_failure");
 
    @Resource
    protected JedisPool jedisPool;
 
    protected Jedis getJedis() throws JedisException {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
        catch (JedisException e) {
            LogContext.instance().warn(logger_failure, "failed:jedisPool getResource.", e);
            if(jedis!=null){
                jedisPool.returnBrokenResource(jedis);
            }
            throw e;
        }
        return jedis;
    }
 
    protected void release(Jedis jedis, boolean isBroken) {
        if (jedis != null) {
            if (isBroken) {
                jedisPool.returnBrokenResource(jedis);
            else {
                jedisPool.returnResource(jedis);
            }
        }
    }
 
    protected String addStringToJedis(String key, String value, int cacheSeconds, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        String lastVal = null;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            lastVal = jedis.getSet(key, value);
            if(cacheSeconds!=0){
                jedis.expire(key,cacheSeconds);
            }
            LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
        finally {
            release(jedis, isBroken);
        }
        return lastVal;
    }
 
    protected void addStringToJedis(Map<String,String> batchData, int cacheSeconds, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            Pipeline pipeline = jedis.pipelined();
            for(Map.Entry<String,String> element:batchData.entrySet()){
                if(cacheSeconds!=0){
                    pipeline.setex(element.getKey(),cacheSeconds,element.getValue());
                }else{
                    pipeline.set(element.getKey(),element.getValue());
                }
            }
            pipeline.sync();
            LogContext.instance().debug(logger_default, "succeed:" + methodName,batchData.size());
        catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        finally {
            release(jedis, isBroken);
        }
    }
 
    protected void addListToJedis(String key, List<String> list, int cacheSeconds, String methodName) {
        if (list != null && list.size() > 0) {
            Jedis jedis = null;
            boolean isBroken = false;
            try {
                jedis = this.getJedis();
                jedis.select(getDBIndex());
                if (jedis.exists(key)) {
                    jedis.del(key);
                }
                for (String aList : list) {
                    jedis.rpush(key, aList);
                }
                if(cacheSeconds!=0){
                    jedis.expire(key, cacheSeconds);
                }
                LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list.size());
            catch (JedisException e) {
                isBroken = true;
                LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list.size(), e);
            catch (Exception e) {
                isBroken = true;
                LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list.size(), e);
            finally {
                release(jedis, isBroken);
            }
        }
    }
 
    protected void addToSetJedis(String key, String[] value, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            jedis.sadd(key,value);
            LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
        finally {
            release(jedis, isBroken);
        }
    }
 
    protected void removeSetJedis(String key,String value, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            jedis.srem(key,value);
            LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
        finally {
            release(jedis, isBroken);
        }
    }
 
    protected void pushDataToListJedis(String key, String data, int cacheSeconds, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            jedis.rpush(key, data);
            if(cacheSeconds!=0){
                jedis.expire(key,cacheSeconds);
            }
            LogContext.instance().debug(logger_default, "succeed:" + methodName, key, data);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, data, e);
        finally {
            release(jedis, isBroken);
        }
    }
    protected void pushDataToListJedis(String key,List<String> batchData, int cacheSeconds, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            jedis.del(key);
            jedis.lpush(key,batchData.toArray(new String[batchData.size()]));
            if(cacheSeconds!=0)
                jedis.expire(key,cacheSeconds);
            LogContext.instance().debug(logger_default, "succeed:" + methodName,batchData!=null?batchData.size():0);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, batchData!=null?batchData.size():0, e);
        finally {
            release(jedis, isBroken);
        }
    }
 
    /**
     * 删除list中的元素
     * @param key
     * @param values
     * @param methodName
     */
    protected void deleteDataFromListJedis(String key,List<String> values, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            Pipeline pipeline = jedis.pipelined();
            if(values!=null && !values.isEmpty()){
                for (String val:values){
                    pipeline.lrem(key,0,val);
                }
            }
            pipeline.sync();
            LogContext.instance().debug(logger_default, "succeed:" + methodName,values!=null?values.size():0);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, values!=null?values.size():0, e);
        finally {
            release(jedis, isBroken);
        }
    }
 
    protected void addHashMapToJedis(String key, Map<String, String> map, int cacheSeconds, boolean isModified, String methodName) {
        boolean isBroken = false;
        Jedis jedis = null;
        if (map != null && map.size() > 0) {
            try {
                jedis = this.getJedis();
                jedis.select(getDBIndex());
                jedis.hmset(key, map);
                if (cacheSeconds >= 0)
                    jedis.expire(key, cacheSeconds);
                LogContext.instance().debug(logger_default, "succeed:" + methodName, key, map.size());
            catch (Exception e) {
                isBroken = true;
                LogContext.instance().warn(logger_failure, "failed:" + methodName, key, map.size(), e);
            finally {
                release(jedis, isBroken);
            }
        }
    }
 
    protected void addHashMapToJedis(String key, String field, String value, int cacheSeconds, String methodName) {
        boolean isBroken = false;
        Jedis jedis = null;
        try {
            jedis = this.getJedis();
            if (jedis != null) {
                jedis.select(getDBIndex());
                jedis.hset(key, field, value);
                jedis.expire(key, cacheSeconds);
                LogContext.instance().debug(logger_default, "succeed:" + methodName, key, field, value);
            }
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, field, value, e);
        }finally {
            release(jedis, isBroken);
        }
    }
 
    protected void updateHashMapToJedis(String key, String incrementField, long incrementValue, String dateField, String dateValue, String methodName) {
        boolean isBroken = false;
        Jedis jedis = null;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            jedis.hincrBy(key, incrementField, incrementValue);
            jedis.hset(key, dateField, dateValue);
            LogContext.instance().debug(logger_default, "succeed:" + methodName, key, incrementField, incrementValue);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, incrementField, incrementValue, e);
        }finally {
            release(jedis, isBroken);
        }
    }
 
    public String getStringFromJedis(String key, String methodName) {
        String value = null;
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            if (jedis.exists(key)) {
                value = jedis.get(key);
                value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value)?value:null;
                LogContext.instance().debug(logger_default, "succeed:" + methodName, key, value);
            }
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, value, e);
        finally {
            release(jedis, isBroken);
        }
        return value;
    }
 
    public List<String> getStringFromJedis(String[] keys, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            return jedis.mget(keys);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, Arrays.toString(keys), e);
        finally {
            release(jedis, isBroken);
        }
        return null;
    }
 
    protected List<String> getListFromJedis(String key, String methodName) throws JMSCacheException {
        List<String> list = null;
        boolean isBroken = false;
        Jedis jedis = null;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            if (jedis.exists(key)) {
                list = jedis.lrange(key, 0, -1);
                LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list != null ? list.size() : 0);
            }
        catch (JedisException e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list != null ? list.size() : 0, e);
        finally {
            release(jedis, isBroken);
        }
        return list;
    }
 
    protected Set<String> getSetFromJedis(String key, String methodName) throws JMSCacheException {
        Set<String> list = null;
        boolean isBroken = false;
        Jedis jedis = null;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            if (jedis.exists(key)) {
                list = jedis.smembers(key);
                LogContext.instance().debug(logger_default, "succeed:" + methodName, key, list != null ? list.size() : 0);
            }
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, list != null ? list.size() : 0, e);
        finally {
            release(jedis, isBroken);
        }
        return list;
    }
 
    protected Map<String, String> getHashMapFromJedis(String key, String methodName) {
        Map<String, String> hashMap = null;
        boolean isBroken = false;
        Jedis jedis = null;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            hashMap = jedis.hgetAll(key);
            LogContext.instance().debug(logger_default, "succeed:" + methodName, key, hashMap != null ? hashMap.size() : 0);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, hashMap != null ? hashMap.size() : 0, e);
        finally {
            release(jedis, isBroken);
        }
        return hashMap;
    }
 
    protected String getHashMapValueFromJedis(String key, String field, String methodName) {
        String value = null;
        boolean isBroken = false;
        Jedis jedis = null;
        try {
            jedis = this.getJedis();
            if (jedis != null) {
                jedis.select(getDBIndex());
                if (jedis.exists(key)) {
                    value = jedis.hget(key, field);
                    LogContext.instance().debug(logger_default, "succeed:" + methodName, key, field, value);
                }
            }
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, key, field, value, e);
        finally {
            release(jedis, isBroken);
        }
        return value;
    }
 
    public Long getIdentifyId(String identifyName ,String methodName) {
        boolean isBroken = false;
        Jedis jedis = null;
        Long identify=null;
        try {
            jedis = this.getJedis();
            if (jedis != null) {
                jedis.select(getDBIndex());
                identify = jedis.incr(identifyName);
                if(identify==0){
                    return jedis.incr(identifyName);
                }else {
                    return identify;
                }
            }
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:" + methodName, identifyName, "", identify, e);
        finally {
            release(jedis, isBroken);
        }
        return null;
    }
 
 
    /**
     * 删除某db的某个key值
     * @param key
     * @return
     */
    public Long delKeyFromJedis(String key) {
        boolean isBroken = false;
        Jedis jedis = null;
        long result = 0;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            LogContext.instance().debug(logger_default, "succeed:delKeyFromJedis");
            return jedis.del(key);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:delKeyFromJedis", e);
        finally {
            release(jedis, isBroken);
        }
        return result;
    }
 
    /**
     * 根据dbIndex flushDB每个shard
     *
     * @param dbIndex
     */
    public void flushDBFromJedis(int dbIndex) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(dbIndex);
            jedis.flushDB();
            LogContext.instance().debug(logger_default, "succeed:flushDBFromJedis");
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:flushDBFromJedis", e);
        finally {
            release(jedis, isBroken);
        }
    }
 
    public boolean existKey(String key, String methodName) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            jedis.select(getDBIndex());
            LogContext.instance().debug(logger_default, "succeed:"+methodName);
            return jedis.exists(key);
        catch (Exception e) {
            isBroken = true;
            LogContext.instance().warn(logger_failure, "failed:"+methodName, e);
        finally {
            release(jedis, isBroken);
        }
        return false;
    }
 
}
分享到:
评论

相关推荐

    jedis连接池配置demo

    这样就完成了基于ShardedJedisPool的Jedis连接池配置。 总结一下,ShardedJedisPool通过分片技术提高了Redis操作的效率,而连接池则有效地管理了与Redis服务器的连接,避免了频繁创建和销毁连接的开销。正确配置和...

    java连接redis/jedis连接池/jedis相关工具/jedis对象存取

    以下是一个简单的Jedis连接池配置示例: ```java import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisPoolExample { private static final String REDIS_...

    jedis-2.9.0.jar及连接池分享

    4. Jedis连接池配置: 使用Jedis时,可以通过连接池来管理连接,例如使用`GenericObjectPoolConfig`配置连接池参数,如最大活动连接数、最大空闲连接数、最大等待时间等。然后创建`JedisPool`实例,指定Redis服务器...

    详谈Jedis连接池的使用

    Jedis连接池的使用 Jedis连接池是Redis客户端Jedis的连接池实现,用于管理Redis连接的创建、释放和复用。通过使用Jedis连接池,可以提高Redis的访问性能和可靠性。在本文中,我们将详细讨论Jedis连接池的使用,包括...

    redis工具类以及redis 连接池配置

    创建jedis池配置实例,redis各种crud方法,包括使用主从同步,读写分离。工具类中包括存放hash表键值对,键值对以map的方式储存,删除键值对,永久存放键值对,设置过期时间,需要的直接去gitHab上看...

    官网jedis-2.9.0+commons-pool2-2.5.0 jar包

    以下是一个简单的Jedis连接池配置示例: ```java import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisPoolExample { private static JedisPool pool; ...

    redis连接池jar jedis+common

    三、Jedis连接池 1. **连接池概念**:连接池是一种对象池设计模式,主要用于管理数据库连接。它预先创建一定数量的连接,当需要时可以从池中获取,使用完毕后归还到池中,而不是直接关闭连接。 2. **JedisPool**:...

    redis+spring jedis方式

    **Jedis连接池配置示例**: ```java Properties props = new Properties(); props.setProperty("maxTotal", "100"); props.setProperty("maxIdle", "50"); props.setProperty("minIdle", "20"); JedisPoolConfig ...

    java,redis,jedis操作工具类,自己写的简易 demo

    1. **Jedis连接池配置** 在实际项目中,为了提高性能和资源利用率,我们会使用连接池来管理Jedis实例。常见的Jedis连接池实现是`org.apache.commons.pool2.impl.GenericObjectPool`。配置包括: - `maxTotal`: ...

    tomcat-redis-session-manager-master文档

    4. **Jedis连接池配置** 可以通过以下参数对Jedis连接池进行更细粒度的控制: - `connectionPoolMaxTotal`: Jedis连接池中最大连接数。 - `connectionPoolMaxIdle`: Jedis连接池中最大空闲连接数。 - `...

    spring-redis.txt

    -- Jedis连接池的相关配置 --&gt; &lt;bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"&gt; &lt;value&gt;200 &lt;value&gt;50 &lt;bean id="jedisPool" class="redis.clients.jedis.JedisPool"&gt;...

    Spring mvc整合redis实例(redis连接池)

    接下来,配置Redis连接池。在Spring的配置文件(如:applicationContext.xml)中,我们需要定义一个`JedisPoolConfig`和`JedisConnectionFactory`。`JedisPoolConfig`用来设置连接池的参数,如最大连接数、最大空闲...

    jedis配置含义详解

    接下来,Jedis连接池配置是提高性能和资源利用率的关键。连接池是一种复用已创建对象的技术,通过预先生成并管理一批Jedis连接,避免了每次操作时创建新的连接。Jedis连接池的配置主要涉及`JedisPoolConfig`类,它是...

    Redis单机、主从、哨兵Jave-Jedis连接代码

    要使用Jedis连接哨兵系统,首先在`redis-sentinel.conf`配置文件中定义哨兵节点,然后在Java代码中设置哨兵群组: ```java import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis....

    jedis-2.9.0.jar和commons-pool2-2.6.0.jar下载(jedis连接redis数据库)

    3. **连接池配置**: 使用Apache Commons Pool配置JedisPool,这将管理连接的创建、复用和回收。 ```java JedisPoolConfig poolConfig = new JedisPoolConfig(); // 设置最大连接数、最大空闲连接等参数 Jedis...

    tomcat9+apr+redissession共享

    这通常涉及到添加一个`&lt;Manager&gt;`元素,指定`className`为`org.apache.catalina.session.PersistentManager`,然后配置相关的属性,如`storeDirectory`(指向Redis的Jedis连接池配置文件)和`redisHost`、`redisPort...

    jedis pool配置

    在这个示例中,我们创建了一个JedisPool实例,设置了连接池配置,并在try-with-resources语句中获取和使用Jedis实例。完成操作后,确保连接池被正确关闭,释放所有资源。 对于数据缓存操作,Jedis提供了多种方法,...

    redis的Java客户端jedis池的介绍及使用.rar

    本文将详细介绍Jedis连接池的概念、配置以及使用方法。 一、Jedis连接池概念 Jedis连接池,即`JedisPool`,是基于Apache Commons Pool2实现的。它允许我们预先创建一定数量的Jedis实例,并将它们存储在一个池中。...

Global site tag (gtag.js) - Google Analytics