当前位置:   article > 正文

RedisTemplate工具类

redistemplate工具类

RedisTemplate工具类,精心整理,精心注释。

package com.bananalab.utils;

import com.bananalab.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 秒
     */
    public void expire(String key, long time) {
        if (time > 0) {
            Boolean res = redisTemplate.expire(key, time, TimeUnit.SECONDS);
            log.info("指定缓存失效时间:" + key + ",结果:" + res);
        }
    }

    /**
     * 指定缓存失效时间
     *
     * @param key      键
     * @param time     秒
     * @param timeUnit 单位
     */
    public void expire(String key, long time, TimeUnit timeUnit) {
        if (time > 0) {
            redisTemplate.expire(key, time, timeUnit);
        }
    }

    /**
     * 获取过期时间
     *
     * @param key 键 不能为null
     * @return 单位:秒,0代表永久有效,-2代表无效key
     */
    public long getExpire(Object key) {
        if (null == key) {
            return -2L;
        }
        Long res = redisTemplate.getExpire(key, TimeUnit.SECONDS);
        if (null == res) {
            return -2L;
        }
        return res;
    }

    /**
     * 查找匹配key
     *
     * @param pattern key,*key*,*key,key*
     * @return 匹配的所有key
     */
    public List<String> scan(String pattern) {
        ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
        RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
        RedisConnection rc = Objects.requireNonNull(factory).getConnection();
        Cursor<byte[]> cursor = rc.scan(options);
        List<String> result = new ArrayList<>();
        while (cursor.hasNext()) {
            result.add(new String(cursor.next()));
        }
        RedisConnectionUtils.releaseConnection(rc, factory, true);
        return result;
    }

    /**
     * 分页查询 key
     *
     * @param patternKey key
     * @param page       页码,0开始
     * @param size       每页数目
     * @return 没有返回size=0数组
     */
    public List<String> findKeysPage(String patternKey, int page, int size) {
        ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
        RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
        RedisConnection rc = Objects.requireNonNull(factory).getConnection();
        Cursor<byte[]> cursor = rc.scan(options);
        List<String> result = new ArrayList<>(size);
        int tmpIndex = 0;
        int fromIndex = page * size;
        int toIndex = page * size + size;
        while (cursor.hasNext()) {
            if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
                result.add(new String(cursor.next()));
                tmpIndex++;
                continue;
            }
            // 获取到满足条件的数据后,就可以退出了
            if (tmpIndex >= toIndex) {
                break;
            }
            tmpIndex++;
            cursor.next();
        }
        RedisConnectionUtils.releaseConnection(rc, factory, true);
        return result;
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true-存在,false-不存在
     */
    public boolean hasKey(String key) {
        Boolean res = redisTemplate.hasKey(key);
        if (null == res) {
            return false;
        }
        return res;
    }

    /**
     * 删除缓存,有几个key就删除几个
     *
     * @param keys 可以传一个值或多个
     */
    public void del(String... keys) {
        if (keys != null && keys.length > 0) {
            Set<Object> keySet = new HashSet<>(Arrays.asList(keys));
            Long count = redisTemplate.delete(keySet);
            log.info("计划删除缓存:" + keySet + ",成功删除:" + count + "个");
        }
    }

    // ===================================Key Value===================================

    /**
     * 获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 批量获取
     *
     * @param keys 键
     * @return 值
     */
    public List<Object> multiGet(Set<Object> keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /**
     * 存,无限期
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 存,并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  单位:秒,如果time小于等于0将设置无限期
     */
    public void set(String key, Object value, long time) {
        if (time > 0) {
            set(key, value, time, TimeUnit.SECONDS);
        } else {
            set(key, value);
        }
    }

    /**
     * 存,并设置时间
     *
     * @param key      键
     * @param value    值
     * @param time     时间
     * @param timeUnit 类型
     */
    public void set(String key, Object value, long time, TimeUnit timeUnit) {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, timeUnit);
        } else {
            set(key, value);
        }
    }

    // ================================Hash=================================

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true-存在,false-不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * Hash,Get
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * Hash,获取所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hEntries(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * Hash,存
     *
     * @param key 键
     * @param map 对应多个键值
     */
    public void hPutAll(String key, Map<String, Object> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * Hash,存,并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 单位:秒
     */
    public void hPutAll(String key, Map<String, Object> map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        if (time > 0) {
            expire(key, time);
        }
    }

    /**
     * Hash,存项
     *
     * @param key   键
     * @param item  项
     * @param value 值
     */
    public void hPut(String key, String item, Object value) {
        redisTemplate.opsForHash().put(key, item, value);
    }

    /**
     * Hash,删除
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个不能为null
     */
    public void hdel(String key, Object... item) {
        Long num = redisTemplate.opsForHash().delete(key, item);
        log.info("Hash计划删除key:" + key + ",item:" + Arrays.toString(item) + ",实际删除:" + num + "个");
    }

    /**
     * hash递增,仅适用于value是数字的值,如果不存在就创建
     *
     * @param key  键
     * @param item 项
     * @param by   要增加数
     * @return 新增后的值
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减,仅适用于value是数字的值,如果不存在就创建
     *
     * @param key  键
     * @param item 项
     * @param by   要减少数
     * @return 递减后的值
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    // ============================Set=============================

    /**
     * Set,根据key获取Set中的所有值
     *
     * @param key 键
     * @return Set中的所有值
     */
    public Set<Object> setMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * Set,是否存在某个值
     *
     * @param key   键
     * @param value 值
     * @return true-存在,false-不存在
     */
    public boolean setIsMember(String key, Object value) {
        Boolean isMember = redisTemplate.opsForSet().isMember(key, value);
        if (null == isMember) {
            return false;
        }
        return isMember;
    }

    /**
     * Set,长度
     *
     * @param key 键
     * @return 长度
     */
    public long setSize(String key) {
        Long size = redisTemplate.opsForSet().size(key);
        if (null == size) {
            return 0;
        }
        return size;
    }

    /**
     * Set,存
     *
     * @param key    键
     * @param values 值,可以是多个
     * @return 成功存入个数
     */
    public long setAdd(String key, Object... values) {
        Long num = redisTemplate.opsForSet().add(key, values);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * Set,存,并设置过期时间
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功存入个数
     */
    public long setAddTime(String key, long time, Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        if (time > 0) {
            expire(key, time);
        }
        if (null == count) {
            return 0;
        }
        return count;
    }

    /**
     * Set,弹出
     *
     * @param key key
     * @return 一个值
     */
    public Object setPop(String key) {
        return redisTemplate.opsForSet().pop(key);
    }

    /**
     * Set,移除值为value的值
     *
     * @param key    键
     * @param values 值,可以是多个
     * @return 实际移除的个数
     */
    public long setRemove(String key, Object... values) {
        Long count = redisTemplate.opsForSet().remove(key, values);
        log.info("Set计划删除key:" + key + ",values:" + Arrays.toString(values) + ",实际删除:" + count + "个");
        if (null == count) {
            return 0;
        }
        return count;
    }

    // ===============================List=================================

    /**
     * List,获取
     *
     * @param key   键
     * @param start 开始,包含,0开始
     * @param end   结束,不包含
     * @return 数据集合
     */
    public List<Object> listRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * List,长度
     *
     * @param key 键
     * @return 长度
     */
    public long listSize(String key) {
        Long size = redisTemplate.opsForList().size(key);
        if (null == size) {
            return 0;
        }
        return size;
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引index>=0时,0表头;index<0时,-1表尾
     * @return 值
     */
    public Object listIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    /**
     * List,右侧放入
     *
     * @param key   键
     * @param value 值
     * @return 数组长度
     */
    public long listRightPush(String key, Object value) {
        Long num = redisTemplate.opsForList().rightPush(key, value);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,右侧放入多个
     *
     * @param key   键
     * @param value 值
     * @return 数组长度
     */
    public long listRightPushAll(String key, List<Object> value) {
        Long num = redisTemplate.opsForList().rightPushAll(key, value);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,value1右侧放入,如果没有value1则不放入
     *
     * @param key    键
     * @param value1 值
     * @param value2 值
     * @return 数组长度,失败返回-1
     */
    public long listRightPush(String key, Object value1, Object value2) {
        Long num = redisTemplate.opsForList().rightPush(key, value1, value2);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,右侧放入,key值必须存在
     *
     * @param key   键
     * @param value 值
     * @return 数组长度,失败返回-1
     */
    public long listRightPushIfPresent(String key, Object value) {
        Long num = redisTemplate.opsForList().rightPushIfPresent(key, value);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,左侧放入
     *
     * @param key   键
     * @param value 值
     * @return 数组长度
     */
    public long listLeftPush(String key, Object value) {
        Long num = redisTemplate.opsForList().leftPush(key, value);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,左侧放入,多个
     *
     * @param key    键
     * @param values 值
     * @return 数组长度
     */
    public long listLeftPushAll(String key, List<Object> values) {
        Long num = redisTemplate.opsForList().leftPushAll(key, values);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,左侧放入,当key存在的时候
     *
     * @param key   键
     * @param value 值
     * @return 数组长度,失败返回-1
     */
    public long listLeftPushIfPresent(String key, Object value) {
        Long num = redisTemplate.opsForList().leftPushIfPresent(key, value);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,value1左侧放入,没有value1则不放入
     *
     * @param key    键
     * @param value1 值1
     * @param value2 值2
     * @return 数组长度,失败返回-1
     */
    public long listLeftPush(String key, Object value1, Object value2) {
        Long num = redisTemplate.opsForList().leftPush(key, value1, value2);
        if (null == num) {
            return 0;
        }
        return num;
    }

    /**
     * List,根据索引修改某条数据
     * 索引不正确会抛出异常:ERR index out of range
     *
     * @param key   键
     * @param index 索引,0开始
     * @param value 值
     */
    public void listSet(String key, long index, Object value) {
        redisTemplate.opsForList().set(key, index, value);
    }

    /**
     * List,移除N个值为value,左边开始移出
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     */
    public void listRemove(String key, long count, Object value) {
        Long num = redisTemplate.opsForList().remove(key, count, value);
        log.info("List计划移出元素" + value + count + "个,实际移出" + num + "个");
    }
}

  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/240499?site
推荐阅读
相关标签
  

闽ICP备14008679号