<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
public static void main(String[] args) {
Cache<String, LogDTO> cache = CacheBuilder.newBuilder()
.maximumSize(2) //设置最大存储
.expireAfterWrite(3,TimeUnit.SECONDS) //设置过期时间
.build();
LogDTO logDTO = new LogDTO();
logDTO.setId(StringUtil.getUUID());
cache.put(logDTO.getId(),logDTO);
LogDTO logDTO1 = new LogDTO();
logDTO1.setId(StringUtil.getUUID());
cache.put(logDTO1.getId(),logDTO1);
LogDTO logDTO2 = new LogDTO();
logDTO2.setId(StringUtil.getUUID());
cache.put(logDTO2.getId(),logDTO2);
System.out.println(cache.getIfPresent(logDTO.getId()));
System.out.println(cache.getIfPresent(logDTO1.getId()));
System.out.println(cache.getIfPresent(logDTO2.getId()));
List<String> list = new ArrayList<String>();
list.add(logDTO.getId());
list.add(logDTO1.getId());
//批量清除list中全部key对应的记录
cache.invalidateAll(list);
System.out.println(cache.getIfPresent(logDTO.getId()));
System.out.println(cache.getIfPresent(logDTO1.getId()));
System.out.println(cache.getIfPresent(logDTO2.getId()));
//单个删除
cache.invalidate(logDTO2.getId());
System.out.println(cache.getIfPresent(logDTO2.getId()));
}
public class CacheDTO {
private static Cache<String, RestLogDTO> restCache = null;
public static Cache<String, RestLogDTO> getRestCache(){
if(null == restCache){
restCache = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(360, TimeUnit.SECONDS)
.build();
}
return restCache;
}
}
CacheDTO.getRestCache().put(RestLogDTO.getId(),restLogDTO);
@Scheduled(cron ="0/10 * * * * ?" )
public void insertRestTask() {
List<String> logIdList = new ArrayList<String>();
List<RestLogDTO> logList = new ArrayList<RestLogDTO>();
int logCount = 0;
// 通过底层map得到iterator,以便后面遍历
Iterator<String> iterator = CacheDTO.getRestCache().asMap().keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
logCount ++;
logIdList.add(key);
logList.add(CacheDTO.getRestCache().getIfPresent(key));
if(logCount == 200){
batchRestLog(logList);
//清除已处理的缓存数据
CacheDTO.getRestCache().invalidateAll(logIdList);
//清空logList
logIdList.clear();
logList.clear();
logCount = 0;
}
}
if(logList.size() > 0 && logIdList.size() > 0){
batchRestLog(logList);
CacheDTO.getRestCache().invalidateAll(logIdList);
}
}
void batchRestLog(List<RestLogDTO> list);
<insert id="batchRestLog">
insert into `t_xx`(`url`,`param_json`,`data_status`,`result_message`,`remark`)
values
<foreach collection="list" item="dto" separator=",">
(#{dto.url}, #{dto.paramJson}, #{dto.dataStatus}, #{dto.resultMessage}, #{dto.remark})
</foreach>
</insert>