Spring Cloud构建微服务架构之服务消费(二)

在上一篇Spring Cloud构建微服务架构之服务消费(一)中我们已经学会如何使用LoadBalanceClient去访问微服务提供的接口了。但是在使用的过程中我们发现,需要我们手动的去指定serviceInstance,并根据serviceInstance去拼接请求url,这对于我们开发者来说是非常不友好的。本节我将演示如何使用Spring Cloud Ribbon 负载均衡去消费微服务提供的服务接口。

使用Ribbon

  • 1在Services工程下新建新的Module工程,命名biz-customer-service
    pom.xml文件如下:


    
        services
        spring-cloud-demos
        1.0-SNAPSHOT
    
    4.0.0
    Spring cloud 案例 消费者

    biz-customer-service

    
        
            org.springframework.boot
            spring-boot-starter-web
            1.5.7.RELEASE
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
        
            org.springframework.cloud
            spring-cloud-starter-ribbon
        
    

    
        UTF-8
        1.8
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            repackage
                        
                    
                
            
        
    


在pom中引入spring-cloud-starter-ribbon依赖

  • 2创建主类
package com.snow.spring.cloud.customer;

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 BizCustomerServiceApp {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args){
        SpringApplication.run(BizCustomerServiceApp.class,args);
    }
}

对比上一篇文章的主类我们发现在RestTemplate上多了一个@LoadBalance注解,该注解指定RestTemplate可以通过客户端负载均衡来去请求微服务接口。

  • 3修改Bootstrap.yml
spring:
  application:
    name: biz-customer-serice
server:
  port: 9000
eureka:
  instance:
    prefer-ip-address: true
  client:
    serviceUrl:
      defaultZone: http://localhost:8762/eureka/

services:
  urls:
    userInfoUrl: http://biz-provider-service1/

修改消费者端口为9000

  • 4 增加消费者访问控制器CustomerController,在Controller包下新建类CustomerController
package com.snow.spring.cloud.customer.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class CustomerController extends RestTemplate{

    private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);


    @Value("${services.urls.userInfoUrl}")
    private String userInfoUrl;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestParam String userName){

        logger.info("userInfoUrl:" + userInfoUrl);
        return restTemplate.postForObject(userInfoUrl+"/getUserInfo",userName,String.class);
    }
}

对比上一小节Controller里移除了LoadBalanceClient选择ServiceInstance实例的相关逻辑,RestTemplate请求接口的拼接也简化了 ,而是由RestTemplate直接请求微服务的别名。那么这样的请求为什么可以调用成功呢?因为Spring Cloud Ribbon有一个拦截器,它能够在这里进行实际调用的时候,自动的去选取服务实例,并将实际要请求的IP地址和端口替换这里的服务名,从而完成服务接口的调用。

  • 5 启动项目在浏览器中访问http://localhost:9000/getUserInfo?userName=snow
    请求首先到达消费者的CustomerController的getUserInfo,然后又由RestTemplate调用postForObject请求微服务名下的getUserInfo接口,从而消费微服务提供的接口。多次刷新浏览器,发现请求分别会被均衡分发到8801端口和8802端口,也实现的负载均衡。
2018-07-02 11:10:14.939  INFO 11925 --- [nio-8802-exec-1] c.s.s.c.s.controller.UserInfoController  : request snow
2018-07-02 11:10:16.822  INFO 11918 --- [nio-8801-exec-8] c.s.s.c.s.controller.UserInfoController  : request snow

我们发现使用Ribbon能够比使用LoadBalanceClient更少的代码实现相同的功能,使我们的开发变得简单。

至此使用Ribbon消费微服务演示完毕,相关代码可以参考
码市:spring-cloud-demos
本人水平有限,写的不好,主要是为了记录自己对SpringCloud的学习之路。
感谢阅读。

你可能感兴趣的:(Spring Cloud构建微服务架构之服务消费(二))