JedisTemplate.java
15.1 KB
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package com.cjs.cms.util.redis;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.Pool;
/**
* JedisTemplate 提供了一个template方法,负责对Jedis连接的获取与归还。
* JedisAction<T> 和 JedisActionNoResult两种回调接口,适用于有无返回值两种情况。
* 同时提供一些最常用函数的封装, 如get/set/zadd等。
*/
@Component
public class JedisTemplate {
private static Logger logger = LoggerFactory.getLogger(JedisTemplate.class);
private Pool<Jedis> jedisPool;
public JedisTemplate() {
this.jedisPool = JedisUtils.getPool();
}
public JedisTemplate(Pool<Jedis> jedisPool) {
this.jedisPool = jedisPool;
}
/**
* 执行有返回结果的action。
*/
public <T> T execute(JedisAction<T> jedisAction) throws JedisException {
Jedis jedis = null;
boolean broken = false;
try {
jedis = jedisPool.getResource();
jedis.setDataSource(jedisPool);
return jedisAction.action(jedis);
} catch (JedisConnectionException e) {
logger.error("Redis connection lost.", e);
broken = true;
throw e;
} finally {
closeResource(jedis, broken);
}
}
/**
* 执行无返回结果的action。
*/
public void execute(JedisActionNoResult jedisAction) throws JedisException {
Jedis jedis = null;
boolean broken = false;
try {
jedis = jedisPool.getResource();
jedis.setDataSource(jedisPool);
jedisAction.action(jedis);
} catch (JedisConnectionException e) {
logger.error("Redis connection lost.", e);
broken = true;
throw e;
} finally {
closeResource(jedis, broken);
}
}
/**
* 根据连接是否已中断的标志,分别调用returnBrokenResource或returnResource。
*/
protected void closeResource(Jedis jedis, boolean connectionBroken) {
if (jedis != null) {
try {
jedis.setDataSource(jedisPool);
jedis.close();
} catch (Exception e) {
logger.error("Error happen when return jedis to pool, try to close it directly.",
e);
JedisUtils.closeJedis(jedis);
}
}
}
/**
* 获取内部的pool做进一步的动作。
*/
public Pool<Jedis> getJedisPool() {
return jedisPool;
}
/**
* 有返回结果的回调接口定义。
*/
public interface JedisAction<T> {
T action(Jedis jedis);
}
/**
* 无返回结果的回调接口定义。
*/
public interface JedisActionNoResult {
void action(Jedis jedis);
}
// ////////////// 常用方法的封装 ///////////////////////// //
// ////////////// 公共 ///////////////////////////
/**选择库*/
public String select(final int index) {
return execute(new JedisAction<String>() {
@Override
public String action(Jedis jedis) {
return jedis.select(index);
}
});
}
/**
* 删除key, 如果key存在返回true, 否则返回false。
*/
public Boolean del(final String... keys) {
return execute(new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
return jedis.del(keys) == 1 ? true : false;
}
});
}
public void flushDB() {
execute(new JedisActionNoResult() {
@Override
public void action(Jedis jedis) {
jedis.flushDB();
}
});
}
// ////////////// 关于String ///////////////////////////
/**
* 如果key不存在, 返回null.
*/
public String get(final String key) {
return execute(new JedisAction<String>() {
@Override
public String action(Jedis jedis) {
return jedis.get(key);
}
});
}
/**
* 如果key不存在, 返回null.
*/
public byte[] get(final byte[] key) {
return execute(new JedisAction<byte[]>() {
@Override
public byte[] action(Jedis jedis) {
return jedis.get(key);
}
});
}
/**
* 如果key不存在, 返回null.
*/
public Long getAsLong(final String key) {
String result = get(key);
return result != null ? Long.valueOf(result) : null;
}
/**
* 如果key不存在, 返回null.
*/
public Integer getAsInt(final String key) {
String result = get(key);
return result != null ? Integer.valueOf(result) : null;
}
public void set(final String key, final String value) {
execute(new JedisActionNoResult() {
@Override
public void action(Jedis jedis) {
jedis.set(key, value);
}
});
}
public void set(final String key, final String value, final int seconds) {
execute(new JedisActionNoResult() {
@Override
public void action(Jedis jedis) {
jedis.setex(key, seconds, value);
}
});
}
/**byte类型主要用于存储序列化后的数据*/
public void set(final byte[] key, final byte[] value) {
execute(new JedisActionNoResult() {
@Override
public void action(Jedis jedis) {
jedis.set(key, value);
}
});
}
/**byte类型主要用于存储序列化后的数据*/
public void set(final byte[] key, final byte[] value, final int seconds) {
execute(new JedisActionNoResult() {
@Override
public void action(Jedis jedis) {
jedis.setex(key, seconds, value);
}
});
}
public void setex(final String key, final String value, final int seconds) {
execute(new JedisActionNoResult() {
@Override
public void action(Jedis jedis) {
jedis.setex(key, seconds, value);
}
});
}
/**
* 如果key还不存在则进行设置,返回true,否则返回false.
*/
public Boolean setnx(final String key, final String value) {
return execute(new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
return jedis.setnx(key, value) == 1 ? true : false;
}
});
}
/**
* 综合setNX与setEx的效果。
*/
public Boolean setnxex(final String key, final String value, final int seconds) {
return execute(new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
String result = jedis.set(key, value, "NX", "EX", seconds);
return JedisUtils.isStatusOk(result);
}
});
}
public Long incr(final String key) {
return execute(new JedisAction<Long>() {
@Override
public Long action(Jedis jedis) {
return jedis.incr(key);
}
});
}
public Long decr(final String key) {
return execute(new JedisAction<Long>() {
@Override
public Long action(Jedis jedis) {
return jedis.decr(key);
}
});
}
// ////////////// 关于List ///////////////////////////
public void lpush(final String key, final String... values) {
execute(new JedisActionNoResult() {
@Override
public void action(Jedis jedis) {
jedis.lpush(key, values);
}
});
}
public String rpop(final String key) {
return execute(new JedisAction<String>() {
@Override
public String action(Jedis jedis) {
return jedis.rpop(key);
}
});
}
/**
* 返回List长度, key不存在时返回0,key类型不是list时抛出异常.
*/
public Long llen(final String key) {
return execute(new JedisAction<Long>() {
@Override
public Long action(Jedis jedis) {
return jedis.llen(key);
}
});
}
/**
* 删除List中的第一个等于value的元素,value不存在或key不存在时返回false.
*/
public Boolean lremOne(final String key, final String value) {
return execute(new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
Long count = jedis.lrem(key, 1, value);
return (count == 1);
}
});
}
/**
* 删除List中的所有等于value的元素,value不存在或key不存在时返回false.
*/
public Boolean lremAll(final String key, final String value) {
return execute(new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
Long count = jedis.lrem(key, 0, value);
return (count > 0);
}
});
}
// ////////////// 关于Sorted Set ///////////////////////////
/**
* 加入Sorted set, 如果member在Set里已存在, 只更新score并返回false, 否则返回true.
*/
public Boolean zadd(final String key, final String member, final double score) {
return execute(new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
return jedis.zadd(key, score, member) == 1 ? true : false;
}
});
}
/**
* 删除sorted set中的元素,成功删除返回true,key或member不存在返回false。
*/
public Boolean zrem(final String key, final String member) {
return execute(new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
return jedis.zrem(key, member) == 1 ? true : false;
}
});
}
/**
* 当key不存在时返回null.
*/
public Double zscore(final String key, final String member) {
return execute(new JedisAction<Double>() {
@Override
public Double action(Jedis jedis) {
return jedis.zscore(key, member);
}
});
}
/**
* 返回sorted set长度, key不存在时返回0.
*/
public Long zcard(final String key) {
return execute(new JedisAction<Long>() {
@Override
public Long action(Jedis jedis) {
return jedis.zcard(key);
}
});
}
/**保存Map*/
public String hmset(final String key, final Map<String, String> hash) {
return execute(new JedisAction<String>() {
@Override
public String action(Jedis jedis) {
return jedis.hmset(key, hash);
}
});
}
/**获取Map*/
public Map<String, String> hgetAll(final String key) {
return execute(new JedisAction<Map<String, String>>() {
@Override
public Map<String, String> action(Jedis jedis) {
return jedis.hgetAll(key);
}
});
}
/**
* 获取Map中指定Key的值
* @param key 存储Map的Key
* @param field Map中的Key
* @return
*/
public String hget(final String key, final String field) {
return execute(new JedisAction<String>() {
@Override
public String action(Jedis jedis) {
return jedis.hget(key, field);
}
});
}
/**
* 获取Map中多个指定Key的值
* @param key 存储Map的Key
* @param fields Map中的Key集合
* @return
*/
public List<String> hmget(final String key, final String... fields) {
return execute(new JedisAction<List<String>>() {
@Override
public List<String> action(Jedis jedis) {
return jedis.hmget(key, fields);
}
});
}
/**
* 指定Key过期
* @param key
* @param seconds 秒数
* @return
*/
public Long expire(final String key, final Integer seconds) {
return execute(new JedisAction<Long>() {
@Override
public Long action(Jedis jedis) {
return jedis.expire(key, seconds);
}
});
}
/**
* 指定Key过期
* @param key
* @param timeUnit 时间单元
* @param duration 时间段
* @return
*/
public Long expire(final String key, final Integer duration, final TimeUnit timeUnit) {
return execute(new JedisAction<Long>() {
@Override
public Long action(Jedis jedis) {
return jedis.expire(key, (int) timeUnit.toSeconds(duration));
}
});
}
/**
* 发布消息到通道
* @param channel 通道
* @param message 消息
* @return
*/
public Long publish(final String channel, final String message) {
return execute(new JedisAction<Long>() {
@Override
public Long action(Jedis jedis) {
return jedis.publish(channel, message);
}
});
}
/**
* 订阅消息(会开启一新个线程)
* @param jedisPubSub 订阅消息处理
* @param channels 通道
*/
public void subscribe(final JedisPubSub jedisPubSub, final String... channels) {
new Thread(new Runnable() {
@Override
public void run() {
execute(new JedisAction<Object>() {
@Override
public Object action(Jedis jedis) {
jedis.subscribe(jedisPubSub, channels);
return null;
}
});
}
}).start();
}
/**
* 模式匹配订阅消息(会开启一新个线程)
* @param jedisPubSub 订阅消息处理(onPMessage)
* @param channels 通道(如:news.*)
*/
public void psubscribe(final JedisPubSub jedisPubSub, final String... channels) {
new Thread(new Runnable() {
@Override
public void run() {
execute(new JedisAction<Object>() {
@Override
public Object action(Jedis jedis) {
jedis.psubscribe(jedisPubSub, channels);
return null;
}
});
}
}).start();
}
}