1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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<byte[]> cursor = (Cursor<byte[]>) redisTemplate.executeWithStickyConnection(
                (RedisCallback<Cursor<byte[]>>) 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");
            }
        }
    }
 
}