1、provider
?
?
?
?
?
?
?
?
2、?手寫LoadBalancer
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
3、實(shí)例
? ? ? ? ? ? ? ?1)、provider2004
?
?
?
?
?
?
?
? ? ? ?2)、consumer2018? ??手寫LoadBalancer? ?
?
? ? ? ? ?i)、pom.xml
? ? ? ? ?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
? ? ???ii)、application.properties
? ? ? #?應(yīng)用名稱
spring.application.name=consumer2018
#?應(yīng)用服務(wù)?WEB?訪問端口
server.port=2018
#?Nacos幫助文檔:?https://nacos.io/zh-cn/docs/concepts.html
#?Nacos認(rèn)證信息
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
#?Nacos?服務(wù)發(fā)現(xiàn)與注冊配置,其中子屬性?server-addr?指定?Nacos?服務(wù)器主機(jī)和端口
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#?注冊到?nacos?的指定?namespace,默認(rèn)為?public
spring.cloud.nacos.discovery.namespace=public
? ? ? ?iii)、LoadBalancer?
public interface LoadBalancer {
ServiceInstance getSingleAddres(List<ServiceInstance> serviceInstances);
}
?
? ? ? ?iiii)、RotationLoadBalancer?
@Component
public class RotationLoadBalancer implements LoadBalancer{
private AtomicInteger atomicInteger=new AtomicInteger(0);
@Override
public ServiceInstance getSingleAddres(List<ServiceInstance> serviceInstances) {
int index=atomicInteger.incrementAndGet()%serviceInstances.size();
return serviceInstances.get(index);
}
}
?
? ? ? ? iiiii)、Consumer2018Application?
?
@SpringBootApplication
public class Consumer2018Application {
public static void main(String[] args) {
SpringApplication.run(Consumer2018Application.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
?
? ? ???iiiiii)、OrderService
? ? ?
@RestController
public class OrderService {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancer loadBalancer;
@RequestMapping("/orderToMember")
public String orderToMember(){
List<ServiceInstance> instances=discoveryClient.getInstances("provider2004");
ServiceInstance serviceInstance=instances.get(0);
String rpcMemberUrl2=serviceInstance.getUri().toString();
String result2=restTemplate.getForObject(rpcMemberUrl2+"/hello/123131321312",String.class);
String rpcMemberUrl=loadBalancer.getSingleAddres(instances).getUri().toString();
String result=restTemplate.getForObject(rpcMemberUrl+"/hello/123131321312",String.class);
return "調(diào)用provider2004 返回結(jié)果:"+result;
}
}
?
?
?
?
本文摘自 :https://blog.51cto.com/s