许鹏程
2024-09-26 b3ee22903d12461ee5bf6e3b38e1684a6daa61ea
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
package com.product.datasource.service;
 
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.product.common.serialization.SerializationUtils;
import com.product.core.cache.util.CacheCommonUtil;
import com.product.core.cache.util.RedisUtil;
import com.product.core.exception.BaseException;
import com.product.datasource.config.ErrorCode;
import com.product.datasource.entity.DataBaseEntity;
import com.product.datasource.utils.RedisSentinelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
 
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * Copyright © 6c
 *
 * @Date 2022年07月14日 14:37
 * @Author 6c
 * @Description
 */
public class RedisService {
    private JSONObject curObj;
    private static final int CONNECTION_TIMEOUT = 60000;// 连接超时时间
    private static final int SO_TIMEOUT = 60000;// 读取超时时间
    private static Map<JSONObject, JedisPool> map = Maps.newHashMap();
    private static Map<JSONObject, JedisSentinelPool> sentinelPoolMap = Maps.newHashMap();
    private static Map<JSONObject, RedisSentinelUtil> redisSentinelUtil = Maps.newHashMap();
 
    public RedisService(DataBaseEntity dbe) {
        try {
            curObj = new JSONObject();
            curObj.put("ip", dbe.getIp());
            curObj.put("port", dbe.getPort());
            curObj.put("password", dbe.getPassWord());
            curObj.put("dbIndex", StringUtils.isEmpty(dbe.getDbInstance()) ? 0 : Integer.parseInt(dbe.getDbInstance()));
            curObj.put("db_type", dbe.getDbTypeByInt());
            curObj.put("user_name", dbe.getUserName());
        } catch (Exception e) {
            throw new BaseException(ErrorCode.GET_REDIS_CONNECTION_FAIL);
        }
    }
 
    public void close() {
        if (curObj != null) {
            curObj = null;
        }
    }
 
    public static void destory() {
        map.forEach((k, v) -> {
            v.close();
        });
    }
 
    /**
     * 获取jedis
     *
     * @return Jedis
     */
    public Jedis getJedis() {
        String dbType = curObj.getString("db_type");
        Jedis jedis;
        if ("6".equals(dbType)) {
            jedis = getSentinelPool().getResource();
        } else {
            jedis = getJedisPool().getResource();
        }
        jedis.select(curObj.getIntValue("dbIndex"));
        return jedis;
    }
 
    /**
     * 获取redis连接
     *
     * @param readOnly 只读
     * @return
     */
    public Jedis getJedis(boolean readOnly) {
        //
        if (false && "6".equals(curObj.getString("db_type")) && readOnly) {
            RedisSentinelUtil redisSentinelUtil = this.redisSentinelUtil.get(this.curObj);
            if (redisSentinelUtil == null) {
                this.getSentinelPool();
                redisSentinelUtil = this.redisSentinelUtil.get(this.curObj);
            }
            Jedis jedis = redisSentinelUtil.getResource();
            jedis.select(curObj.getIntValue("dbIndex"));
            return jedis;
        } else {
            return getJedis();
        }
    }
 
    /**
     * 主从哨兵获取jedis
     *
     * @return
     */
    private JedisSentinelPool getSentinelPool() {
        JedisSentinelPool jedisPool = sentinelPoolMap.get(curObj);
        if (jedisPool == null) {
            synchronized (curObj.toJSONString().intern()) {
                if (sentinelPoolMap.containsKey(curObj)) {
                    jedisPool = sentinelPoolMap.get(curObj);
                }
                if (jedisPool == null) {
                    //哨兵模式
                    String[] ip = curObj.getString("ip").split(",");
                    GenericObjectPoolConfig<Jedis> poolConfig = new GenericObjectPoolConfig<>();
                    //线程池最大数量
                    poolConfig.setMaxIdle(100);
                    //等待时间
                    poolConfig.setMaxWaitMillis(60000);
                    poolConfig.setTestOnBorrow(true);
                    int connectionTimeout = 5000;
                    int soTimeout = 5000;
                    String password = null;
                    int database = 0;
                    HashSet<String> sentinels = Sets.newHashSet(ip);
                    jedisPool = new JedisSentinelPool(curObj.getString("user_name"), sentinels, poolConfig,
                            connectionTimeout, soTimeout, password, database);
                    sentinelPoolMap.put(curObj, jedisPool);
                    redisSentinelUtil.put(curObj, new RedisSentinelUtil(sentinels, jedisPool, poolConfig, curObj.getString("user_name")));
                }
            }
        }
        return jedisPool;
    }
 
