批量友好的删除redis缓存

/*
 * Copyright 2021 Wicrenet, Inc. All rights reserved.
 */
package com.hq.cloud.controller;

import com.hq.cloud.base.Result;
import com.hq.cloud.dict.CacheConfigs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 【】
 *
 * @author yangjunxiong
 * Created on 2021/6/21 9:59
 */
@RestController
@Api(tags = {"缓存接口"}, description = "缓存接口")
@RequestMapping("/cache/redis")
public class RedisCacheController {
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "清除缓存接口", notes = "清除缓存接口")
    @PostMapping("/clear")
    public Result clear(String key) {
        EnumUtils.getEnumList(CacheConfigs.class).forEach(item -> {
            if (StringUtils.equals(key, item.getKey())) {
                this.deleteBatchByKeys(key);
            }
        });
        return Result.success();
    }

    /**
     * 【 递归删除redis key-value 】
     *
     * @author yangjunxiong
     * @date 2021/6/21 10:05
     **/
    public Set<String> deleteBatchByKeys(String key) {
        Set<String> keys = new HashSet<>();
        this.redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
                    .match(key + "*")
                    .count(5000).build())) {
                while (cursor.hasNext()) {
                    keys.add(new String(cursor.next(), StandardCharsets.UTF_8));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return keys;
        });
        if (CollectionUtils.isEmpty(keys)) {
            return Collections.emptySet();
        }
        for (String key1 : keys) {
            this.redisTemplate.delete(key1);
        }
        if (CollectionUtils.isNotEmpty(keys)) {
            return this.deleteBatchByKeys(key);
        }
        return keys;
    }
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