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());
}
}
}
Redis操作工具类
于 2022-10-26 15:15:19 首次发布