SpringCloud(第 013 篇)電影微服務(wù)使用定制化 Feign 在客戶端進(jìn)行負(fù)載均衡調(diào)度并為 Feign 配置帳號(hào)密碼登錄認(rèn)證 Eureka

SpringCloud(第 013 篇)電影微服務(wù)使用定制化 Feign 在客戶端進(jìn)行負(fù)載均衡調(diào)度并為 Feign 配置帳號(hào)密碼登錄認(rèn)證 Eureka

一擅耽、大致介紹

1岩遗、定制 Feign 實(shí)現(xiàn)訪問(wèn)遠(yuǎn)端微服務(wù)告私;
2馁龟、為 Feign 配置帳號(hào)密碼來(lái)登錄認(rèn)證 Eureka 服務(wù)發(fā)現(xiàn)模塊蹋盆;
3、修改 Feign 的日志打印級(jí)別后德;
4部宿、定制 Feign 也毫不掩飾的支持負(fù)載均衡調(diào)度功能;

二瓢湃、實(shí)現(xiàn)步驟

2.1 添加 maven 引用包

<?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">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springms-consumer-movie-feign-custom</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.springms.cloud</groupId>
        <artifactId>springms-spring-cloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        <!-- web模塊 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 客戶端發(fā)現(xiàn)模塊 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <!-- Java HTTP 客戶端開(kāi)發(fā)的工具的模塊 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>

</project>

2.2 添加應(yīng)用配置文件(springms-consumer-movie-feign-custom\src\main\resources\application.yml)

spring:
  application:
    name: springms-consumer-movie-feign-custom
server:
  port: 8050
eureka:
  client:
#    healthcheck:
#      enabled: true
    serviceUrl:
      defaultZone: http://admin:admin@localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}

logging:
  level:
    com.springms.cloud.feign.UserFeignCustomClient: DEBUG


# 解決第一次請(qǐng)求報(bào)超時(shí)異常的方案理张,因?yàn)?hystrix 的默認(rèn)超時(shí)時(shí)間是 1 秒,因此請(qǐng)求超過(guò)該時(shí)間后绵患,就會(huì)出現(xiàn)頁(yè)面超時(shí)顯示 :
#
# 這里就介紹大概三種方式來(lái)解決超時(shí)的問(wèn)題雾叭,解決方案如下:
#
# 第一種方式:將 hystrix 的超時(shí)時(shí)間設(shè)置成 5000 毫秒
# hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
#
# 或者:
# 第二種方式:將 hystrix 的超時(shí)時(shí)間直接禁用掉,這樣就沒(méi)有超時(shí)的一說(shuō)了落蝙,因?yàn)橛肋h(yuǎn)也不會(huì)超時(shí)了
# hystrix.command.default.execution.timeout.enabled: false
#
# 或者:
# 第三種方式:索性禁用feign的hystrix支持
feign.hystrix.enabled: false ## 索性禁用feign的hystrix支持

# 超時(shí)的issue:https://github.com/spring-cloud/spring-cloud-netflix/issues/768
# 超時(shí)的解決方案: http://stackoverflow.com/questions/27375557/hystrix-command-fails-with-timed-out-and-no-fallback-available
# hystrix配置: https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.thread.timeoutInMilliseconds

2.3 添加實(shí)體用戶類User(springms-consumer-movie-feign-custom\src\main\java\com\springms\cloud\entity\User.java)

package com.springms.cloud.entity;

import java.math.BigDecimal;

public class User {

    private Long id;

    private String username;

    private String name;

    private Short age;

    private BigDecimal balance;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Short getAge() {
        return this.age;
    }

    public void setAge(Short age) {
        this.age = age;
    }

    public BigDecimal getBalance() {
        return this.balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

}

2.4 添加訪問(wèn)遠(yuǎn)端服務(wù) Feign 客戶端(springms-consumer-movie-feign-custom\src\main\java\com\springms\cloud\feign\UserFeignCustomClient.java)

package com.springms.cloud.feign;

import com.springms.cloud.entity.User;
import com.springms.config.TestFeignCustomConfiguration;
import feign.Param;
import feign.RequestLine;
import org.springframework.cloud.netflix.feign.FeignClient;

/**
 * 用戶Http請(qǐng)求的客戶端织狐,F(xiàn)eignClient 注解地方采用了自定義的配置。
 *
 * 注解FeignClient的傳參:表示的是注冊(cè)到 Eureka 服務(wù)上的模塊名稱掘殴。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/9/19
 *
 */
@FeignClient(name = "springms-provider-user", configuration = TestFeignCustomConfiguration.class)
public interface UserFeignCustomClient {

