需要做的:
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: 8080
#需要连接的服务
conns:
services:
- localhost:8088
知识兔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(":")[0],
Integer.parseInt(s.split(":")[1]),
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()); }}