我们继续以之前博客的代码为基础,增加带组件来提供客户端负载均衡。负载均衡是实现高并发,高性能,可伸缩服务的重要组成部分,它可以把请求分散到一个集群中不同的服务器中,以减轻每个服务器的负担。客户端负载均衡是运行在客户端程序中的,如我们的web项目,然后通过获取集群的IP地址列表,随机选择一个服务器发送请求。相对于服务端负载均衡来说,它不需要消耗服务器的资源。
-
<李> JDK 1.8 李>
<李> Maven 3.3.9李>
<李> IntelliJ 2018.1 李>
Git:项目源码
我们这次需要在本地启动两个产品服务程序,用来验证负载均衡,所以需要为第二个程序提供不同的端口.Spring云配置服务中心的配置默认会覆盖本地系统环境变量,而我们需要通过系统环境变量来设置产品服务的端口,所以需要在配置中心git仓库中修改产品服务的配置文件product-service.yml
服务器: 端口:8081 春天: 云: 配置: allow-override:真 override-system-properties:假 >之前allow-override的默认值即为真实的,写出它来是想作说明,它的意思是允许远程配置中心的配置项覆盖本地的配置,并不是说允许本地的配置去覆盖远程的配置。当然我们可以把它设置成假的,但是为了提供更精确的覆盖规则,这里保留了默认值。
我们添加了override-system-properties=false,即虽然远程配置中心的配置文件可以覆盖本地的配置,但是不要覆盖本地系统变量。修改完成后提交到git仓库。
另外,在productService项目的ProductController中添加一些日志,用来验证负载均衡是否生效:
包cn.zxuqian.controllers; 进口org.slf4j.Logger; 进口org.slf4j.LoggerFactory; 进口org.springframework.web.bind.annotation.RequestMapping; 进口org.springframework.web.bind.annotation.RestController; @RestController 公开课ProductController { 私有静态日志记录器=LoggerFactory.getLogger (ProductController.class); @RequestMapping(“产品”) 公共字符串productList () { log.info(“访问/产品端点”); 返回“外套,夹克,毛衣、T恤”; } } >之前,为网络配置丝带
首先在pom.xml中添加丝带的依赖:
& lt; dependency> & lt; groupId> org.springframework.cloud & lt; artifactId> spring-cloud-starter-netflix-ribbon & lt;/dependency>然后修改应用程序类,添加如下代码:
@EnableCircuitBreaker @EnableDiscoveryClient @RibbonClient (name="产品服务”) @SpringBootApplication 公共类应用程序{ 公共静态void main (String [] args) { SpringApplication.run (Application.class, args); } @ bean @LoadBalanced 公共创建RestTemplate休息(RestTemplateBuilder builder) { 返回builder.build (); } },这里用到了@RibbonClient (name="产品服务")注解,用来标记此项目为带负载均衡的客户端,它需要选择产品服务集群中其中的一台来访问所需要的服务,这里的名字属性对应于productService项目中配置的spring.application.name属性。
@LoadBalanced注解标明了创建RestTemplate会被配置为自动使用丝带的LoadBalancerClient来选择服务的uri并发送请求。
在我们在ProductService类中添加如下代码:
@ service 公开课ProductService { 私人最终创建RestTemplate创建RestTemplate; @ autowired 私人DiscoveryClient DiscoveryClient; 公共ProductService(创建RestTemplate创建RestTemplate) { 这一点。创建restTemplate=创建restTemplate; } @HystrixCommand (fallbackMethod=癰ackupProductList”) 公共字符串productList () { List=this.discoveryClient.getInstances实例(产品服务); 如果实例!=零,,instances.size()比;0){ 返回this.restTemplate.getForObject (instances.get (0) .getUri() +“/产品”,String.class); } 返回"; } 公共字符串backupProductList () { 返回“夹克,毛衣”; } 公共字符串productListLoadBalanced () { this.restTemplate返回。String.class getForObject (“http://product-service/products”); } } 春云带实现客户端负载均衡的方法