    /**
     * 這里的注解 RequestLine、Param 是 Feign 的配置新的注解粟誓,詳細(xì)請(qǐng)參考鏈接:https://github.com/OpenFeign/feign
     *
     * @param id
     * @return
     */
    @RequestLine("GET /simple/{id}")
    public User findById(@Param("id") Long id);
}


/****************************************************************************************
 參考代碼如下:

    interface GitHub {
        @RequestLine("GET /repos/{owner}/{repo}/contributors")
        List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
    }

    static class Contributor {
        String login;
        int contributions;
    }

    public static void main(String... args) {
        GitHub github = Feign.builder().decoder(new GsonDecoder()).target(GitHub.class, "https://api.github.com");

        // Fetch and print a list of the contributors to this library.
        List<Contributor> contributors = github.contributors("OpenFeign", "feign");
        for (Contributor contributor : contributors) {
            System.out.println(contributor.login + " (" + contributor.contributions + ")");
        }
    }
 ****************************************************************************************/

2.5 添加登錄認(rèn)證Eureka服務(wù) Feign 客戶端(springms-consumer-movie-feign-custom\src\main\java\com\springms\cloud\feign\UserFeignCustomSecondClient.java)

package com.springms.cloud.feign;

import com.springms.config.TestEurekaAuthConfiguration;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 用戶Http請(qǐng)求的客戶端奏寨,F(xiàn)eignClient 注解地方采用了自定義的配置。
 *
 * 注解FeignClient的傳參:表示的是注冊(cè)到 Eureka 服務(wù)上的模塊名稱鹰服。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/9/19
 *
 */
@FeignClient(name = "xxx", url = "http://localhost:8761/", configuration = TestEurekaAuthConfiguration.class)
public interface UserFeignCustomSecondClient {

    @RequestMapping(value = "/eureka/apps/{serviceName}")
    public String findEurekaInfo(@PathVariable("serviceName") String serviceName);
}

2.6 添加訪問(wèn)遠(yuǎn)端服務(wù)配置類(springms-consumer-movie-feign-custom\src\main\java\com\springms\config\TestFeignCustomConfiguration.java)

package com.springms.config;

import feign.Contract;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自定義配置病瞳。
 *
 * 不和 com.springms.cloud 在同級(jí)目錄,因?yàn)槲臋n有說(shuō)明悲酷,該配置文件不需要被掃描到套菜。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/9/19
 *
 */
@Configuration
public class TestFeignCustomConfiguration {

    @Bean
    public Contract feignContract(){
        return new feign.Contract.Default();
    }

    /**
     * 日志級(jí)別配置
     *
     * @return
     */
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

2.7 添加登錄認(rèn)證Eureka服務(wù)配置(springms-consumer-movie-feign-custom\src\main\java\com\springms\config\TestEurekaAuthConfiguration.java)

package com.springms.config;

import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 認(rèn)證配置,由于 UserFeignCustomSecondClient 訪問(wèn) http://localhost:8761/ 需要密碼登錄设易,所以才有了此配置的出現(xiàn)逗柴。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/9/19
 *
 */
@Configuration
public class TestEurekaAuthConfiguration {

    /**
     * 此方法主要配置登錄 Eureka 服務(wù)器的帳號(hào)與密碼。
     *
     * @return
     */
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){
        return new BasicAuthRequestInterceptor("admin", "admin");
    }
}

2.8 添加Web訪問(wèn)層Controller(springms-consumer-movie-feign-custom\src\main\java\com\springms\cloud\controller\MovieFeignCustomController.java)

package com.springms.cloud.controller;

import com.springms.cloud.entity.User;
import com.springms.cloud.feign.UserFeignCustomClient;
import com.springms.cloud.feign.UserFeignCustomSecondClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * 自定義 Feign 控制器顿肺。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/9/19
 *
 */
