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

在上篇文章Spring Cloud构建微服务之服务注册与发现(一)介绍了如何使用Netflix的Eureka服务来构建服务注册中心与服务提供者,在本文中将介绍使用LoadBalanceClient来去消费注册到注册中心的服务提供者提供的接口。

使用LoadBalanceClient

在spring cloud提供了提供了有个服务治理的高度抽象接口,例如DiscoveryClient,LoadBalanceClient等。我们直接可以使用LoadBalanceClient,Spring Cloud提供的负载均衡客户端接口来实现服务的消费,关于如何使用,请看下面的例子。

  • 1 在Services工程下新建一个Module,名称为loadbalance-client-customer,pom.xml如下:


    
        services
        spring-cloud-demos
        1.0-SNAPSHOT
    
    4.0.0
    使用loadBalance Client 去消费 服务提供者提供的服务

    loadbalance-client-customer

    
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        

        
            com.fasterxml.jackson.core
            jackson-databind
            2.8.9
        

        
            org.springframework.boot
            spring-boot-starter-web
            1.5.7.RELEASE
        
    

这里特别指定了jackson-databind的依赖的版本,原因是因为:如果不指定版本会报如下的NoClassDefFoundError异常

Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.fasterxml.jackson.databind.SerializationConfig
    at com.fasterxml.jackson.databind.ObjectMapper.(ObjectMapper.java:560) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ObjectMapper.(ObjectMapper.java:476) ~[jackson-databind-2.8.10.jar:2.8.10]
    at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:588) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.(MappingJackson2HttpMessageConverter.java:57) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.(AllEncompassingFormHttpMessageConverter.java:61) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.HttpPutFormContentFilter.(HttpPutFormContentFilter.java:63) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter.(OrderedHttpPutFormContentFilter.java:29) ~[spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.httpPutFormContentFilter(WebMvcAutoConfiguration.java:149) ~[spring-boot-autoconfigure-1.5.7.RELEASE.jar:1.5.7.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$$EnhancerBySpringCGLIB$$b70dbbdb.CGLIB$httpPutFormContentFilter$1() ~[spring-boot-autoconfigure-1.5.7.RELEASE.jar:1.5.7.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$$EnhancerBySpringCGLIB$$b70dbbdb$$FastClassBySpringCGLIB$$d99e4f65.invoke() ~[spring-boot-autoconfigure-1.5.7.RELEASE.jar:1.5.7.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$$EnhancerBySpringCGLIB$$b70dbbdb.httpPutFormContentFilter() ~[spring-boot-autoconfigure-1.5.7.RELEASE.jar:1.5.7.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    ... 27 common frames omitted

  • 2创建启动主类
    创建LoadBalanceClient消费主类
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.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class CustomerByLoadBalanceClientApp {
    public static void main(String[] args){
        SpringApplication.run(CustomerByLoadBalanceClientApp.class,args);
    }
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  • 3 创建消费微服务的Controller
    在Module下创建controller包,然后创建Controller接口去消费微服务提供的微服务
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.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
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 LoadBalanceController {

    Logger logger = LoggerFactory.getLogger(LoadBalanceController.class);

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    RestTemplate restTemplate;
    /**
     * 消费服务提供者1 提供的getUserInfo接口
     * @param userName
     * @return
     */
    @GetMapping("/customer/loadbalancerclient/getUserInfo")
    public String getInfoFrom(@RequestParam String userName){
        logger.info("接收到请求---Load Balance Client 消费");
        ServiceInstance instance = loadBalancerClient.choose("biz-provider-service1");
        logger.info("处理请求的服务提供者的主机名:" + instance.getHost() + "--端口:" + instance.getPort());

        return restTemplate.postForObject("http://"+instance.getHost()+":"+instance.getPort()+"/getUserInfo",userName,String.class);
    }
}

在Controller中我们注入了LoadBalanceClient对象,在接口被调用的时候由LoadBalanceClient通过choose方法动态计算负载选择一个指定名称的微服务提供者实例ServiceInstance。通过log我们输出被选择的serviceInstance的主机和端口。然后通过RestTemplate调用对应的服务提供者接口。

  • 4 配置项目properties
spring:
  application:
    name: loadbalance-customer-serice
server:
  port: 9001
eureka:
  instance:
    prefer-ip-address: true
  client:
    serviceUrl:
      defaultZone: http://localhost:8762/eureka/

services:
  urls:
    userInfoUrl: http://biz-provider-service1/
  • 5 启动项目在浏览器中访问:http://localhost:9001/customer/loadbalancerclient/getUserInfo?userName=snow
    在控制台我们可以看到如下日志:
2018-07-01 15:45:12.535  INFO 13256 --- [nio-9001-exec-1] c.s.s.c.c.c.LoadBalanceController        : 处理请求的服务提供者的主机名:192.168.43.27--端口:8802
2018-07-01 15:45:13.455  INFO 13256 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: biz-provider-service1.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-07-01 15:50:00.097  INFO 13256 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2018-07-01 15:50:00.552  INFO 13256 --- [nio-9001-exec-6] c.s.s.c.c.c.LoadBalanceController        : 接收到请求---Load Balance Client 消费
2018-07-01 15:50:00.553  INFO 13256 --- [nio-9001-exec-6] c.s.s.c.c.c.LoadBalanceController        : 处理请求的服务提供者的主机名:192.168.43.27--端口:8801

从日志分析,LoadBalanceClient均衡的选择注册的两个节点8801和8802来处理请求去消费微服务提供的接口,通过restTemplate访问微服务。从下面的浏览器显示内容,可以验证,我们的请求到达微服务并正确返回:

hello snowfrom provider service1

至此通过LoadBalanceClient消费微服务提供的接口演示完毕,文章中所有的实例代码均可以在下面的连接上获取参考。谢谢。
码市:spring-cloud-demos

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