服务部署时,调用shutdown接口实例状态为Down,通过delete请求可以让注册中心即刻下线服务,减少服务部署时的请求异常情况。
package lewis.demo1.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lewis.demo1.common.utils.HttpUtils;
import lewis.demo1.common.utils.WebUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/instance")
public class InstanceController {
@Value("${spring.application.name}")
private String springApplicationName;
@Value("${eureka.client.service-url.defaultZone}")
private String eurekaClientServiceUrlDefaultZone;
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/offline")
@ResponseBody
public InstanceModel offline(){
InstanceModel model = new InstanceModel();
try {
List<String> offlineUrlList = getInstanceAddress(springApplicationName, "instanceId");
for (String offlineUrl:offlineUrlList) {
HttpUtils.doDelete(offlineUrl);
}
List<String> zuulNotifyUrlList = getInstanceAddress("ZUUL", "homePageUrl");
for (String zuulNotifyUrl:zuulNotifyUrlList) {
HttpUtils.doPost(zuulNotifyUrl);
}
model.setStatus("0000");
model.setMessage("服务下线成功");
model.setSuccess(true);
} catch (Exception e) {
model.setStatus("9999");
model.setMessage("服务下线失败");
model.setSuccess(false);
log.error(e.getMessage(), e);
}
model.setTimestamp(System.currentTimeMillis());
return model;
}
private List<String> getInstanceAddress(String springApplicationName, String urlType){
List<String> instanceAddressList = new ArrayList<>();
List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(springApplicationName);
try {
String host = WebUtils.getLinuxLocalIp();
log.debug("LOCAL IP:"+host);
log.debug(JSONObject.toJSONString(serviceInstanceList));
for (ServiceInstance serviceInstance : serviceInstanceList) {
JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(serviceInstance));
if (serviceInstance.getHost().equals(host)) {
String url = jsonObject.getJSONObject("instanceInfo").getString(urlType);
if ("instanceId".equalsIgnoreCase(urlType)) {
String[] defaultZones = eurekaClientServiceUrlDefaultZone.split(",");
for (String zone:defaultZones) {
instanceAddressList.add(zone + "apps/" + springApplicationName + "/" + url);
}
} else if ("homePageUrl".equalsIgnoreCase(urlType)) {
instanceAddressList.add(url + "actuator/shutdown");
}
}
}
} catch (Exception e){
log.error(e.getMessage(), e);
}
return instanceAddressList;
}
@Data
@NoArgsConstructor
class InstanceModel {
private String status;
private String message;
private boolean isSuccess;
private Long timestamp;
}
}