一、负载均衡策略
1.导入依赖
要通过User调用Order,所以在User里做处理,在User中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>4.1.0</version>
</dependency>
2.编写代码
首先创建Order集群,方便查看随机分配结果;其次,在User里编写负载均衡策略的配置,并在启动类通过注解将它应用到Order
public class LbConfig
{
@Bean
ReactiveLoadBalancer<ServiceInstance> getLb(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory)
{
String name=environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
//返回随机负载均衡方式
return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class),name);
}
}
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@LoadBalancerClient(value = "S99-ORDER",configuration = LbConfig.class)
public class S99UserApplication {
public static void main(String[] args) {
SpringApplication.run(S99UserApplication.class, args);
}
}
3.结果校验
在浏览器中输入127.0.0.1:19050/getUsers,刷新页面,会拿到不同的订单编号。
二、网关路由代理
1.导入依赖
新建一个网关项目GateWay,导入依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>4.1.0</version>
</dependency>
2.配置文件
![](https://i-blog.csdnimg.cn/direct/2770339e1b844f27ada1b6fb781f5540.png)
配置要通过网关的路由地址
![](https://i-blog.csdnimg.cn/direct/0bfc73b60ce843e18b950dc8d34d6697.png)
3.开启被发现注解
@SpringBootApplication
@EnableDiscoveryClient
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class, args);
}
}
4.查看结果
输入网关地址127.0.0.1:8888/getUsers查看
三、错误排查
1.解决RestTemplate的No instances available for localhost错误
既然是负载均衡,那必然是多台服务器的负载均衡,用IP访问就没有意义了,因此用负载均衡的注解时,不能用IP或者localhost,而应该用服务名。