Spring Cloud構(gòu)建微服務(wù)架構(gòu)之服務(wù)消費(fèi)(一)

在上篇文章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/
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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末迷帜,一起剝皮案震驚了整個(gè)濱河市火诸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件芥玉,死亡現(xiàn)場(chǎng)離奇詭異揽涮,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)零院,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門龄糊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來阿浓,“玉大人,你說我怎么就攤上這事。” “怎么了唱捣?”我有些...
    開封第一講書人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵巡社,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我燕耿,道長(zhǎng),這世上最難降的妖魔是什么胀瞪? 我笑而不...
    開封第一講書人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮窖剑,結(jié)果婚禮上跳昼,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般徽级。 火紅的嫁衣襯著肌膚如雪朴下。 梳的紋絲不亂的頭發(fā)上团滥,一...
    開封第一講書人閱讀 51,573評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音甲喝,去河邊找鬼诵冒。 笑死豹芯,一個(gè)胖子當(dāng)著我的面吹牛娩梨,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播企巢,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼再姑,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了绍填?” 一聲冷哼從身側(cè)響起卿闹,我...
    開封第一講書人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤奄容,失蹤者是張志新(化名)和其女友劉穎涣觉,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體员淫,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡合蔽,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了介返。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拴事。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖圣蝎,靈堂內(nèi)的尸體忽然破棺而出刃宵,到底是詐尸還是另有隱情,我是刑警寧澤徘公,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布牲证,位于F島的核電站,受9級(jí)特大地震影響关面,放射性物質(zhì)發(fā)生泄漏坦袍。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一等太、第九天 我趴在偏房一處隱蔽的房頂上張望捂齐。 院中可真熱鬧,春花似錦澈驼、人聲如沸辛燥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挎塌。三九已至,卻和暖如春内边,著一層夾襖步出監(jiān)牢的瞬間榴都,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工漠其, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留嘴高,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓和屎,卻偏偏與公主長(zhǎng)得像拴驮,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子柴信,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理套啤,服務(wù)發(fā)現(xiàn),斷路器随常,智...
    卡卡羅2017閱讀 134,657評(píng)論 18 139
  • 軟件是有生命的潜沦,你做出來的架構(gòu)決定了這個(gè)軟件它這一生是坎坷還是幸福萄涯。 本文不是講解如何使用Spring Cloud...
    Bobby0322閱讀 22,651評(píng)論 3 166
  • 微服務(wù)架構(gòu)模式的核心在于如何識(shí)別服務(wù)的邊界,設(shè)計(jì)出合理的微服務(wù)唆鸡。但如果要將微服務(wù)架構(gòu)運(yùn)用到生產(chǎn)項(xiàng)目上涝影,并且能夠發(fā)揮...
    程序員技術(shù)圈閱讀 2,783評(píng)論 10 27
  • 請(qǐng)大家把自己手放在紙上,在紙上畫自己的手印争占,在手掌中寫下你的名字燃逻,分別從左往右寫下這幾個(gè)問題的答案:1.你孩子的年...
    王翠英閱讀 181評(píng)論 0 0
  • 關(guān)于推薦序 再次打開本書閱讀,讓我對(duì)作者有了更深刻的了解燃乍,本書能夠有巨大的影響力唆樊,那是必然的宛琅,這是柯維花了三...
    楊慧玲閱讀 126評(píng)論 0 2