Repository navigation
Expand file tree
/
Copy pathRedis-业务层设计模式.java
More file actions
82 lines (82 loc) · 1.92 KB
/
Copy pathRedis-业务层设计模式.java
File metadata and controls
82 lines (82 loc) · 1.92 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
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
* Redis Service
* */
@Service
public class RedisService {
@Autowired
private ShardedJedisPool shardedJedisPool;
/**
* 往缓存中添加记录
* */
private <T> T execut(Function<ShardedJedis ,T> fun){
ShardedJedis shardedJedis = null;
try{
// 获取Redis连接
shardedJedis = shardedJedisPool.getResource();
return fun.callback(shardedJedis);
}finally{
//关闭连接
shardedJedis.close();
}
}
/**
* 设置值
* */
public String set(final String key,final String value){
return this.execut(new Function<ShardedJedis, String>() {
public String callback(ShardedJedis jedis) {
return jedis.set(key, value);
}
});
}
/**
* 设置值,同时设置生存时间
* 单位为秒
* */
public String set(final String key,final String value,final Integer seconds){
return this.execut(new Function<ShardedJedis, String>() {
public String callback(ShardedJedis jedis) {
String result = jedis.set(key, value);
jedis.expire(key, seconds);
return result;
}
});
}
/**
* 获取值
* */
public String get(String key){
return this.execut(new Function<ShardedJedis, String>() {
public String callback(ShardedJedis jedis) {
return jedis.get(key);
}
});
}
/**
* 根据Key删除数据
* */
public Long delete(String key){
return this.execut(new Function<ShardedJedis, Long>() {
public Long callback(ShardedJedis jedis) {
return jedis.del(key);
}
});
}
/**
* 根据Key删除数据
* */
public Long expire(String key,Integer seconnds){
return this.execut(new Function<ShardedJedis, Long>() {
public Long callback(ShardedJedis jedis) {
return jedis.expire(key, seconnds);
}
});
}
}
interface Function <T,E>{
public E callback(T t);
}