    /**
     * 单机获取
     *
     * @return
     */
    private JedisPool getJedisPool() {
        JedisPool jedisPool = map.get(curObj);
        if (jedisPool == null) {
            synchronized (curObj.toJSONString().intern()) {
                if (!map.containsKey(curObj)) {
                    // 设置配置
                    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
                    jedisPoolConfig.setMaxTotal(100);// 最大连接数
                    jedisPoolConfig.setMaxIdle(20);// 最大空闲数
                    jedisPoolConfig.setMaxWaitMillis(CONNECTION_TIMEOUT);
                    jedisPoolConfig.setTestOnBorrow(true);
                    jedisPoolConfig.setTestOnReturn(true);
                    // 初始化JedisPool
                    jedisPool = new JedisPool(
                            jedisPoolConfig,
                            curObj.getString("ip"),
                            curObj.getIntValue("port"),
                            SO_TIMEOUT,
                            StringUtils.isEmpty(curObj.getString("password")) ? null : curObj.getString("password"));
                    map.put(curObj, jedisPool);
                } else {
                    jedisPool = map.get(curObj);
                }
            }
        }
//        Jedis jedis = jedisPool.getResource();
//        jedis.select(curObj.getIntValue("dbIndex"));
        return jedisPool;
    }
 
    /*==================key-start==================*/
    public static void main(String[] args) throws InterruptedException {
    }
 
    public static void test2() throws InterruptedException {
        DataBaseEntity dbe = new DataBaseEntity(5);
        dbe.setIp("10.4.3.78");
        dbe.setPort("6390");
        RedisService redisService = new RedisService(dbe);
        if (redisService.existsHash("DC:" + ("TT_T_WIP_REPAIR").toLowerCase() + ":4", "6a662ff2-c124-40ef-950f-4d1329ec624b")) {
            redisService.delHash("DC:" + ("TT_T_WIP_REPAIR").toLowerCase() + ":4", "6a662ff2-c124-40ef-950f-4d1329ec624b");
            System.out.println("清除");
        }
 
    }
 
    /**
     * 模糊匹配key
     *
     * @param pattern 匹配正则表达式
     * @return
     */
    public String[] getKeys(String pattern, boolean flag) {
        if (!StringUtils.isEmpty(pattern)) {
            try (Jedis jedis = getJedis(true)) {
                if (flag) {
                    Set<byte[]> keyBytes = jedis.keys(pattern.getBytes(StandardCharsets.UTF_8));
                    if (!CollectionUtil.isEmpty(keyBytes)) {
                        return keyBytes.stream().map(item -> new String(item, StandardCharsets.UTF_8)).toArray(String[]::new);
                    }
                } else {
                    Set<String> keys = jedis.keys(pattern);
                    if (!CollectionUtil.isEmpty(keys)) {
                        return keys.toArray(new String[0]);
                    }
                }
            }
        }
        return null;
    }
 
    public String[] getKeys(String pattern) {
        return getKeys(pattern, true);
    }
 
    /**
     * 判定是否存在key
     *
     * @param key 关键字
     * @return 是否存在
     */
    public boolean exists(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        try (Jedis jedis = getJedis(true)) {
            return jedis.exists(key);
        }
    }
 
    /**
     * 删除key
     *
     * @param keys 关键字...
     */
    public void del(String... keys) {
        try (Jedis jedis = getJedis(false)) {
            for (String key : keys) {
                if (StringUtils.isEmpty(key)) {
                    continue;
                }
                jedis.del(key);
            }
        }
    }
 
    /**
     * 删除key
     *
     * @param keys 关键字...
     */
    public void del(boolean serializeFlag, String... keys) {
        try (Jedis jedis = getJedis(false)) {
            if (!serializeFlag) {
                del(keys);
            }
            for (String key : keys) {
                if (StringUtils.isEmpty(key)) {
                    continue;
                }
                if (serializeFlag) {
                    jedis.del(SerializationUtils.serialize(key));
                }
            }
        }
    }
 
