SpringCloud(第 016 篇)電影微服務(wù),定制Feign,一個(gè)Feign功能禁用Hystrix,另一個(gè)Feign功能啟用Hystrix
一、大致介紹
1、在一些場(chǎng)景中,部分功能需要使用斷路器功能,部分功能不需要斷路器功能,所以才有了本章節(jié)的介紹;
2、定制 Feign 的時(shí)候,可以為 Feign 設(shè)置 Configuration 配置,在該配置中可以設(shè)置是否需要斷路器功能;
3、該定制的 Configuration 在官方文件介紹中特意提到不需要被啟動(dòng)類所在的包下,因?yàn)樵撆渲妙惒徊灰粧呙璧剑?4、當(dāng)然,此章節(jié)定制后的 Feign 同樣支持客戶端負(fù)載均衡功能,只要開(kāi)啟多個(gè)用戶微服務(wù)即可;
5、這里提到為什么開(kāi)啟多個(gè)微服務(wù)就能做到客戶端負(fù)載均衡呢?
- 簡(jiǎn)答的說(shuō)就是 Feign 可以看作僅僅只是一個(gè)請(qǐng)求網(wǎng)絡(luò)已被封裝好的客戶端HTTP請(qǐng)求工具類,將發(fā)出去的請(qǐng)求封裝好;
- 至于要請(qǐng)求到哪臺(tái)遠(yuǎn)端微服務(wù)的話,剩下的就交給 Ribbon 來(lái)處理了,而且默認(rèn)集成使用了負(fù)載均衡的Ribbon客戶端;
- 自然而然添加多個(gè)用戶微服務(wù),F(xiàn)eign自然就支持負(fù)載均衡的功能。
二、實(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-without-hystrix</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>
<!-- Hystrix 斷路器模塊 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
</dependencies>
</project>
2.2 添加應(yīng)用配置文件(springms-consumer-movie-feign-custom-without-hystrix\src\main\resources\application.yml)
spring:
application:
name: springms-consumer-movie-feign-custom-without-hystrix
server:
port: 8110
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-without-hystrix\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-without-hystrix\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/24
*
*/
@FeignClient(name = "springms-provider-user", configuration = TestFeignCustomConfiguration.class, fallback = UserFeignCustomClientFallback.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-without-hystrix\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/24
*
*/
@FeignClient(name = "xxx", url = "http://localhost:8761/", configuration = TestEurekaAuthConfiguration.class, fallback = UserFeignCustomSecondClientFallback.class)
public interface UserFeignCustomSecondClient {
@RequestMapping(value = "/eureka/apps/{serviceName}")
public String findEurekaInfo(@PathVariable("serviceName") String serviceName);
}
2.6 添加訪問(wèn)遠(yuǎn)端用戶微服務(wù) Fallback 類(springms-consumer-movie-feign-custom\src\main\java\com\springms\config\TestFeignCustomConfiguration.java)
package com.springms.cloud.feign;
import com.springms.cloud.entity.User;
import org.springframework.stereotype.Component;
/**
* Hystrix 客戶端回退機(jī)制類。
*
* 這里加上注解 Component 的目的:就是因?yàn)闆](méi)有這個(gè)注解,運(yùn)行時(shí)候會(huì)報(bào)錯(cuò),報(bào)錯(cuò)會(huì)說(shuō)沒(méi)有該類的這個(gè)實(shí)例,所以我們就想到要實(shí)例化這個(gè)類,因此加了這個(gè)注解。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/24
*
*/
@Component
public class UserFeignCustomClientFallback implements UserFeignCustomClient{
/**
* Fallback 回退降級(jí)的方法,返回一個(gè)默認(rèn)的用戶信息。
*
* @param id
* @return
*/
@Override
public User findById(Long id) {
System.out.println("========== findById Fallback " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());
User tmpUser = new User();
tmpUser.setId(0L);
return tmpUser;
}
}
2.7 添加登錄認(rèn)證Eureka服務(wù) Fallback 類(springms-consumer-movie-feign-custom\src\main\java\com\springms\config\TestEurekaAuthConfiguration.java)
package com.springms.cloud.feign;
import org.springframework.stereotype.Component;
/**
* Hystrix 客戶端回退機(jī)制類。
*
* 這里加上注解 Component 的目的:就是因?yàn)闆](méi)有這個(gè)注解,運(yùn)行時(shí)候會(huì)報(bào)錯(cuò),報(bào)錯(cuò)會(huì)說(shuō)沒(méi)有該類的這個(gè)實(shí)例,所以我們就想到要實(shí)例化這個(gè)類,因此加了這個(gè)注解。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/24
*
*/
@Component
public class UserFeignCustomSecondClientFallback implements UserFeignCustomSecondClient{
@Override
public String findEurekaInfo(String serviceName) {
System.out.println("========== findEurekaInfo Fallback " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());
return "springms-provider-user";
}
}
2.8 添加訪問(wèn)遠(yuǎn)端用戶微服務(wù)配置類(springms-consumer-movie-feign-custom-without-hystrix\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/24
*
*/
@Configuration
public class TestFeignCustomConfiguration {
@Bean
public Contract feignContract(){
return new feign.Contract.Default();
}
/**
* 日志級(jí)別配置
*
* @return
*/
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
2.9 添加訪問(wèn)遠(yuǎn)端Eureka微服務(wù)配置類(springms-consumer-movie-feign-custom-without-hystrix\src\main\java\com\springms\config\TestEurekaAuthConfiguration.java)
package com.springms.config;
import feign.Feign;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
/**
* 認(rèn)證配置,由于 UserFeignCustomSecondClient 訪問(wèn) http://localhost:8761/ 需要密碼登錄,所以才有了此配置的出現(xiàn)。
*
* 不和 com.springms.cloud 在同級(jí)目錄,因?yàn)槲臋n有說(shuō)明,不要被掃描到即可。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/24
*
*/
@Configuration
public class TestEurekaAuthConfiguration {
/**
* 此方法主要配置登錄 Eureka 服務(wù)器的帳號(hào)與密碼。
*
* @return
*/
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){
return new BasicAuthRequestInterceptor("admin", "admin");
}
/**
* 在該配置中,加入這個(gè)方法的話,表明使用了該配置的地方,就會(huì)禁用該模塊使用 Hystrix 容災(zāi)降級(jí)的功能;
*
* @return
*/
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder(){
return Feign.builder();
}
}
2.10 添加Web訪問(wèn)層Controller(springms-consumer-movie-feign-custom-without-hystrix\src\main\java\com\springms\cloud\controller\MovieFeignCustomWithoutHystrixController.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;
@RestController
public class MovieFeignCustomWithoutHystrixController {
@Autowired
private UserFeignCustomClient userFeignCustomClient;
@Autowired
private UserFeignCustomSecondClient userFeignCustomSecondClient;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
System.out.println("======== findById Controller " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());
return userFeignCustomClient.findById(id);
}
@GetMapping("/{serviceName}")
public String findEurekaInfo(@PathVariable String serviceName){
System.out.println("======== findEurekaInfo Controller " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());
return userFeignCustomSecondClient.findEurekaInfo(serviceName);
}
}
2.11 添加電影微服務(wù)啟動(dòng)類(springms-consumer-movie-feign-custom-without-hystrix\src\main\java\com\springms\cloud\MsConsumerMovieFeignCustomWithoutHystrixApplication.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,一個(gè)Feign功能禁用Hystrix,另一個(gè)Feign功能啟用Hystrix。
*
* Feign: Java HTTP 客戶端開(kāi)發(fā)的工具。
*
* 注解 EnableFeignClients 表示該電影微服務(wù)已經(jīng)接入 Feign 模塊。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/24
*
*/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class MsConsumerMovieFeignCustomWithoutHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(MsConsumerMovieFeignCustomWithoutHystrixApplication.class, args);
System.out.println("【【【【【【 電影自定義FeignWithoutHystrix微服務(wù) 】】】】】】已啟動(dòng).");
}
}
三、測(cè)試
/****************************************************************************************
一、電影微服務(wù),定制Feign,一個(gè)Feign功能禁用Hystrix,另一個(gè)Feign功能啟用Hystrix(正常功能測(cè)試):
1、編寫(xiě):UserFeignCustomClientFallback、UserFeignCustomSecondClientFallback 斷路器回退客戶端類;
2、編寫(xiě) TestEurekaAuthConfiguration 配置,加入禁用 Hystrix 模塊功能的代碼,表示禁用該配置的客戶端模塊;
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-without-hystrix 模塊服務(wù);
6、在瀏覽器輸入地址 http://localhost:8110/movie/1 可以看到信息成功的被打印出來(lái),表明正常情況下一切正常;
7、在瀏覽器輸入地址 http://localhost:8110/springms-provider-user 可以看到信息成功的被打印出來(lái),表明正常情況下一切正常;
注意:如果第6步如果一開(kāi)始就輸入ID = 0 的用戶信息,不要灰心,耐心等等,說(shuō)不定服務(wù)之間還沒(méi)通信鏈接成功呢。。。
如果第6步的地址輸入錯(cuò)誤,請(qǐng)回頭看看 springms-provider-user 該微服務(wù) appname 的名字,再次輸入http://localhost:8110/ + appname 即可試試;
****************************************************************************************/
/****************************************************************************************
二、電影微服務(wù),定制Feign,一個(gè)Feign功能禁用Hystrix,另一個(gè)Feign功能啟用Hystrix(禁用其中一個(gè) Feign 的斷路器功能):
1、編寫(xiě):UserFeignCustomClientFallback、UserFeignCustomSecondClientFallback 斷路器回退客戶端類;
2、編寫(xiě) TestEurekaAuthConfiguration 配置,加入禁用 Hystrix 模塊功能的代碼,表示禁用該配置的客戶端模塊;
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-without-hystrix 模塊服務(wù);
6、在瀏覽器輸入地址 http://localhost:8110/movie/1 可以看到信息成功的被打印出來(lái),表明正常情況下一切正常;
7、在瀏覽器輸入地址 http://localhost:8110/springms-provider-user 可以看到信息成功的被打印出來(lái),表明正常情況下一切正常;
8、關(guān)閉 springms-provider-user 模塊服務(wù);
9、在瀏覽器輸入地址 http://localhost:8110/movie/1 可以看到用戶ID = 0 的用戶信息被打印出來(lái),表明該模塊的Hystrix斷路器模塊起作用了;
10、再關(guān)閉 springms-discovery-eureka 模塊服務(wù);
11、再在瀏覽器輸入地址 http://localhost:8110/appname-springms-provider-user 可以看到網(wǎng)頁(yè)已經(jīng)打印出鏈接不上服務(wù)的錯(cuò)誤頁(yè)面了,表明該模塊禁用Hystrix斷路器模塊也起作用了;
****************************************************************************************/
四、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接
歡迎關(guān)注,您的肯定是對(duì)我最大的支持!!!