@RestController
public class MovieFeignCustomController {

    @Autowired
    private UserFeignCustomClient userFeignCustomClient;

    @Autowired
    private UserFeignCustomSecondClient userFeignCustomSecondClient;

    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
        return userFeignCustomClient.findById(id);
    }

    @GetMapping("/{serviceName}")
    public String findEurekaInfo(@PathVariable String serviceName){
        return userFeignCustomSecondClient.findEurekaInfo(serviceName);
    }
}

2.9 添加電影微服務(wù)啟動(dòng)類(springms-consumer-movie-feign-custom\src\main\java\com\springms\cloud\MsConsumerMovieFeignCustomApplication.java)

package com.springms.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

/**
 *
 * 電影微服務(wù)使用定制化 Feign 在客戶端進(jìn)行負(fù)載均衡調(diào)度并為 Feign 配置帳號(hào)密碼登錄認(rèn)證 Eureka戏溺。
 *
 * Feign: Java HTTP 客戶端開(kāi)發(fā)的工具。
 *
 * 注解 EnableFeignClients 表示該電影微服務(wù)已經(jīng)接入 Feign 模塊屠尊。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/9/19
 *
 */
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class MsConsumerMovieFeignCustomApplication {

    public static void main(String[] args) {
        SpringApplication.run(MsConsumerMovieFeignCustomApplication.class, args);
        System.out.println("【【【【【【 電影自定義Feign微服務(wù) 】】】】】】已啟動(dòng).");
    }
}

三旷祸、測(cè)試

/****************************************************************************************
 一、電影微服務(wù)使用定制化Feign在客戶端進(jìn)行負(fù)載均衡調(diào)度并為Feign配置帳號(hào)密碼登錄認(rèn)證Eureka(測(cè)試接入 Feign 模塊):

 1讼昆、注解:EnableFeignClients
 2托享、啟動(dòng) springms-discovery-eureka 模塊服務(wù),啟動(dòng)1個(gè)端口;
 3闰围、啟動(dòng) springms-provider-user 模塊服務(wù)赃绊,啟動(dòng)1個(gè)端口;
 4辫诅、啟動(dòng) springms-consumer-movie-feign-custom 模塊服務(wù)凭戴;
 5、在瀏覽器輸入地址http://localhost:8050/movie/1 可以看到信息成功的被打印出來(lái)炕矮;

 總結(jié):說(shuō)明接入 Feign 已經(jīng)成功通過(guò)測(cè)試么夫;
 ****************************************************************************************/

/****************************************************************************************
 二、電影微服務(wù)使用定制化Feign在客戶端進(jìn)行負(fù)載均衡調(diào)度并為Feign配置帳號(hào)密碼登錄認(rèn)證Eureka(測(cè)試登錄 Eureka 服務(wù)器需要認(rèn)證配置):

 1肤视、注解:EnableFeignClients
 2档痪、啟動(dòng) springms-discovery-eureka 模塊服務(wù),啟動(dòng)1個(gè)端口邢滑;
 3腐螟、啟動(dòng) springms-provider-user 模塊服務(wù),啟動(dòng)1個(gè)端口困后;
 4乐纸、啟動(dòng) springms-consumer-movie-feign-custom 模塊服務(wù);
 5摇予、在瀏覽器輸入地址 http://localhost:8050/springms-provider-user 可以看到信息成功的被打印出來(lái)汽绢;

 總結(jié):說(shuō)明 TestEurekaAuthConfiguration 類中配置的帳號(hào)密碼已經(jīng)生效,可以正常訪問(wèn) Eureka 服務(wù)侧戴;
 ****************************************************************************************/

