在上篇文章Spring Cloud構(gòu)建微服務(wù)之服務(wù)注冊(cè)與發(fā)現(xiàn)(一)介紹了如何使用Netflix的Eureka服務(wù)來構(gòu)建服務(wù)注冊(cè)中心與服務(wù)提供者,在本文中將介紹使用LoadBalanceClient來去消費(fèi)注冊(cè)到注冊(cè)中心的服務(wù)提供者提供的接口沐序。
使用LoadBalanceClient
在spring cloud提供了提供了有個(gè)服務(wù)治理的高度抽象接口,例如DiscoveryClient奴紧,LoadBalanceClient等黍氮。我們直接可以使用LoadBalanceClient沫浆,Spring Cloud提供的負(fù)載均衡客戶端接口來實(shí)現(xiàn)服務(wù)的消費(fèi)专执,關(guān)于如何使用本股,請(qǐng)看下面的例子拄显。
- 1 在Services工程下新建一個(gè)Module,名稱為loadbalance-client-customer棘街,pom.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>services</artifactId>
<groupId>spring-cloud-demos</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<name>使用loadBalance Client 去消費(fèi) 服務(wù)提供者提供的服務(wù)</name>
<artifactId>loadbalance-client-customer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.7.RELEASE</version>
</dependency>
</dependencies>
</project>
這里特別指定了jackson-databind的依賴的版本蹬碧,原因是因?yàn)椋喝绻恢付ò姹緯?huì)報(bào)如下的NoClassDefFoundError異常
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.fasterxml.jackson.databind.SerializationConfig
at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:560) ~[jackson-databind-2.8.10.jar:2.8.10]
at com.fasterxml.jackson.databind.ObjectMapper.<init>(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.<init>(MappingJackson2HttpMessageConverter.java:57) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.<init>(AllEncompassingFormHttpMessageConverter.java:61) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.filter.HttpPutFormContentFilter.<init>(HttpPutFormContentFilter.java:63) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter.<init>(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(<generated>) ~[spring-boot-autoconfigure-1.5.7.RELEASE.jar:1.5.7.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$$EnhancerBySpringCGLIB$$b70dbbdb$$FastClassBySpringCGLIB$$d99e4f65.invoke(<generated>) ~[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(<generated>) ~[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創(chuàng)建啟動(dòng)主類
創(chuàng)建LoadBalanceClient消費(fèi)主類
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 創(chuàng)建消費(fèi)微服務(wù)的Controller
在Module下創(chuàng)建controller包,然后創(chuàng)建Controller接口去消費(fèi)微服務(wù)提供的微服務(wù)
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;
/**
* 消費(fèi)者接口
*/
@RestController
public class LoadBalanceController {
Logger logger = LoggerFactory.getLogger(LoadBalanceController.class);
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
RestTemplate restTemplate;
/**
* 消費(fèi)服務(wù)提供者1 提供的getUserInfo接口
* @param userName
* @return
*/
@GetMapping("/customer/loadbalancerclient/getUserInfo")
public String getInfoFrom(@RequestParam String userName){
logger.info("接收到請(qǐng)求---Load Balance Client 消費(fèi)");
ServiceInstance instance = loadBalancerClient.choose("biz-provider-service1");
logger.info("處理請(qǐng)求的服務(wù)提供者的主機(jī)名:" + instance.getHost() + "--端口:" + instance.getPort());
return restTemplate.postForObject("http://"+instance.getHost()+":"+instance.getPort()+"/getUserInfo",userName,String.class);
}
}
在Controller中我們注入了LoadBalanceClient對(duì)象炒刁,在接口被調(diào)用的時(shí)候由LoadBalanceClient通過choose方法動(dòng)態(tài)計(jì)算負(fù)載選擇一個(gè)指定名稱的微服務(wù)提供者實(shí)例ServiceInstance恩沽。通過log我們輸出被選擇的serviceInstance的主機(jī)和端口。然后通過RestTemplate調(diào)用對(duì)應(yīng)的服務(wù)提供者接口翔始。
- 4 配置項(xiàng)目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 啟動(dòng)項(xiàng)目在瀏覽器中訪問:http://localhost:9001/customer/loadbalancerclient/getUserInfo?userName=snow
在控制臺(tái)我們可以看到如下日志:
2018-07-01 15:45:12.535 INFO 13256 --- [nio-9001-exec-1] c.s.s.c.c.c.LoadBalanceController : 處理請(qǐng)求的服務(wù)提供者的主機(jī)名: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 : 接收到請(qǐng)求---Load Balance Client 消費(fèi)
2018-07-01 15:50:00.553 INFO 13256 --- [nio-9001-exec-6] c.s.s.c.c.c.LoadBalanceController : 處理請(qǐng)求的服務(wù)提供者的主機(jī)名:192.168.43.27--端口:8801
從日志分析罗心,LoadBalanceClient均衡的選擇注冊(cè)的兩個(gè)節(jié)點(diǎn)8801和8802來處理請(qǐng)求去消費(fèi)微服務(wù)提供的接口,通過restTemplate訪問微服務(wù)城瞎。從下面的瀏覽器顯示內(nèi)容脖镀,可以驗(yàn)證弦蹂,我們的請(qǐng)求到達(dá)微服務(wù)并正確返回:
hello snowfrom provider service1
至此通過LoadBalanceClient消費(fèi)微服務(wù)提供的接口演示完畢翅溺,文章中所有的實(shí)例代碼均可以在下面的連接上獲取參考褪猛。謝謝严里。
碼市:spring-cloud-demos