redis大key拆小key-Set(完整示例)

示例

@Component
public class HuaweiSmartLifeUserCacheData extends IValueRedisService<Set<String>> {
    @Override
    protected String getRedisKey() {
        return CacheKey.HUAWEI_SMART_LIFE_USER_KEY;
    }
}
@Component
public class HuaweiSmartLifeUserCacheUtils {
    private static final Logger logger = LoggerFactory.getLogger(HuaweiSmartLifeUserCacheUtils.class);

    @Autowired
    private HuaweiSmartLifeUserCacheData huaweiSmartLifeUserCacheData;

    public Boolean existsKey(String uid) {
        String key = getKey(uid);
        Set<String> uids = huaweiSmartLifeUserCacheData.get(key);
        if (uids == null) {
            return false;
        }
        return uids.contains(uid);
    }


    public String setKey(String uid) {
        String key = getKey(uid);
        Set<String> uids = huaweiSmartLifeUserCacheData.get(key);
        logger.info("新增前 uids:" + uids);
        if (uids == null) {
            uids = new HashSet<>();
        }
        uids.add(uid);
        logger.info("新增后 uids:" + uids);
        huaweiSmartLifeUserCacheData.put(key, uids);
        return key;
    }

    public Set<String> getByKey(String uid) {
        String key = getKey(uid);
        return huaweiSmartLifeUserCacheData.get(key);
    }

    public String removeByKey(String uid) {
        String key = getKey(uid);
        huaweiSmartLifeUserCacheData.remove(key);
        return key;
    }

    public String getKey(String str) {
        String prefix = "_group";
        return prefix + getHashKey(str);
    }

    public static int getHashKey(String key) {
        return (hash(key) & Integer.MAX_VALUE) % 5;
    }

    public static int hash(String key) {
        //1.将字母转化成ASCII,然后相加
        int hashValue = 0;
        if (StringUtils.isNotEmpty(key)) {
            key = key.toLowerCase();
        }
        for (int i = 0; i < key.length(); i++) {
            //a是97,其他字母减去97就是字母对应的数字
            int letter = key.charAt(i) - 'a' + 1;
            hashValue += letter;
        }
        //取模可以压缩可选值
        return hashValue & Integer.MAX_VALUE;
    }
}
@RestController
public class UserCacheController {
    private static final Logger logger = LoggerFactory.getLogger(UserCacheController.class);
    @Autowired
    private IHuaweiSmartLifeUserInfoService huaweiSmartLifeUserInfoService;
    @Autowired
    private HuaweiSmartLifeUserCacheUtils huaweiSmartLifeUserCacheUtils;
    @Autowired
    private HuaweiSmartLifeUserCacheData huaweiSmartLifeUserCacheData;


    @GetMapping("/user/initCache")
    public JSONObject initCache() {
        JSONObject jsonObject = new JSONObject();
        List<HuaweiSmartLifeUserInfo> userInfoList = huaweiSmartLifeUserInfoService.selectAll();
        if (userInfoList == null || userInfoList.size() == 0) {
            return jsonObject;
        }
        userInfoList = userInfoList.stream().limit(50).collect(Collectors.toList());
        logger.info("绑定用户数:" + userInfoList.size());
        String key;
        for (HuaweiSmartLifeUserInfo userInfo : userInfoList) {
            key = huaweiSmartLifeUserCacheUtils.setKey(userInfo.getThirdPartyUserId());
            // 统计一下每个key中包含的用户数
            if (jsonObject.containsKey(key)) {
                int temp = jsonObject.getInteger(key);
                jsonObject.put(key, temp + 1);
            } else {
                jsonObject.put(key, 1);
            }
        }
        return jsonObject;
    }

    @GetMapping("/user/getAllCache")
    public JSONObject getAllCache() {
        Set<String> keys = huaweiSmartLifeUserCacheData.keys();
        logger.info("keys:" + keys.toString());
        JSONObject jsonObject = new JSONObject();
        Set<String> uids;
        for (String key : keys) {
            logger.info("key:" + key.replace("huawei_smart_life_user", ""));
            uids = huaweiSmartLifeUserCacheData.get(key.replace("huawei_smart_life_user", ""));
            if (uids != null) {
                jsonObject.put(key, uids);
            }
        }
        return jsonObject;
    }

    @GetMapping("/user/removeAllCache")
    public void removeAllCache() {
        Set<String> keys = huaweiSmartLifeUserCacheData.keys();
        for (String key : keys) {
            key = key.replace("huawei_smart_life_user", "");
            logger.info("key:" + key.replace("huawei_smart_life_user", ""));
            huaweiSmartLifeUserCacheUtils.removeByKey(key);
        }

    }

    @GetMapping("/user/setByKey/{uid}")
    public JSONObject setByKey(@PathVariable(value = "uid") String uid) {
        JSONObject jsonObject = new JSONObject();
        logger.info("uid:" + uid);
        String key = huaweiSmartLifeUserCacheUtils.setKey(uid);
        jsonObject.put("key", key);
        return jsonObject;
    }

    @GetMapping("/user/getByKey/{uid}")
    public Set<String> getByKey(@PathVariable(value = "uid") String uid) {
        String key = huaweiSmartLifeUserCacheUtils.getKey(uid);
        logger.info("uid=" + uid + ",key=" + key);
        Set<String> set1 = huaweiSmartLifeUserCacheUtils.getByKey(uid);
        logger.info("set1:" + JSONArray.toJSONString(set1));
        Set<String> set2 = huaweiSmartLifeUserCacheData.get(key);
        logger.info("set2:" + JSONArray.toJSONString(set2));
        return set2;
    }

    @GetMapping("/user/removeByKey/{uid}")
    public void removeByKey(@PathVariable(value = "uid") String uid) {
        String key = huaweiSmartLifeUserCacheUtils.getKey(uid);
        Set<String> uids = huaweiSmartLifeUserCacheUtils.getByKey(key);
        logger.info("remove before:" + JSONArray.toJSONString(uids));
        if (uids.contains(uid)) {
            uids = uids.stream().filter(item -> !item.equals(uid)).collect(Collectors.toSet());
        }
        logger.info("remove end:" + JSONArray.toJSONString(uids));
        if (uids.size() > 0) {
            //将原来key中保存的内容替换
            huaweiSmartLifeUserCacheData.put(key, new HashSet<>(uids));
        } else {
            //列表中不包含任何元素时,删除这个key
            huaweiSmartLifeUserCacheUtils.removeByKey(key);
        }
    }
}

补充

  1. IValueRedisService是一个抽象类,主要是对RedisTemplate进一步封装,简化操作。
  2. 使用ValueOerations 的两种方法:
    2.1 方法一:
ValueOperations valueOperations = redisTemplate.opsForValue();

方法二:Redis配置类中配置

    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

在IValueRedisService中使用@Autowired

    @Autowired
    protected ValueOperations<String, T> valueOperations;
  • 19
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值