之前在我们的订单服务
中,用来获取商品信息的接口逻辑如下
public Goods findGoodsById(Long id){
String service = "goods-service";
List<ServiceInstance> instances = discoveryClient.getInstances(service);
if (instances.isEmpty()){
return null;
}
String url = "http://" + instances.get(0).getHost()+":"+instances.get(0).getPort() + "/goods/" + id;
return restTemplate.getForObject(url,Goods.class);
}
也就是每次从服务中心
获取服务,然后使用instances.get(0)
,获取到第一个商品服务
取商品信息,这样的话就完全没有必要增加多台商品服务
的服务器了,因为根本没有使用到其他商品服务器
,为了充分利用资源,我们需要每次在请求商品服务器
的数据时,请求不同的服务器,达到压力分担,其实就是这节要说的负载均衡
。
SpringCloud
中负载均衡可以使用Ribbon
来实现,接下来,引入Ribbon
到我们的项目来达到负载均衡的目的。
首先,在订单服务
中,找到OrderApplication
,在``public RestTemplate restTemplate()````上面添加@LoadBalanced
启用负载均衡
package com.felix;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class OrderApplication {
@Bean
@LoadBalanced //启用负载均衡
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
然后,在请求商品信息也就是GoodsService
中,修改原来只获取第一个服务的逻辑
public Goods findGoodsById(Long id){
String service = "goods-service";
String url = "http://" + service + "/goods/" + id;
return restTemplate.getForObject(url,Goods.class);
}
你没有看错,不在是之前的使用DiscoveryClient
获取服务实体,然后使用服务实体的第一个去做网络请求了,而只需要使用现在的这种方式,其他的工作其实在引入@LoadBalanced注解
的时候,就已经解决了。
接下来,我们启动2台商品服务器
、1台订单服务器
、0或多台服务中心服务器
,为了表现出负载均衡的效果,我们修改goods
模块中的GoodsController
的log信息
public Goods findGoodsById(@PathVariable("id") Long id){
System.out.println("goods收到商品信息请求");
return goodsService.findGoodsById(id);
}
goods01
模块中的GoodsController
的log信息
public Goods findGoodsById(@PathVariable("id") Long id){
System.out.println("goods01收到商品信息请求");
return goodsService.findGoodsById(id);
}
本次请求实际上访问了两条商品信息(订单id为2的订单信息中有两个商品),但是
GoodsApplication
的日志信息中只请求了一次商品信息,另一次商品信息从哪里获取的呢?查看GoodsApplication01
这就没错了,因为做了负载均衡,默认开启了轮询的方式,所以每次请求都会访问下一个服务器,也就是达到了我们的负载均衡的目的。
以上内容转载请注明出处,同时也请大家不吝你的关注和下面的赞赏
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