向consul註冊服務spring原始碼
阿新 • • 發佈:2018-12-04
consul註冊報錯 connectex: No connection could be made because the target machine actively refused it.
-
Get http://localhost:2000/actuator/health: dial tcp [::1]:2000: connectex: No connection could be made because the target machine actively refused it.
-
Copy Output
專案springboot 註冊向consul時,健康檢查失敗,可以看到上面的連線地址是 localhost:2000/actuator/health ,consul與微服務在不同主機上,就會出現以上錯誤.
原因是配置properties有問題,
配置如下
spring.application.name=XXX
server.port=9114
spring.cloud.consul.host=192.168.0.17
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.serviceName=service-XXX
解決方式:
1.配置hostname
spring.cloud.consul.discovery.hostname=192.168.0.240
2.配置健康檢查地址
spring.cloud.consul.discovery.healthCheckUrl=http://192.168.0.240:9113/actuator/health
以下是向consul註冊服務的spring原始碼,順序是從下自上
下面也附上具體的類的名稱方便找到方法進行檢視
7.傳送put 請求
//類名 com.ecwid.consul.transport.AbstractHttpTransport; //方法 public RawResponse makePutRequest(String url, String content) { /*content = {"ID":"oms-xt-plan-9114","Name":"service-oms-xt-plan","Tags":["secure\u003dfalse"],"Address":"localhost","Port":9114,"Check":{"Interval":"10s","HTTP":"http://192.168.0.240:9114/actuator/health"}} */ HttpPut httpPut = new HttpPut(url); //PUT http://192.168.0.17:8500/v1/agent/service/register?token= HTTP/1.1 httpPut.setEntity(new StringEntity(content, UTF_8)); return this.executeRequest(httpPut); }
//類名
com.ecwid.consul.v1.ConsulRawClient;
//方法
public RawResponse makePutRequest(String endpoint, String content, UrlParameters... urlParams) {
String url = this.prepareUrl(this.agentAddress + endpoint);
// http://192.168.0.17:8500/v1/agent/service/register
url = Utils.generateUrl(url, urlParams); //http://192.168.0.17:8500/v1/agent/service/register?token=
return this.httpTransport.makePutRequest(url, content);
}
6.傳送請求,到consul註冊
//類名
com.ecwid.consul.v1.agent.AgentConsulClient;
//方法
public Response<Void> agentServiceRegister(NewService newService, String token) {
UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;
String json = GsonFactory.getGson().toJson(newService);
/*{"ID":"oms-xt-plan-9114","Name":"service-oms-xt-plan","Tags":["secure\u003dfalse"],"Address":"localhost","Port":9114,"Check":{"Interval":"10s","HTTP":"http://192.168.0.240:9114/actuator/health"}}*/
RawResponse rawResponse = this.rawClient.makePutRequest("/v1/agent/service/register", json, new UrlParameters[]{tokenParam});
if (rawResponse.getStatusCode() == 200) {
return new Response((Object)null, rawResponse);
} else {
throw new OperationException(rawResponse);
}
}
5.請求註冊
//類名
org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration
//方法
public void start() {
if (!this.isEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("Discovery Lifecycle disabled. Not starting");
}
} else {
if (!this.running.get()) {
this.register(); //註冊
if (this.shouldRegisterManagement()) {
this.registerManagement();
}
this.context.publishEvent(new InstanceRegisteredEvent(this, this.getConfiguration()));
this.running.compareAndSet(false, true);
}
}
}
package com.ecwid.consul.v1.agent.model
public class NewService {
@SerializedName("ID")
private String id; //XXX-9114
@SerializedName("Name")
private String name; //service-XXX
@SerializedName("Tags")
private List<String> tags;
@SerializedName("Address")
private String address; //properties.getHostname()
@SerializedName("Port")
private Integer port;
@SerializedName("EnableTagOverride")
private Boolean enableTagOverride;
@SerializedName("Check")
private NewService.Check check;
@SerializedName("Checks")
private List<NewService.Check> checks;
....省略GetSet
}
4.寫入引數
//類名
org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration
//方法
public static ConsulAutoRegistration registration(AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ApplicationContext context, List<ConsulRegistrationCustomizer> registrationCustomizers, HeartbeatProperties heartbeatProperties) {
NewService service = new NewService();
String appName = getAppName(properties, context.getEnvironment());
service.setId(getInstanceId(properties, context));
if (!properties.isPreferAgentAddress()) {
service.setAddress(properties.getHostname());
}
service.setName(normalizeForDns(appName));
service.setTags(createTags(properties));
if (properties.getPort() != null) {
service.setPort(properties.getPort());
setCheck(service, autoServiceRegistrationProperties, properties, context, heartbeatProperties);
}
ConsulAutoRegistration registration = new ConsulAutoRegistration(service, autoServiceRegistrationProperties, properties, context, heartbeatProperties);
customize(registrationCustomizers, registration);
return registration;
}
3.開始註冊 傳入引數
//類名
org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistrationAutoConfiguration
//方法
@Bean
@ConditionalOnMissingBean
public ConsulAutoRegistration consulRegistration(AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ApplicationContext applicationContext, ObjectProvider<List<ConsulRegistrationCustomizer>> registrationCustomizers, HeartbeatProperties heartbeatProperties) {
return ConsulAutoRegistration.registration(autoServiceRegistrationProperties, properties, applicationContext, (List)registrationCustomizers.getIfAvailable(), heartbeatProperties);
}
2.通過properies寫入 hostname
//類名
org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties
//方法
public void setHostname(String hostname) {
this.hostname = hostname;
this.hostInfo.override = true;
}
1.註冊所有class
//類名
org.springframework.context.annotation.ConfigurationClassEnhancer
//方法
static {
CALLBACKS = new Callback[]{new ConfigurationClassEnhancer.BeanMethodInterceptor(), new ConfigurationClassEnhancer.BeanFactoryAwareMethodInterceptor(), NoOp.INSTANCE};
CALLBACK_FILTER = new ConfigurationClassEnhancer.ConditionalCallbackFilter(CALLBACKS); //遍歷
logger = LogFactory.getLog(ConfigurationClassEnhancer.class);
objenesis = new SpringObjenesis();
}