ILM.java 2.48 KB
package com.viontech.match.runner;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Time;
import co.elastic.clients.elasticsearch.ilm.*;
import co.elastic.clients.elasticsearch.ilm.get_lifecycle.Lifecycle;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration;
import org.springframework.boot.autoconfigure.context.LifecycleProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Author: inggg
 * Date: 2022/05/26 16:53
 */
@Component
@Slf4j
public class ILM implements CommandLineRunner {

    /**
     * 生命周期名字
     */
    public final static String LIFECYCLE_NAME = "delete-pool-after-days";

    @Value("${delete.after.days:5}")
    private Integer deleteAfterDays;

    @Autowired
    private ElasticsearchClient client;

    @Override
    public void run(String... args) throws Exception {
        try {
            Actions hotAction = new Actions.Builder()
                    .setPriority(p -> p.priority(100))
                    .build();
            Actions deleteAction = new Actions.Builder().delete(s -> s.deleteSearchableSnapshot(true)).build();
            IlmPolicy ilmPolicy = new IlmPolicy.Builder()
                    .phases(new Phases.Builder()
                            .hot(new Phase.Builder().actions(hotAction).minAge(Time.of(t -> t.time("0ms"))).build())
                            .delete(new Phase.Builder().actions(deleteAction).minAge(Time.of(t -> t.time(deleteAfterDays + "d"))).build())
                            .build())
                    .build();
            PutLifecycleRequest request = new PutLifecycleRequest.Builder().name(LIFECYCLE_NAME).policy(ilmPolicy).build();
            PutLifecycleResponse response = client.ilm().putLifecycle(request);
            GetLifecycleResponse getResponse = client.ilm().getLifecycle(new GetLifecycleRequest.Builder().name(LIFECYCLE_NAME).build());
            if (getResponse.get(LIFECYCLE_NAME) != null) {
                log.info(LIFECYCLE_NAME + "生命周期创建完成");
            }
        } catch (Exception e) {
            log.error("生命周期创建异常", e);
        }
    }
}