Active kill process Consul displays unavailable status

Workaround: Write timed task code to remove invalid services, either in Python or another language, mainly by sending HTTP requests. The key code is as follows

import com.alibaba.fastjson.JSONObject;
import com.example.CloudDemoConsumerApplication;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
import java.util.Set;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = CloudDemoConsumerApplication.class)
public class TestService {

    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void test(a) {
        // Obtain Consul service
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://127.0.0.1:8500/v1/agent/services", String.class);
        if (forEntity.getStatusCode().is2xxSuccessful()) {
            String body = forEntity.getBody();
            if (StringUtils.isEmpty(body)) {
                return;
            }
            JSONObject jsonObject = JSONObject.parseObject(body);
            Set<String> strings = jsonObject.keySet();
            // Node service
            strings.forEach(k -> {
                // Interface for obtaining service status If the state is critica, it is 503, restTemplate throws an exception
                //So use okhttp here to send the request
                OkHttpClient okHttpClient = new OkHttpClient();
                final Request request = new Request.Builder()
                        .url("http://127.0.0.1:8500/v1/agent/health/service/id/" + k)
                        .build();
                try (Response response = okHttpClient.newCall(request).execute()) {
                    if (response.code() == 503) {
                        String string = Objects.requireNonNull(response.body()).string();
                        JSONObject object = JSONObject.parseObject(string);
                        String aggregatedStatus = object.getString("AggregatedStatus");
                        // Critical Indicates that the service is unavailable
                        if ("critical".equals(aggregatedStatus)) {
                            restTemplate.put("http://127.0.0.1:8500/v1/agent/service/deregister/" + k, null.newHashMap<>()); }}}catch(IOException e) { e.printStackTrace(); }}); }}}Copy the code