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

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.indexlifecycle.DeleteAction;
import org.elasticsearch.client.indexlifecycle.LifecycleAction;
import org.elasticsearch.client.indexlifecycle.LifecyclePolicy;
import org.elasticsearch.client.indexlifecycle.Phase;
import org.elasticsearch.client.indexlifecycle.PutLifecyclePolicyRequest;
import org.elasticsearch.client.indexlifecycle.SetPriorityAction;
import org.elasticsearch.common.unit.TimeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
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 RestHighLevelClient restHighLevelClient;

    @Override
    public void run(String... args) throws Exception {
        try {
            Map<String, Phase> phases = new HashMap<>();
            Map<String, LifecycleAction> setPriorityAction = new HashMap<>();
            setPriorityAction.put(SetPriorityAction.NAME, new SetPriorityAction(100));
            phases.put("hot", new Phase("hot", TimeValue.ZERO, setPriorityAction));

            Map<String, LifecycleAction> deleteActions =
                    Collections.singletonMap(DeleteAction.NAME, new DeleteAction());
            phases.put("delete", new Phase("delete",
                    new TimeValue(deleteAfterDays, TimeUnit.DAYS), deleteActions));

            LifecyclePolicy policy = new LifecyclePolicy(LIFECYCLE_NAME, phases);
            PutLifecyclePolicyRequest lifecyclePolicyRequest = new PutLifecyclePolicyRequest(policy);
            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indexLifecycle().putLifecyclePolicy(lifecyclePolicyRequest, RequestOptions.DEFAULT);
            if (acknowledgedResponse.isAcknowledged()) {
                log.info(LIFECYCLE_NAME + "生命周期创建完成");
            }
        } catch (Exception e) {
            log.error("生命周期创建异常", e);
        }
    }
}