郑永安
2023-09-19 69185134fcfaf913ea45f1255677225a2cc311a4
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
package com.gk.hotwork.Config.Oauth2;
 
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
 
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
/**
 * redis service
 *
 * @author zhangby
 * @date 2019-05-15 09:34
 */
@Service
public class IRedisService {
    /**
     * logger
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
    /**
     * redis service
     */
    @Autowired
    protected StringRedisTemplate redisTemplate;
    @Value("${spring.redis.database}")
    private Integer database;
 
   @PostConstruct
   public void initTest(){
       try {
           this.set("redisConnect", "testConnection", (long) 60);
           logger.info("redis-db connection测试连接成功");
       } catch (Exception e) {
           logger.error("redis-db connection测试连接失败");
       }
 
   }
    /**
     * Write to redis cache
     *
     * @param key key
     * @param value value
     * @return boolean
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        if (value != null) {
            try {
                ValueOperations operations = redisTemplate.opsForValue();
                if (value instanceof String) {
                    operations.set(key, value.toString());
                } else {
                    operations.set(key, JSON.toJSONString(value));
                }
                result = true;
            } catch (Exception e) {
                logger.info("Writing redis cache failed! The error message is:" + e.getMessage());
                e.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * Write redis cache (set expire survival time)
     *
     * @param key key
     * @param value value
     * @param expire time
     * @return boolean
     */
    public boolean set(final String key, Object value, Long expire) {
        boolean result = false;
        try {
            ValueOperations operations = redisTemplate.opsForValue();
            if (value instanceof String) {
                operations.set(key, value.toString());
            } else {
                operations.set(key, JSON.toJSONString(value));
            }
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            logger.info("Writing to the redis cache (setting the expire lifetime) failed! The error message is:" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
 
 
    /**
     * Read redis cache
     *
     * @param key key
     * @return object
     */
    public Object get(final String key) {
        Object result = null;
        try {
            ValueOperations operations = redisTemplate.opsForValue();
            result = operations.get(key);
        } catch (Exception e) {
            logger.info("Failed to read redis cache! The error message is:" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
 
    /**
     * Read redis to entity
     *
     * @param key   redis key
     * @param clazz 实体类class
     * @param <T>   泛型
     * @return T
     */
    public <T> T getBean(final String key, Class<T> clazz) {
        return Optional.ofNullable(get(key))
                .map(o -> JSON.parseObject(o.toString(), clazz))
                .orElse(null);
    }
 
    /**
     * Read redis to List
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> getArrayBean(final String key, Class<T> clazz) {
        return Optional.ofNullable(get(key))
                .map(o -> JSON.parseArray(o.toString(), clazz))
                .orElse(null);
    }
 
 
    /**
     * Determine if there is a corresponding key in the redis cache
     *
     * @param key key
     * @return boolean
     */
    public boolean exists(final String key) {
        boolean result = false;
        try {
            result = redisTemplate.hasKey(key);
        } catch (Exception e) {
           logger.info("Determine if there is a corresponding key in the redis cache failed! The error message is:" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
 
    /**
     * Redis deletes the corresponding value according to the key
     *
     * @param key key
     * @return boolean
     */
    public boolean remove(final String key) {
        boolean result = false;
        try {
            if (exists(key)) {
                redisTemplate.delete(key);
            }
            result = true;
        } catch (Exception e) {
            logger.info("Redis fails to delete the corresponding value according to the key! The error message is:" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
 
    /**
     * Redis deletes the corresponding value according to the keywords batch
     *
     * @param keys keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
 
 
    public void setDbIndex(Integer dbIndex) {
        if (dbIndex == null || dbIndex > 15 || dbIndex < 0) {
            dbIndex = database;
        }
        JedisConnectionFactory connectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory();
        if (connectionFactory == null) {
            return;
        }
        connectionFactory.setDatabase(dbIndex);
        redisTemplate.setConnectionFactory(connectionFactory);
    }
 
    public void rightPush(String key, String value) {
        redisTemplate.opsForList().rightPush(key, value);
    }
 
    public String leftPop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }
 
    public Long listSize(String key) {
        return redisTemplate.opsForList().size(key);
    }
 
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
 
    public void setExpiredTime(String key,long seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }
 
 
    /**
     * @Description: 获取以某个prefix为前缀的所有value
     * @date 2022/5/16 11:13
     */
    public List<String> getListKey(Set<String> keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }
 
    public Set<String> scan(String matchKey) {
        return redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keysTmp = new HashSet<>();
            Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(matchKey).count(1000).build());
            while (cursor.hasNext()) {
                keysTmp.add(new String(cursor.next()));
            }
            return keysTmp;
        });
    }
 
    public void expireAt(String key, Date date) {
        redisTemplate.expireAt(key, date);
    }
 
}