用JAVA写一个定时任务,定时清理es mtime 30天之前的数据 采用 delete_by_query
时间: 2023-07-16 07:16:52 浏览: 137
JAVA定时任务
可以使用 Quartz 定时任务框架来实现,以下是一个简单的示例代码:
首先引入相关依赖:
```xml
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.0.0</version>
</dependency>
```
然后定义一个 Job 类来执行清理操作:
```java
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.deletebyquery.DeleteByQueryRequest;
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
public class EsCleanJob implements Job {
private RestHighLevelClient esClient;
public EsCleanJob(RestHighLevelClient esClient) {
this.esClient = esClient;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("开始清理es数据...");
// 计算30天前的时间戳
LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
long timestamp = thirtyDaysAgo.toInstant(ZoneOffset.of("+8")).toEpochMilli();
// 构建 delete by query 请求
DeleteByQueryRequest request = new DeleteByQueryRequest("index_name");
request.setQuery(QueryBuilders.rangeQuery("mtime").lt(timestamp));
// 执行 delete by query 操作
try {
DeleteByQueryResponse response = esClient.deleteByQuery(request, RequestOptions.DEFAULT);
System.out.println("清理完成,删除 " + response.getDeleted() + " 条数据");
} catch (IOException e) {
throw new JobExecutionException("清理es数据失败", e);
}
}
}
```
最后在主函数中启动定时任务:
```java
import org.elasticsearch.client.RestHighLevelClient;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class EsCleanScheduler {
public static void main(String[] args) throws SchedulerException {
// 创建 es 客户端
RestHighLevelClient esClient = new RestHighLevelClient(/* es 配置 */);
// 创建 JobDetail 实例
JobDetail jobDetail = JobBuilder.newJob(EsCleanJob.class).withIdentity("esCleanJob").build();
// 创建 Trigger 实例
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("esCleanTrigger")
.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(86400)) // 每隔一天执行一次
.build();
// 创建 Scheduler 实例
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
}
}
```
这样就完成了定时清理 es 数据的任务。
阅读全文