當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringCloud Consul自定义服务注册
生活随笔
收集整理的這篇文章主要介紹了
SpringCloud Consul自定义服务注册
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SpringCloud自定義consul服務注冊器,獲取特定的本地地址進行注冊,注銷的時候檢查并注銷其他無效實例
package com.mk.springcloud.config;import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.agent.model.NewService; import com.ecwid.consul.v1.health.HealthServicesRequest; import com.ecwid.consul.v1.health.model.Check; import com.ecwid.consul.v1.health.model.HealthService; import lombok.SneakyThrows; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; import org.springframework.cloud.consul.discovery.HeartbeatProperties; import org.springframework.cloud.consul.discovery.TtlScheduler; import org.springframework.cloud.consul.serviceregistry.ConsulRegistration; import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; import org.springframework.stereotype.Service;import java.net.Inet4Address; import java.util.*;@Service public class ConsulRegistry extends ConsulServiceRegistry {private ConsulDiscoveryProperties properties;private ConsulClient consulClient;@Value("${spring.application.name}")private String applicationName;public ConsulRegistry(ConsulClient client, ConsulDiscoveryProperties properties, @Autowired(required = false) TtlScheduler ttlScheduler, HeartbeatProperties heartbeatProperties) {super(client, properties, ttlScheduler, heartbeatProperties);this.properties = properties;this.consulClient = client;}@SneakyThrows@Overridepublic void register(ConsulRegistration reg) {//獲取服務器的ipString address = Inet4Address.getLocalHost().getHostAddress();NewService newService = reg.getService();newService.setAddress(address);newService.getCheck().setHttp("http://" + address + ":" + reg.getService().getPort() + properties.getHealthCheckPath());newService.setId(reg.getService().getName() + "-" + address + ":" + reg.getService().getPort() + "-" + UUID.randomUUID().toString().replace("-",""));super.register(reg);}@Overridepublic void deregister(ConsulRegistration reg) {super.deregister(reg);//查詢no pass的服務實例HealthServicesRequest request = HealthServicesRequest.newBuilder().setPassing(false).build();List<HealthService> services = consulClient.getHealthServices(applicationName, request).getValue();for (HealthService service : services) {for (Check check : service.getChecks()) {//注銷無效實例if (check.getStatus() != Check.CheckStatus.PASSING) {consulClient.agentServiceDeregister(check.getServiceId());}}}} }?
總結
以上是生活随笔為你收集整理的SpringCloud Consul自定义服务注册的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot shedlock
- 下一篇: 上市价 1199 元:三星 Buds L