package com.zt.task; import com.zt.common.utils.CommonUtils; import com.zt.life.modules.mainPart.basicInfo.service.XhProductModelService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.Cursor; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ScanOptions; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; import java.util.concurrent.TimeUnit; @Component public class UpdateDataTask { private static final Logger logger = LoggerFactory.getLogger(UpdateDataTask.class); @Autowired private RedisTemplate redisTemplate; @Autowired XhProductModelService xhProductModelService; @Scheduled(cron = "0 0 3 * * ?") //每天3点执行 public void task() { logger.info("更新数据task开始"); Date beginDate = new Date(); xhProductModelService.refreshCache(); purgeRedis(); logger.info("更新数据task耗时:" + CommonUtils.getDatePoor(new Date(), beginDate)); logger.info("更新数据task结束"); } private void purgeRedis() { Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection( (RedisCallback>) connection -> connection.scan(ScanOptions.NONE) ); while (cursor.hasNext()) { String key = new String(cursor.next()); System.out.println(key); Long ttl = redisTemplate.getExpire(key); if (ttl == -1) { redisTemplate.expire(key, 7*24*3600, TimeUnit.SECONDS); System.out.println("set key["+key+"] expire 7 days"); } } } }