RedisCache.java
2.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
package com.cjs.cms.util.redis;
import java.io.Serializable;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.ibatis.cache.Cache;
import com.cjs.cms.util.redis.JedisTemplate.JedisAction;
import redis.clients.jedis.Jedis;
/**
* 自定义Mybatis整合Redis缓存
*
* @author tongyufu
*
*/
public final class RedisCache implements Cache {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private String id;
private static JedisTemplate jedisTemplate = new JedisTemplate();
public RedisCache(String id) {
this.id = id;
}
@Override
public void clear() {
this.getCache().flushDB();
}
@Override
public String getId() {
return this.id;
}
@Override
public void putObject(Object key, Object value) {
this.getCache().set(SerializationUtils.serialize((Serializable) key),
SerializationUtils.serialize((Serializable) value), 3600);
}
@Override
public Object getObject(Object key) {
byte[] bitKey = SerializationUtils.serialize((Serializable) key);
byte[] value = this.getCache().get(bitKey);
return value == null ? null : SerializationUtils.deserialize(value);
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
@Override
public int getSize() {
return this.getCache().execute(new JedisAction<Integer>() {
@Override
public Integer action(Jedis jedis) {
return Integer.parseInt(jedis.dbSize().toString());
}
});
}
@Override
public Object removeObject(final Object key) {
return this.getCache().execute(new JedisAction<Object>() {
@Override
public Object action(Jedis jedis) {
return jedis.expire(SerializationUtils.serialize((Serializable) key), 0);
}
});
}
private JedisTemplate getCache() {
return jedisTemplate;
}
}