فهرست منبع

定时删除过期数据(3天前)

JiahengHe 1 سال پیش
والد
کامیت
74e68c6b2f

+ 3 - 0
price_collection/src/main/java/com/liangjiang/price_collection/mapper/TableMapper.java

@@ -16,6 +16,9 @@ public interface TableMapper {
     void createTable(@Param("tableName")String tableName);
     // 批量创建表
     void createTables(@Param("tableNames")Set<String> tableNames);
+    // 删除数据
+    void deleteData(@Param("tableNames")List<String> tableNames, @Param("time")Integer time);
+
     // 获取所有表名
     List<String> getTableName();
 

+ 3 - 0
price_collection/src/main/java/com/liangjiang/price_collection/service/ITableService.java

@@ -14,6 +14,9 @@ public interface ITableService {
     // 初始化交易所币对数据
     boolean initExchange(ExchangeCoinDto dto);
 
+    // 删除指定时间之前的数据
+    void deleteData(List<String> tableNames, Integer time);
+
     // 批量写入
     void savePriceBatch(List<PriceInfoDto> dtos);
 

+ 5 - 0
price_collection/src/main/java/com/liangjiang/price_collection/service/impl/TableServiceImpl.java

@@ -91,6 +91,11 @@ public class TableServiceImpl implements ITableService {
         }
     }
 
+    @Override
+    public void deleteData(List<String> tableNames, Integer time){
+        this.tableMapper.deleteData(tableNames, time);
+    }
+
     @Override
     public void savePriceBatch(List<PriceInfoDto> dtos){
         if(CollectionUtil.isEmpty(dtos)){

+ 28 - 0
price_collection/src/main/java/com/liangjiang/price_collection/task/DataTask.java

@@ -0,0 +1,28 @@
+package com.liangjiang.price_collection.task;
+
+import com.liangjiang.price_collection.service.ITableService;
+import com.liangjiang.price_collection.service.impl.QueryService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+
+@Component
+@RequiredArgsConstructor
+public class DataTask {
+
+    private final ITableService tableService;
+    // 每天1点30
+    @Scheduled(cron="0 30 1 * * ? ")
+    public void deleteData() {
+        // 获取3天前时间
+        Integer[] time = QueryService.getDaysAgoTime(System.currentTimeMillis(), 3);
+        Integer threeDayAgo = time[1];
+        // 获取所有表名
+        List<String> tableNames = tableService.getTableNames();
+        // 清除数据
+        tableService.deleteData(tableNames, threeDayAgo);
+    }
+
+}

+ 6 - 0
price_collection/src/main/resources/mapper/TableMapper.xml

@@ -22,6 +22,12 @@
         </foreach>
     </update>
 
+    <update id="deleteData">
+        <foreach item="item" collection="tableNames" open="" separator=";" close="">
+            delete FROM ${item} where id &lt; ${time}
+        </foreach>
+    </update>
+
     <!-- 获取所有数据表格 -->
     <select id="getTableName" resultType="java.lang.String">
         SELECT