consul自动下线不可用服务

3,175 阅读1分钟

主动kill进程 consul中显示不可用为状态

解决办法: 编写定时任务代码清除无效服务,当然用python 或者其他语言都可以,主要是发送http请求。关键代码如下

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() {
        //获取consul服务
        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();
            //节点服务
            strings.forEach(k -> {
                //获取服务状态接口若状态为critica,则状态为503 restTemplate会抛出异常
                //So 此处使用okhttp发送请求
                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为服务不可用状态 则去掉
                        if ("critical".equals(aggregatedStatus)) {
                            restTemplate.put("http://127.0.0.1:8500/v1/agent/service/deregister/" + k, null, new HashMap<>());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}