新增批量存redis方法

This commit is contained in:
2023-06-26 11:37:00 +08:00
parent 867459a671
commit e7aec156e8
4 changed files with 79 additions and 13 deletions

View File

@@ -1,24 +1,15 @@
package com.jsowell.common.core.redis;
import com.jsowell.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
@@ -72,6 +63,50 @@ public class RedisCache {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
* 批量保存
* @param source
* @param seconds
*/
public void multiSave(Map<String, Object> source, final Integer seconds) {
redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
// 这里逻辑简单不会抛异常
// 否则需要加上try...catch...finally防止链接未正常关闭 造成泄漏
connection.openPipeline();
source.forEach((key, value) -> {
if (StringUtils.isBlank(key) || Objects.isNull(value)) {
return;
}
// hset zset都是可以用的但是要序列化
connection.set(RedisSerializer.string().serialize(key), RedisSerializer.json().serialize(value));
// 设置过期时间 TimeUnit.DAYS.toSeconds(10)
connection.expire(RedisSerializer.string().serialize(key), seconds);
});
connection.close();
// executePipelined源码要求RedisCallback必须返回null否则抛异常
return null;
});
}
/**
* 删除单个对象(异步清除内存)
*
* @param key
*/
public boolean unlinkObject(final String key) {
return redisTemplate.unlink(key);
}
/**
* 实现命令 : INCR key
* 给 value 加 1,value 必须是整数
* @param key
* @return
*/
public Long incr(String key) {
return redisTemplate.opsForValue().increment(key);
}
/**
* 设置有效时间
*