Spring-Cloud系列 Ribbon(二)

什么是Ribbon

Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients.

????上述是官方文檔對Ribbon的解釋,意思是Ribbon是一個客戶端負(fù)載均衡器匙赞,它可以有效的控制HTTP和TCP客戶端的訪問会宪。上述一段話有個很關(guān)鍵的詞“客戶端負(fù)載均衡器”,我們常用的負(fù)載均衡模式就是nginx反向代理模式,這種模式我們是不知道服務(wù)究竟請求的是那臺機(jī)器的揩懒。這種負(fù)載均衡模式是服務(wù)端負(fù)載均衡。
而客戶端負(fù)載均衡就是在發(fā)起請求是有明確的目標(biāo)被辑,請求精確指向集群中的某臺機(jī)器燎悍。
</br>????Ribbon的負(fù)載均衡默認(rèn)是依靠Eureka來實(shí)現(xiàn)的,Ribbon通過Eureka客戶端定期拉取注冊服務(wù)盼理,通過客戶端的輪訓(xùn)谈山、隨機(jī)等算法來實(shí)現(xiàn)負(fù)載均衡。

快速開始

這個案例依賴Eureka-Server,請準(zhǔn)備好server服務(wù)宏怔。Eureka相關(guān)查看Spring-Cloud系列(一) Eureka

添加依賴

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.13.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Dalston.SR5</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

????看上面的依賴有些同學(xué)可能會奇怪,為什么沒有引入Ribbon依賴奏路,只引入了Eureka客戶端。下面我們來看一下Eureka客戶端的依賴關(guān)系圖就明白了举哟。


Eureka客戶端依賴

????從上圖中我們明顯可以看出來,Eureka客戶端的依賴是包含Ribbon依賴的思劳。所以我們不需要添加依賴。

代碼

初始化bean

/**
 * @LoadBalanced Ribbon整合注解妨猩,Rebbon本身依賴在EurekClient中存在潜叛。所以不需要繼續(xù)引入
 * Ribbon是客戶端負(fù)載均衡實(shí)現(xiàn)之一,具有輪訓(xùn),隨機(jī)等等多種算法壶硅。
 * @return
 */
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}

使用方式

@RestController
public class RibbonControlller {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/url")
    public String postUser() {
        return this.restTemplate.getForObject("http://eureka-client-one/url", String.class);
    }
}

application配置

server:
</br>??port: 8082
</br>spring:
</br>??application:

</br>????name: ribbon-one
</br>eureka:
</br>??instance:
</br>????prefer-ip-address: true
</br>????instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
</br>??client:
</br>????serviceUrl:
</br>??????defaultZone: http://user:Pass123456@localhost:8761/eureka

啟動效果

啟動效果

自定義RibbonClient

代碼自定義

定義配置

@Configuration
public class RibbonConfiguration {

    @Autowired
    private IClientConfig config;

    @Bean
    public IRule ribbonRule(IClientConfig config){
        return new RandomRule();
    }
}

The FooConfiguration has to be @Configuration but take care that it is not in a @ComponentScan for the main application context, otherwise it will be shared by all the @RibbonClients. If you use @ComponentScan (or @SpringBootApplication) you need to take steps to avoid it being included (for instance put it in a separate, non-overlapping package, or specify the packages to scan explicitly in the @ComponentScan).

注意Configuration類不能和主類平級威兜,也不能在主類的子包下,否則該配置會覆蓋本項(xiàng)目下所有的Ribben配置

代碼配置

配置注入

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "eureka-client-one",configuration = RibbonConfiguration.class)
public class RibbonApplication {

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

使用方式

@Autowired
private LoadBalancerClient loadBalancerClient;

@GetMapping("/test")
public String test() {
    ServiceInstance instance = this.loadBalancerClient.choose("eureka-client-one");
    return instance.toString();
}

可被重寫的其他配置

????上面的代碼配置我們改變了IRule配置,更多例子參考官方文檔庐椒。以下配置可以通過代碼修改:

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl
  • IRule ribbonRule: ZoneAvoidanceRule
  • IPing ribbonPing: NoOpPing
  • ServerList<Server> ribbonServerList: ConfigurationBasedServerList
  • ServerListFilter<Server> ribbonServerListFilter: ZonePreferenceServerListFilter
  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer
  • ServerListUpdater ribbonServerListUpdater: PollingServerListUpdater

配置文件自定義

配置文件

users:#即需要調(diào)用的應(yīng)用名
</br>??ribbon:
</br>????NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule

使用方式

@Autowired
private LoadBalancerClient loadBalancerClient;

@GetMapping("/test")
public String test() {
    ServiceInstance instance = this.loadBalancerClient.choose("eureka-client-one");
    return instance.toString();
}

注意椒舵!
</br>Ribbon的配置優(yōu)先級順序是 yml>javaConfig>default

其他配置選項(xiàng)

上面的配置文件我們改變IRule配置,更多例子參考官方文檔约谈。以下配置可以通過配置文件修改

  • NFLoadBalancerClassName: should implement ILoadBalancer
  • NFLoadBalancerRuleClassName: should implement IRule
  • NFLoadBalancerPingClassName: should implement IPing
  • NIWSServerListClassName: should implement ServerList
  • NIWSServerListFilterClassName should implement ServerListFilter

Ribbon的其他配置

Ribbon禁用Eureka

ribbon:
</br>??eureka:
</br>????enabled: false
</br>users:#即需要調(diào)用的應(yīng)用名
</br>??ribbon:
</br>????listOfServers: localhost:8080,localhost:8081 #服務(wù)IP List

延遲加載Ribbon

ribbon:
</br>??eager-load:
</br>????enabled: true
</br>????clients: client1, client2, client3

????本文參考Spring-Cloud-Ribbon笔宿,Ribbon延遲加載

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市棱诱,隨后出現(xiàn)的幾起案子泼橘,更是在濱河造成了極大的恐慌,老刑警劉巖迈勋,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件炬灭,死亡現(xiàn)場離奇詭異,居然都是意外死亡靡菇,警方通過查閱死者的電腦和手機(jī)重归,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來厦凤,“玉大人鼻吮,你說我怎么就攤上這事∮具耄” “怎么了狈网?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長笨腥。 經(jīng)常有香客問我拓哺,道長,這世上最難降的妖魔是什么脖母? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任士鸥,我火速辦了婚禮,結(jié)果婚禮上谆级,老公的妹妹穿的比我還像新娘烤礁。我一直安慰自己,他們只是感情好肥照,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布脚仔。 她就那樣靜靜地躺著,像睡著了一般舆绎。 火紅的嫁衣襯著肌膚如雪鲤脏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天吕朵,我揣著相機(jī)與錄音猎醇,去河邊找鬼。 笑死努溃,一個胖子當(dāng)著我的面吹牛硫嘶,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播梧税,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼沦疾,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了第队?” 一聲冷哼從身側(cè)響起哮塞,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎斥铺,沒想到半個月后彻桃,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡晾蜘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年邻眷,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片剔交。...
    茶點(diǎn)故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡肆饶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出岖常,到底是詐尸還是另有隱情驯镊,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站板惑,受9級特大地震影響橄镜,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜冯乘,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一洽胶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧裆馒,春花似錦姊氓、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至梗搅,卻和暖如春禾唁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背些膨。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工蟀俊, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人订雾。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓肢预,卻偏偏與公主長得像,于是被迫代替她去往敵國和親洼哎。 傳聞我的和親對象是個殘疾皇子烫映,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評論 2 355

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