/****************************************************************************************
 三宁昭、電影微服務(wù)使用定制化Feign在客戶端進(jìn)行負(fù)載均衡調(diào)度并為Feign配置帳號(hào)密碼登錄認(rèn)證Eureka(測(cè)試接入 Feign 模塊進(jìn)行負(fù)載均衡):

 1、注解:EnableFeignClients
 2酗宋、啟動(dòng) springms-discovery-eureka 模塊服務(wù)积仗,啟動(dòng)1個(gè)端口;
 3蜕猫、啟動(dòng) springms-provider-user 模塊服務(wù)寂曹,啟動(dòng)3個(gè)端口(7900、7899回右、7898)稀颁;
 4、啟動(dòng) springms-consumer-movie-feign-custom 模塊服務(wù)楣黍;
 5匾灶、在瀏覽器輸入地址http://localhost:8050/movie/1 連續(xù)刷新9次,正常情況可以看到 springms-provider-user 的3個(gè)端口輪詢打印用戶日志信息租漂;

 總結(jié):1阶女、說(shuō)明接入 Feign 已經(jīng)成功的在客戶端進(jìn)行了負(fù)載均衡處理颊糜;
 2、之所以會(huì)在客戶端進(jìn)行輪詢打印日志信息秃踩,是因?yàn)闆](méi)有配置調(diào)度算法衬鱼,而默認(rèn)的調(diào)度算法就是輪詢,所以會(huì)出現(xiàn)輪詢打印日志信息憔杨;
 ****************************************************************************************/

/****************************************************************************************
 四鸟赫、電影微服務(wù)使用定制化Feign在客戶端進(jìn)行負(fù)載均衡調(diào)度并為Feign配置帳號(hào)密碼登錄認(rèn)證Eureka(配置日志級(jí)別):

 1、application.yml 修改:logging.level.com.springms.cloud.feign.UserFeignCustomClient: DEBUG
 2消别、編寫 TestFeignCustomConfiguration 新增日志級(jí)別的方法
 3抛蚤、啟動(dòng) springms-discovery-eureka 模塊服務(wù),啟動(dòng)1個(gè)端口寻狂;
 4岁经、啟動(dòng) springms-provider-user 模塊服務(wù),啟動(dòng)1個(gè)端口蛇券;
 5缀壤、啟動(dòng) springms-consumer-movie-feign-custom 模塊服務(wù);
 6纠亚、在瀏覽器輸入地址http://localhost:8050/springms-provider-user 可以看到控制臺(tái)中 DEBUG 日志級(jí)別的信息成功的被打印出來(lái)塘慕;
 ****************************************************************************************/

四、下載地址

https://gitee.com/ylimhhmily/SpringCloudTutorial.git

SpringCloudTutorial交流QQ群: 235322432

SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接

歡迎關(guān)注蒂胞,您的肯定是對(duì)我最大的支持!!!

<上一篇????????首頁(yè)????????下一篇>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末图呢,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子啤誊,更是在濱河造成了極大的恐慌岳瞭,老刑警劉巖拥娄,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蚊锹,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡稚瘾,警方通過(guò)查閱死者的電腦和手機(jī)牡昆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)摊欠,“玉大人丢烘,你說(shuō)我怎么就攤上這事⌒┙罚” “怎么了播瞳?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)免糕。 經(jīng)常有香客問(wèn)我赢乓,道長(zhǎng)忧侧,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任牌芋,我火速辦了婚禮蚓炬,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘躺屁。我一直安慰自己肯夏,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布犀暑。 她就那樣靜靜地躺著驯击,像睡著了一般。 火紅的嫁衣襯著肌膚如雪母怜。 梳的紋絲不亂的頭發(fā)上余耽,一...
    開(kāi)封第一講書(shū)人閱讀 49,929評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音苹熏,去河邊找鬼碟贾。 笑死,一個(gè)胖子當(dāng)著我的面吹牛轨域,可吹牛的內(nèi)容都是我干的袱耽。 我是一名探鬼主播,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼干发,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼朱巨!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起枉长,我...
    開(kāi)封第一講書(shū)人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤冀续,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后必峰,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體洪唐,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年吼蚁,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了凭需。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡肝匆,死狀恐怖粒蜈,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情旗国,我是刑警寧澤枯怖,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站能曾,受9級(jí)特大地震影響度硝,放射性物質(zhì)發(fā)生泄漏设捐。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一塘淑、第九天 我趴在偏房一處隱蔽的房頂上張望萝招。 院中可真熱鬧,春花似錦存捺、人聲如沸槐沼。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)岗钩。三九已至,卻和暖如春肖油,著一層夾襖步出監(jiān)牢的瞬間兼吓,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工森枪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留视搏,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓县袱,卻偏偏與公主長(zhǎng)得像浑娜,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子式散,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

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