    /**
     * 设置超时时间
     *
     * @param key           关键字
     * @param outTime       超时时间,单位:秒
     * @param serializeFlag 是否序列化
     * @return
     */
    public boolean setOutTime(String key, int outTime, boolean serializeFlag) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        try (Jedis jedis = getJedis(false)) {
            Long result;
            if (serializeFlag) {
                result = jedis.expire(SerializationUtils.serialize(key), outTime);
            } else {
                result = jedis.expire(key, outTime);
            }
            return result != null && result == 1L;
        }
    }
 
    public void setOutTime(String key, int minOutTime, int maxOutTime, boolean serializeFlag) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        if (maxOutTime < minOutTime || maxOutTime <= 0) {
            return;
        }
        int outTime = (int) (Math.random() * (maxOutTime - minOutTime)) + minOutTime;
        setOutTime(key, outTime, serializeFlag);
    }
 
    /**
     * 移除超时时间
     *
     * @param key 关键字
     */
    public void clearOutTime(String key) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        try (Jedis jedis = getJedis(false)) {
            jedis.persist(key);
        }
    }
 
    /**
     * 获取指定key的剩余过期时间
     *
     * @param key 关键字
     * @return 剩余过期时间,单位:秒(特殊值如-2:没有这个key;-1:有key单没有设置过期时间,就是不过期)
     */
    public Long getOutTime(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        try (Jedis jedis = getJedis(false)) {
            return jedis.ttl(key);
        }
    }
 
    /**
     * 获取redis中的类型
     *
     * @param key 关键字
     * @return redis的数据类型:String, hash, list, set, zset,若是key不存在,则返回"none"
     */
    public String getType(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        try (Jedis jedis = getJedis(true)) {
            return jedis.type(key);
        }
    }
    /*==================key-final==================*/
 
    /*==================string-start==================*/
 
    /**
     * 新增
     *
     * @param key           关键字
     * @param value         值,非null
     * @param serializeFlag 序列化标识
     */
    public void set(String key, Object value, boolean serializeFlag) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        if (value == null) {
            return;
        }
        try (Jedis jedis = getJedis(false)) {
            if (!serializeFlag && value instanceof String) {
                jedis.set(key, value.toString());
            } else {
                jedis.set(SerializationUtils.serialize(key), SerializationUtils.serialize(value));
            }
        }
    }
 
    /**
     * 获取指定key的value
     *
     * @param key           关键字
     * @param serializeFlag 序列化标识
     * @return 值,不存在key会返回null
     */
    public Object get(String key, boolean serializeFlag) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        try (Jedis jedis = getJedis(true)) {
            if (serializeFlag) {
                return jedis.get(SerializationUtils.serialize(key)) == null ? null : SerializationUtils.deserialize(jedis.get(SerializationUtils.serialize(key)));
            } else {
                return jedis.get(key);
            }
        }
    }
    /*==================string-final==================*/
 
    /*==================hash-start==================*/
 
    /**
     * hash-新增
     *
     * @param key   关键字
     * @param field 字段名
     * @param value 字段值
     */
    public void setHash(String key, String field, Object value) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        if (StringUtils.isEmpty(field)) {
            return;
        }
        if (value == null) {
            return;
        }
        try (Jedis jedis = getJedis(false)) {
            jedis.hset(key.getBytes(StandardCharsets.UTF_8), field.getBytes(StandardCharsets.UTF_8), SerializationUtils.serialize(value));
        }
    }
 
    /**
     * hash-新增
     *
     * @param key 关键字
     * @param map 内容Map
     */
    public void setHash(String key, Map<String, Object> map) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        Map<byte[], byte[]> param = Maps.newHashMap();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            param.put(entry.getKey().getBytes(StandardCharsets.UTF_8), SerializationUtils.serialize(entry.getValue()));
        }
        try (Jedis jedis = getJedis(false)) {
            jedis.hmset(key.getBytes(StandardCharsets.UTF_8), param);
        }
    }
 
    /**
     * hash-判定是否存在
     *
     * @param key   关键字
     * @param field 字段名
     * @return 是否存在
     */
    public boolean existsHash(String key, String field) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        if (StringUtils.isEmpty(field)) {
            return false;
        }
        try (Jedis jedis = getJedis(true)) {
            return jedis.hexists(key.getBytes(StandardCharsets.UTF_8), field.getBytes(StandardCharsets.UTF_8));
        }
    }
 
    /**
     * hash-获取字段值
     *
     * @param key   关键字
     * @param field 字段名
     * @return 字段值
     */
    public Object getHash(String key, String field) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        if (StringUtils.isEmpty(field)) {
            return null;
        }
        try (Jedis jedis = getJedis(true)) {
            return SerializationUtils.deserialize(jedis.hget(key.getBytes(StandardCharsets.UTF_8), field.getBytes(StandardCharsets.UTF_8)));
        }
    }
 
    /**
     * hash-获取所有字段内容集合
     *
     * @param key 关键字
     * @return 所有字段内容集合
     */
    public Map<String, Object> getHash(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        try (Jedis jedis = getJedis(true)) {
            Map<byte[], byte[]> map = jedis.hgetAll(key.getBytes(StandardCharsets.UTF_8));
            Map<String, Object> result = Maps.newHashMap();
            Object field;
            for (Map.Entry<byte[], byte[]> entry : map.entrySet()) {
                field = StringUtils.toEncodedString(entry.getKey(), Charset.forName("UTF-8"));
                result.put(field.toString(), SerializationUtils.deserialize(entry.getValue()));
            }
            return result;
        }
    }
 
    /**
     * hash-获取指定key的拥有的字段数
     *
     * @param key 关键字
     * @return 拥有的字段数
     */
    public Long getHashLength(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        try (Jedis jedis = getJedis(true)) {
            return jedis.hlen(key.getBytes(StandardCharsets.UTF_8));
        }
    }
 
    /**
     * hash-获取指定key的字段名集合
     *
     * @param key 关键字
     * @return 字段名集合
     */
    public List<String> getHashFields(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        try (Jedis jedis = getJedis(true)) {
            Set<byte[]> set = jedis.hkeys(key.getBytes(StandardCharsets.UTF_8));
            if (set != null && set.size() > 0) {
                return set.stream().collect(Collectors.toList()).stream().map(bytes -> StringUtils.toEncodedString(bytes, Charset.forName("UTF-8"))).collect(Collectors.toList());
            }
            return null;
        }
    }
 
    /**
     * hash-获取指定key的所有value集合
     *
     * @param key 关键字
     * @return value集合
     */
    public List<Object> getHashValues(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        return getHashValues(key, Object.class);
    }
 
    /**
     * hash-获取指定key的所有value集合
     *
     * @param key 关键字
     * @return value集合
     */
    public <T> List<T> getHashValues(String key, Class<T> t) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        try (Jedis jedis = getJedis(true)) {
            return CacheCommonUtil.deserializeCollection(jedis.hvals(key.getBytes(StandardCharsets.UTF_8)), t);
        }
    }
 
    /**
     * hash-获取指定key的指定字段内容集合
     *
     * @param key    关键字
     * @param fields 字段名集合
     * @return 字段内容集合
     */
    public List<Object> getHashAimFieldValues(String key, String... fields) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        return getHashAimFieldValues(key, Object.class, fields);
    }
 
    /**
     * hash-获取指定key的指定字段内容集合
     *
     * @param key    关键字
     * @param fields 字段名集合
     * @return 字段内容集合
     */
    public <T> List<T> getHashAimFieldValues(String key, Class<T> t, String... fields) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        byte[][] bytes = Arrays.stream(fields).map(field -> field.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
        try (Jedis jedis = getJedis(true)) {
            return CacheCommonUtil.deserializeCollection(jedis.hmget(key.getBytes(StandardCharsets.UTF_8), bytes), t);
        }
    }
 
    /**
     * hash-删除
     *
     * @param key    关键字
     * @param fields 字段名...
     * @return 删除个数
     */
    public Long delHash(String key, String... fields) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        byte[][] bytes = Arrays.stream(fields).map(field -> field.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
        try (Jedis jedis = getJedis(false)) {
            return jedis.hdel(key.getBytes(StandardCharsets.UTF_8), bytes);
        }
    }
    /*==================hash-final==================*/
}