实现自己的DiscoveryClient
需要做的:
DiscoveryClient能提供那些服务的服务名列表
返回指定服务对于的ServiceInstance列表
返回DiscoveryClient的顺序
返回HealthIndicator里显示的描述
实现LoadBalanceClient
实现自己的ServiceList<T extends Server>
Ribbon提供了AbstractServerList<T extends Server>
提供一个配置类,声明ServerListBean 实例
pom引入
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
- </dependency>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-dependencies</artifactId>
- <version>${spring-cloud.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
bootstartp.properties
- spring.application.name=name-service
application.yaml
- server:
- port:
- #需要连接的服务
- conns:
- services:
- - localhost:
DiscoveryClient服务列表
- import lombok.Setter;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.cloud.client.DefaultServiceInstance;
- import org.springframework.cloud.client.ServiceInstance;
- import org.springframework.cloud.client.discovery.DiscoveryClient;
- import java.util.Collections;
- import java.util.List;
- import java.util.stream.Collectors;
- @ConfigurationProperties(prefix = "conns")
- @Setter
- @Slf4j
- public class MyDiscoveryClient implements DiscoveryClient {
- public static final String SERVICE_ID = "conn-service";
- // waiter.services
- private List<String> services;
- @Override
- public String description() {
- return "DiscoveryClient that uses service.list from application.yml.";
- }
- @Override
- public List<ServiceInstance> getInstances(String serviceId) {
- if (!SERVICE_ID.equalsIgnoreCase(serviceId)) {
- return Collections.emptyList();
- }
- // 这里忽略了很多边界条件判断,认为就是 HOST:PORT 形式
- return services.stream()
- .map(s -> new DefaultServiceInstance(s,
- SERVICE_ID,
- s.split(":")[],
- Integer.parseInt(s.split(":")[]),
- false)).collect(Collectors.toList());
- }
- @Override
- public List<String> getServices() {
- return Collections.singletonList(SERVICE_ID);
- }
- }
- ServerList
- import java.util.List;
- import java.util.stream.Collectors;
- public class MyServerList implements ServerList<Server> {
- @Autowired
- private MyDiscoveryClient discoveryClient;
- @Override
- public List<Server> getInitialListOfServers() {
- return getServers();
- }
- @Override
- public List<Server> getUpdatedListOfServers() {
- return getServers();
- }
- private List<Server> getServers() {
- return discoveryClient.getInstances(MyDiscoveryClient.SERVICE_ID).stream()
- .map(i -> new Server(i.getHost(), i.getPort()))
- .collect(Collectors.toList());
- }
- }
开启:@EnableDiscoveryClient //注册中心注册服务
注入bean
- @Bean
- public DiscoveryClient myDiscovery(){
- return new MyDiscoveryClient();
- }
- @Bean
- public MyServerList myServerList() {
- return new MyServerList();
- }
- @Bean
- public HttpComponentsClientHttpRequestFactory requestFactory() {
- PoolingHttpClientConnectionManager connectionManager =
- new PoolingHttpClientConnectionManager(, TimeUnit.SECONDS);
- connectionManager.setMaxTotal();
- connectionManager.setDefaultMaxPerRoute();
- CloseableHttpClient httpClient = HttpClients.custom()
- .setConnectionManager(connectionManager)
- .evictIdleConnections(, TimeUnit.SECONDS)
- .disableAutomaticRetries()
- // 有 Keep-Alive 认里面的值,没有的话永久有效
- //.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
- // 换成自定义的
- .setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy())
- .build();
- HttpComponentsClientHttpRequestFactory requestFactory =
- new HttpComponentsClientHttpRequestFactory(httpClient);
- return requestFactory;
- }
- @LoadBalanced
- @Bean
- public RestTemplate restTemplate(RestTemplateBuilder builder) {
- return builder
- .setConnectTimeout(Duration.ofMillis())
- .setReadTimeout(Duration.ofMillis())
- .requestFactory(this::requestFactory)
- .build();
- }
- import org.apache.commons.lang3.StringUtils;
- import org.apache.commons.lang3.math.NumberUtils;
- import org.apache.http.HttpResponse;
- import org.apache.http.conn.ConnectionKeepAliveStrategy;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.protocol.HttpContext;
- import java.util.Arrays;
- public class CustomConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
- private final long DEFAULT_SECONDS = ;
- @Override
- public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
- return Arrays.asList(response.getHeaders(HTTP.CONN_KEEP_ALIVE))
- .stream()
- .filter(h -> StringUtils.equalsIgnoreCase(h.getName(), "timeout")
- && StringUtils.isNumeric(h.getValue()))
- .findFirst()
- .map(h -> NumberUtils.toLong(h.getValue(), DEFAULT_SECONDS))
- .orElse(DEFAULT_SECONDS) * ;
- }
- }
开启localhost:8088服务
测试:
- import com.example.discovery.model.TechnologyType;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.ApplicationArguments;
- import org.springframework.boot.ApplicationRunner;
- import org.springframework.core.ParameterizedTypeReference;
- import org.springframework.http.HttpMethod;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Component;
- import org.springframework.web.client.RestTemplate;
- import java.util.List;
- @Component
- @Slf4j
- public class CustomerRunner implements ApplicationRunner {
- @Autowired
- private RestTemplate restTemplate;
- @Override
- public void run(ApplicationArguments args) throws Exception {
- showServiceInstances();
- }
- private void showServiceInstances() {
- ParameterizedTypeReference<List<TechnologyType>> ptr =
- new ParameterizedTypeReference<List<TechnologyType>>() {};
- ResponseEntity<List<TechnologyType>> list = restTemplate
- .exchange("http://waiter-service/tech/", HttpMethod.GET, null, ptr);
- list.getBody().forEach(t -> log.info("technology: {}", t));
- }
- }
运行结果
- TechnologyType{techTypeId='', techTypeName='先进医疗/康复设备', techTypeDesc='', techCreateDate=Wed Sep :: CST }
- TechnologyType{techTypeId='', techTypeName='大数据', techTypeDesc='null', techCreateDate=Thu Aug :: CST }
实现自己的DiscoveryClient的更多相关文章
- SpringCloud学习之DiscoveryClient探究
当我们使用@DiscoveryClient注解的时候,会不会有如下疑问:它为什么会进行注册服务的操作,它不是应该用作服务发现的吗?下面我们就来深入的来探究一下其源码. 一.Springframewor ...
- springcloud-3:required a bean of type 'com.netflix.discovery.DiscoveryClient' that could not be found.
在写客户端程序的时候,总是报'com.netflix.discovery.DiscoveryClient' that could not be found. 原因在于导入了错误的类:com.netfl ...
- SpringCloud报错: "Field discoveryClient in com.controller.DcController required a bean of type 'com.netflix.discovery.DiscoveryClient' that could not be found."
SpringCloud报错: "Field discoveryClient in com.controller.DcController required a bean of type 'c ...
- spring eureka required a bean of type 'com.netflix.discovery.DiscoveryClient' that could not be found.
spring在集成第三方过程很容易出现类名相同,且基本作用相同的类.这样给初学者带来一定的困惑. 导致用错类而出现以下问题. required a bean of type 'com.netflix. ...
- Spring Cloud之DiscoveryClient使用
主要修改zk order的代码: package com.toov5.api.controller; import java.util.List; import org.springframework ...
- 深入理解DiscoveryClient
Spring Cloud Commons 提供的抽象 最早的时候服务发现注册都是通过DiscoveryClient来实现的,随着版本变迁把DiscoveryClient服务注册抽离出来变成了Servi ...
- com.netflix.discovery.DiscoveryClient : Completed shut down of DiscoveryClient
启动报错:com.netflix.discovery.DiscoveryClient : Completed shut down of DiscoveryClient 解决方案: 添加web主件 ...
- client-go实战之五:DiscoveryClient
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- SpringCloud发现服务代码(EurekaClient,DiscoveryClient)
1.说明 本文介绍SpringCloud发现服务代码的开发, 通过使用EurekaClient,DiscoveryClient来发现注册中心的服务等, 从而可以自定义客户端对注册中心的高级用法. 2. ...
随机推荐
- js中基本数据类型与引用数据类型的本质区别
代码 /** * 基本数据类型:string, number, boolean, null, undefined. * * 说明: * 基本数据类型的变量是保存在栈内存中的,基本数据类型的值 * 直接 ...
- 基本SQL查询语句
使用Emp表和Dept表完成下列练习 Emp员工表 empno ename job Mgr Hiredate Sal Comm Deptno 员工号 员工姓名 工作 上级编号 受雇日期 薪金 佣金 部 ...
- ReactiveCocoa详解
最近看了大神的博客后,感觉该对ReactiveCocoa做一个了断了. 首先大致的对以下关于ReactiveCocoa内容做一个简单的总结,其他的后续更新 1.ReactiveCocoa的操作思想 2 ...
- vue修改Element的el-table样式
修改Element中的el-table样式,可以使用以下几种方法: 1. row-style 行的 style 的回调方法,也可以使用一个固定的 Object 为所有行设置一样的 Style. 2. ...
- 【技巧】Windows 10 1809无法接收1903解决方法
这都7月份了,Windows10 1903都升级的有一个月了,然而我的1809的系统一直找不到1903的更新. 虽说1903会有bug,但还是想体验一把.周围同事都更新了,心里还是痒痒的. 于是每天都 ...
- 【Kickstart】2018 Round (Practice ~ C)
Practice Round Problem A GBus count (9pt/15pt) (2019年1月14日,kickstart群每日一题) 题意:有一条笔直的大路,上面有城市编号从 1 开始 ...
- error: must use ‘class’ tag to refer to type ‘XXX’ in this scope
开发环境: Qt Creator 4.8.2 在写程序的时候,遇到了编译器报错 error: must use 'class' tag to refer to type 'XXX' in this s ...
- bzoj3123 [Sdoi2013]森林 树上主席树+启发式合并
题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=3123 题解 如果是静态的查询操作,那么就是直接树上主席树的板子. 但是我们现在有了一个连接两棵 ...
- 多组件共享-vuex
1.解决多个组件共享同一状态数据问题1)多个视图共享同一状态2)来自不同视图的触发事件需要变更同一状态文档API:https://vuex.vuejs.org/zh/api/ 2.组件与store连接 ...
- loadrunner 使用
loadrunner给我的感觉很强势吧,第一次接触被安装包吓到了,当时用的是win10安装11版本的,各种安装失败,印象很深刻,那时候全班二三十号人,搞环境搞了两天,后来无奈,重做系统换成win7的了 ...