Merge pull request #34 from pengkai242/main

增加服务实例自身健康检查
pull/41/head
Haotian Zhang 3 years ago committed by GitHub
commit f3763b0a45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,6 +1,6 @@
server:
session-timeout: 1800
port: 48081
port: 48084
spring:
application:
name: DiscoveryCalleeService

@ -59,4 +59,14 @@ public class DiscoveryCallerController {
return restTemplate.getForObject("http://DiscoveryCalleeService/discovery/service/callee/info", String.class);
}
/**
* health check
*
* @return
*/
@GetMapping("/healthCheck")
public String healthCheck() {
return "pk ok";
}
}

@ -7,6 +7,10 @@ spring:
cloud:
polaris:
address: grpc://127.0.0.1:8091
discovery:
heartbeat:
enabled: true
health-check-url: /discovery/service/caller/healthCheck
consul:
port: 8500
host: 127.0.0.1

@ -98,6 +98,12 @@ public class PolarisProperties {
@Value("${spring.cloud.polaris.discovery.heartbeat.enabled:#{false}}")
private Boolean heartbeatEnabled = true;
/**
* Custom health check url to override default
*/
@Value("${spring.cloud.polaris.discovery.health-check-url:}")
private String healthCheckUrl;
@Autowired
private Environment environment;
@ -212,6 +218,14 @@ public class PolarisProperties {
this.port = port;
}
public String getHealthCheckUrl() {
return healthCheckUrl;
}
public void setHealthCheckUrl(String healthCheckUrl) {
this.healthCheckUrl = healthCheckUrl;
}
@Override
@SuppressWarnings("checkstyle:all")
public String toString() {
@ -227,6 +241,7 @@ public class PolarisProperties {
", policy='" + policy + '\'' +
", registerEnabled=" + registerEnabled +
", heartbeatEnabled=" + heartbeatEnabled +
", healthCheckUrl=" + healthCheckUrl +
", environment=" + environment +
'}';
}

@ -21,6 +21,7 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;
import com.tencent.cloud.metadata.config.MetadataLocalProperties;
import com.tencent.cloud.polaris.PolarisProperties;
import com.tencent.cloud.polaris.util.OkHttpUtil;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.pojo.Instance;
@ -33,6 +34,7 @@ import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
@ -179,6 +181,12 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
@Override
public void run() {
try {
String healthCheckUrl = String.format("http://%s:%s%s", heartbeatRequest.getHost(), heartbeatRequest.getPort(), polarisProperties.getHealthCheckUrl());
//先判断是否配置了health-check-url如果配置了需要先进行服务实例健康检查如果健康检查通过则进行心跳上报如果不通过则不上报心跳
if (Strings.isNotEmpty(healthCheckUrl) && !OkHttpUtil.get(healthCheckUrl, null)){
log.error("polaris health check failed");
return;
}
polarisDiscoveryHandler.getProviderAPI().heartbeat(heartbeatRequest);
} catch (PolarisException e) {
log.error("polaris heartbeat[{}]", e.getCode(), e);

@ -0,0 +1,83 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.util;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Objects;
/**
* okhttp util.
*
* @author kan peng
*/
public class OkHttpUtil {
public final static Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
/**
* JSON format
*/
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
/**
* client
*/
private final static OkHttpClient HTTP_CLIENT = new OkHttpClient();
/**
* get request.
*
* @param url url
* @param headers headers
* @return response
*/
public static boolean get(String url, Map<String, String> headers) {
try {
Request.Builder builder = new Request.Builder();
buildHeader(builder, headers);
Request request = builder.url(url).build();
Response response = HTTP_CLIENT.newCall(request).execute();
if (response.isSuccessful() && Objects.nonNull(response.body())) {
String result = response.body().string();
logger.info("exec get request, url: {} successresponse data: {}", url, result);
return true;
}
} catch (Exception e) {
logger.error("exec get requesturl: {} failed!", url, e);
}
return false;
}
/**
* build header.
*
* @param builder builder
* @param headers headers
*/
private static void buildHeader(Request.Builder builder, Map<String, String> headers) {
if (Objects.nonNull(headers) && headers.size() > 0) {
headers.forEach((k, v) -> {
if (Objects.nonNull(k) && Objects.nonNull(v)) {
builder.addHeader(k, v);
}
});
}
}
}

@ -18,6 +18,12 @@
"defaultValue": true,
"description": "enable polaris discovery or not."
},
{
"name": "spring.cloud.polaris.discovery.health-check-url",
"type": "java.lang.String",
"defaultValue": "",
"description": "heal check url."
},
{
"name": "spring.cloud.polaris.discovery.instance-enabled",
"type": "java.lang.Boolean",

Loading…
Cancel
Save