一、项目描述
1.1、两个工程分别为:
one_prj和two_prj
1.2、通过openFeign工程one_prj调用two_prj
1.3、two_prj项目中的twoService接口的代码为
1.4、在idea中启动两个two_prj项目,分别代表两个区域(bj:beijing,sh:shanghai)
二、项目编写
2.1、启动两个two_prj项目
创建两个application.yml文件,分别为application-bj.yml,application-sh.yml,添加cluster-name配置并修改端口号
即:
2.2、配置启项
添加两个springboot启动项目,并修改其中的配置,点击确定
2.3、分别启动两个项目
2.4、nacos控制台显示如下:
点击详情显示如下:
2.4、修改one-prj项目里的application.yml文 件(本文 将配置写到了bootstrap.yml中了,两个文件都可以,只是加载先后不一样),这里配置的是bj(beijing)
2.5、one_prj项目中创建路由
MyLoadBanlancerRule.java代码如下
public class MyLoadBalancerRule implements ReactorServiceInstanceLoadBalancer {
private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSuppliers;
public MyLoadBalancerRule(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSuppliers){
this.serviceInstanceListSuppliers = serviceInstanceListSuppliers;
}
@Override
public Mono<Response<ServiceInstance>> choose(Request request) {
ServiceInstanceListSupplier ifAvailable = serviceInstanceListSuppliers.getIfAvailable();
return ifAvailable.get().next().map(this::getInstanceResponse);
}
@Autowired
NacosDiscoveryProperties nacosDiscoveryProperties;
private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances){
//拿到我当前服务的cluster-name
String myClusterName = nacosDiscoveryProperties.getClusterName();
ServiceInstance serviceInstance = null;
for(int i =0;i<instances.size();i++){
serviceInstance = instances.get(i);
String instanceClusterName = serviceInstance.getMetadata().get("nacos.cluster");
if(myClusterName.equals(instanceClusterName)){
break;
}
}
return new DefaultResponse(serviceInstance);
}
MyRule.java代码如下:
@Configuration
public class MyRule {
@Bean
public ReactorServiceInstanceLoadBalancer myLoadBalancerRule(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSuppliers){
return new MyLoadBalancerRule(serviceInstanceListSuppliers);
}
}
3.6、修改OnePrjApplication.java启动类
3、启动项目one_prj,在浏览器访问
连接点击多次
后台显示:TwoService-sh未被调用到,全被负载到了TwoService-bj中