用JAVA写一个定时任务,定时清理es(mtime 修改时间是30天之前)的数据
时间: 2023-07-04 10:03:59 浏览: 190
JAVA定时任务
可以使用Java的ScheduledExecutorService类来实现定时任务,然后使用Java API连接到ES服务器,执行删除操作。
以下是代码示例:
```java
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
public class EsDataCleaner {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(new EsCleanTask(), 0, 24, TimeUnit.HOURS);
}
static class EsCleanTask implements Runnable {
@Override
public void run() {
RestHighLevelClient client = null;
try {
// 连接ES服务器
client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));
// 构造搜索请求,查询mtime字段小于30天前的文档
Date date = new Date(System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000L);
SearchRequest searchRequest = new SearchRequest("my_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.rangeQuery("mtime").lte(date));
searchSourceBuilder.size(1000);
searchSourceBuilder.sort(SortBuilders.fieldSort("_doc").order(SortOrder.ASC));
searchRequest.source(searchSourceBuilder);
// 执行搜索请求,获取结果
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 遍历结果,逐个删除
for (SearchHit hit : searchResponse.getHits().getHits()) {
DeleteRequest deleteRequest = new DeleteRequest("my_index", hit.getId());
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println("Deleted document " + hit.getId() + ", status: " + deleteResponse.status());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
```
这里使用了Java API连接到ES服务器,并执行了一次搜索请求,然后遍历搜索结果,逐个删除符合条件的文档。定时任务每24小时运行一次。
阅读全文