Redis操作工具类

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

/**
 * Redis 操作工具类
 * 实现Hash数据保存并设置过期时间
 *
 * @author huxiang
 */
@Slf4j
@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 保存Hash数据并设置过期时间
     *
     * @param redisKey
     * @param hashKey
     * @param hashValue
     * @param expire
     * @param timeUnit
     */
    public void putAndExpireHash(String redisKey, String hashKey, Object hashValue, Long expire, TimeUnit timeUnit) {
        //转换成毫秒,然后跟当前时间比较
        Map redisData = new HashMap();
        redisData.put("storeData", hashValue);
        redisData.put("expireTime", System.currentTimeMillis() + timeUnit.toMillis(expire));
        ObjectMapper mapper = new ObjectMapper();
        try {
            redisTemplate.opsForHash().put(redisKey, hashKey, mapper.writeValueAsString(redisData));
        } catch (JsonProcessingException e) {
            log.error("类型转换异常-putAndExpireHash:" + e.getMessage());
        }
    }

    /**
     * 清理过期的Hash数据
     *
     * @param redisKey
     */
    public void clearHashExpireData(String redisKey) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(redisKey);
        if (entries == null || entries.size() == 0) {
            return;
        }
        ObjectMapper mapper = new ObjectMapper();
        //去掉l2中过期数据
        List<String> lstHashKey = new ArrayList<>();
        entries.entrySet().stream().forEach(app -> {
            Map map = null;
            try {
                map = mapper.readValue((String) app.getValue(), Map.class);
            } catch (IOException e) {
                log.error("类型转换异常-clearHashExpireData:" + e.getMessage());
            }
            if (map == null) {
                return;
            }
            long expireTime = (long) map.get("expireTime");
            if (expireTime < System.currentTimeMillis()) {
                lstHashKey.add((String) app.getKey());
            }
        });
        if (!CollectionUtils.isEmpty(lstHashKey)) {
            redisTemplate.opsForHash().delete(redisKey, lstHashKey.toArray());
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值