| | |
| | | import java.util.Comparator; |
| | | import java.util.Date; |
| | | import java.util.HashMap; |
| | | import java.util.LinkedHashSet; |
| | | import java.util.Set; |
| | | import java.util.List; |
| | | import java.util.ArrayList; |
| | |
| | | @Slf4j |
| | | @Component |
| | | public class DeviceLogScheduler { |
| | | |
| | | private static final int BASE_BATCH_SIZE = 100; |
| | | private static final int BACKLOG_SCAN_LIMIT = 2000; |
| | | private static final int MAX_BATCH_SIZE = 1000; |
| | | |
| | | @Value("${deviceLogStorage.type}") |
| | | private String storageType; |
| | |
| | | |
| | | @Scheduled(cron = "0/3 * * * * ? ") |
| | | public void execute() { |
| | | int maxCount = 100; |
| | | Set<String> keys = redisUtil.scanKeys(RedisKeyType.DEVICE_LOG_KEY.key, maxCount); |
| | | if (keys == null || keys.isEmpty()) { |
| | | Set<String> scannedKeys = redisUtil.scanKeys(RedisKeyType.DEVICE_LOG_KEY.key, BACKLOG_SCAN_LIMIT); |
| | | if (scannedKeys == null || scannedKeys.isEmpty()) { |
| | | return; |
| | | } |
| | | Set<String> keys = selectBatchKeys(scannedKeys); |
| | | List<Object> values = redisUtil.multiGet(keys); |
| | | List<DeviceDataLog> list = new ArrayList<>(); |
| | | for (Object object : values) { |
| | |
| | | } |
| | | } |
| | | |
| | | private Set<String> selectBatchKeys(Set<String> scannedKeys) { |
| | | int backlog = scannedKeys.size(); |
| | | int batchSize = resolveBatchSize(backlog); |
| | | if (backlog <= batchSize) { |
| | | return scannedKeys; |
| | | } |
| | | LinkedHashSet<String> selected = new LinkedHashSet<>(); |
| | | for (String key : scannedKeys) { |
| | | selected.add(key); |
| | | if (selected.size() >= batchSize) { |
| | | break; |
| | | } |
| | | } |
| | | return selected; |
| | | } |
| | | |
| | | private int resolveBatchSize(int backlog) { |
| | | if (backlog <= BASE_BATCH_SIZE) { |
| | | return backlog; |
| | | } |
| | | int adaptive = Math.max(BASE_BATCH_SIZE, backlog / 2); |
| | | int rounded = ((adaptive + BASE_BATCH_SIZE - 1) / BASE_BATCH_SIZE) * BASE_BATCH_SIZE; |
| | | return Math.min(MAX_BATCH_SIZE, rounded); |
| | | } |
| | | |
| | | private void mysqlSave(Set<String> keys, List<DeviceDataLog> list) { |
| | | if (deviceDataLogService.saveBatch(list)) { |
| | | redisUtil.del(keys.toArray(new String[0])); |