feature:add User-Agent:polaris for healthyCheck api. (#872)

Co-authored-by: lingxiao.wu <51630311+lingxiao-wu@users.noreply.github.com>
pull/877/head
Haotian Zhang 2 years ago committed by GitHub
parent 6768e94c2f
commit 6998c32035
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,3 +10,4 @@
- [feat:enable stat reporting as default.](https://github.com/Tencent/spring-cloud-tencent/pull/863) - [feat:enable stat reporting as default.](https://github.com/Tencent/spring-cloud-tencent/pull/863)
- [refactor:update to junit 5.](https://github.com/Tencent/spring-cloud-tencent/pull/866) - [refactor:update to junit 5.](https://github.com/Tencent/spring-cloud-tencent/pull/866)
- [docs:support auto snapshot release in GitHub Action.](https://github.com/Tencent/spring-cloud-tencent/pull/871) - [docs:support auto snapshot release in GitHub Action.](https://github.com/Tencent/spring-cloud-tencent/pull/871)
- [feature:add User-Agent:polaris for healthyCheck api.](https://github.com/Tencent/spring-cloud-tencent/pull/872)

@ -18,6 +18,8 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@ -45,6 +47,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.http.HttpHeaders;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;
@ -224,7 +227,9 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
String healthCheckUrl = String.format("http://%s:%s%s", heartbeatRequest.getHost(), String healthCheckUrl = String.format("http://%s:%s%s", heartbeatRequest.getHost(),
heartbeatRequest.getPort(), healthCheckEndpoint); heartbeatRequest.getPort(), healthCheckEndpoint);
if (!OkHttpUtil.get(healthCheckUrl, null)) { Map<String, String> headers = new HashMap<>(1);
headers.put(HttpHeaders.USER_AGENT, "polaris");
if (!OkHttpUtil.get(healthCheckUrl, headers)) {
LOGGER.error("backend service health check failed. health check endpoint = {}", LOGGER.error("backend service health check failed. health check endpoint = {}",
healthCheckEndpoint); healthCheckEndpoint);
return; return;

@ -27,6 +27,9 @@ import java.util.concurrent.TimeUnit;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/** /**
* okhttp util. * okhttp util.
* *
@ -58,6 +61,9 @@ public final class OkHttpUtil {
conn.setRequestMethod("GET"); conn.setRequestMethod("GET");
conn.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(2)); conn.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(2));
conn.setReadTimeout((int) TimeUnit.SECONDS.toMillis(2)); conn.setReadTimeout((int) TimeUnit.SECONDS.toMillis(2));
if (!CollectionUtils.isEmpty(headers)) {
headers.forEach(conn::setRequestProperty);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
String str; String str;
@ -65,7 +71,7 @@ public final class OkHttpUtil {
buffer.append(str); buffer.append(str);
} }
String responseBody = buffer.toString(); String responseBody = buffer.toString();
if (conn.getResponseCode() == 200 && !responseBody.isBlank()) { if (conn.getResponseCode() == 200 && StringUtils.hasText(responseBody)) {
LOGGER.debug("exec get request, url: {} success, response data: {}", url, responseBody); LOGGER.debug("exec get request, url: {} success, response data: {}", url, responseBody);
return true; return true;
} }

@ -61,6 +61,19 @@ public class PolarisServiceRegistryTest {
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) .withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx"); .withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
private final WebApplicationContextRunner contextRunner2 = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisDiscoveryAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx")
.withPropertyValues("spring.cloud.polaris.discovery.health-check-url=/test");
@BeforeAll @BeforeAll
static void beforeAll() throws Exception { static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
@ -111,6 +124,23 @@ public class PolarisServiceRegistryTest {
}); });
} }
@Test
void testHeartbeat() {
this.contextRunner2.run(context -> {
PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class);
PolarisRegistration registration = Mockito.mock(PolarisRegistration.class);
when(registration.getHost()).thenReturn("127.0.0.1");
when(registration.getPort()).thenReturn(8080);
when(registration.getServiceId()).thenReturn(SERVICE_PROVIDER);
assertThatCode(() -> registry.register(registration)).doesNotThrowAnyException();
Thread.sleep(6000);
assertThatCode(() -> registry.deregister(registration)).doesNotThrowAnyException();
});
}
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
static class PolarisPropertiesConfiguration { static class PolarisPropertiesConfiguration {

@ -26,6 +26,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -53,8 +54,8 @@ public class OkHttpUtilTest {
@RestController @RestController
static class TestApplication { static class TestApplication {
@GetMapping("/test") @GetMapping("/test")
public String test() { public String test(@RequestHeader("key") String key) {
return "test"; return key;
} }
} }
} }

Loading…
Cancel
Save