IRedisService.java
2.29 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
package com.huaheng.common.redis.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public abstract class IRedisService<T> {
@Autowired
protected RedisTemplate<String, Object> redisTemplate;
@Resource
protected HashOperations<String, String, T> hashOperations;
/**
* 存入redis中的key
*
* @return
*/
protected abstract String getRedisKey();
/**
* 添加
*
* @param key key
* @param doamin 对象
* @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
*/
public void put(String key, T doamin, long expire) {
hashOperations.put(getRedisKey(), key, doamin);
if (expire != -1) {
redisTemplate.expire(getRedisKey(), expire, TimeUnit.SECONDS);
}
}
/**
* 删除
*
* @param key 传入key的名称
*/
public void remove(String key) {
hashOperations.delete(getRedisKey(), key);
}
/**
* 查询
*
* @param key 查询的key
* @return
*/
public T get(String key) {
return hashOperations.get(getRedisKey(), key);
}
/**
* 获取当前redis库下所有对象
*
* @return
*/
public List<T> getAll() {
return hashOperations.values(getRedisKey());
}
/**
* 查询查询当前redis库下所有key
*
* @return
*/
public Set<String> getKeys() {
return hashOperations.keys(getRedisKey());
}
/**
* 判断key是否存在redis中
*
* @param key 传入key的名称
* @return
*/
public boolean isKeyExists(String key) {
return hashOperations.hasKey(getRedisKey(), key);
}
/**
* 查询当前key下缓存数量
*
* @return
*/
public long count() {
return hashOperations.size(getRedisKey());
}
/**
* 清空redis
*/
public void empty() {
Set<String> set = hashOperations.keys(getRedisKey());
set.stream().forEach(key -> hashOperations.delete(getRedisKey(), key));
}
}