xiangpei
2024-07-11 5073a245f53fd5ca936e779be8c6b9b19d42f67d
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
56
57
58
59
60
61
62
63
64
65
66
67
package com.ycl.jxkg.job;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.ycl.jxkg.constants.CaffeineConstant;
import com.ycl.jxkg.domain.entity.StudyRecord;
import com.ycl.jxkg.mapper.StudyRecordMapper;
import com.ycl.jxkg.service.StudyRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
 
/**
 * @author:xp
 * @date:2024/7/1 11:06
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class StudyRecordJob {
 
    @Autowired
    private Cache<String, Object> caffeineCache;
    private final StudyRecordMapper studyRecordMapper;
    private final StudyRecordService studyRecordService;
 
    @Scheduled(fixedRate = 1200000) // 2分钟执行一次
    private void updateStudyRecord() {
        log.info("开始存学习时长");
        List<StudyRecord> cacheList = new ArrayList<>();
        // 取出所有学习记录缓存项
        ConcurrentMap<String, Object> map = caffeineCache.asMap();
        Map<String,StudyRecord> studyMap = (Map<String, StudyRecord>) map.get(CaffeineConstant.STUDY_RECORD);
        for (Map.Entry<String, StudyRecord> entry : studyMap.entrySet()) {
            cacheList.add(entry.getValue());
        }
 
        List<Integer> studentIds = cacheList.stream().map(StudyRecord::getStudentId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(studentIds)) {
            //数据库中已经存在的学生数据
            QueryWrapper<StudyRecord> wrapper = new QueryWrapper<>();
            wrapper.in("student_id", studentIds);
            List<StudyRecord> studyRecords = studyRecordMapper.selectList(wrapper);
            for (StudyRecord record : studyRecords) {
                for (StudyRecord cacheRecord : cacheList) {
                    if (record.getStudentId().equals(cacheRecord.getStudentId())) {
                        cacheRecord.setId(record.getId());
                        cacheRecord.setStudyTime(record.getStudyTime() + cacheRecord.getStudyTime());
                        cacheRecord.setMeetCount(record.getMeetCount());
                    }
                }
            }
            studyRecordService.saveOrUpdateBatch(cacheList);
        }
        caffeineCache.invalidate(CaffeineConstant.STUDY_RECORD);
        log.info("结束存学习时长");
    }
}