當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringCloud(第 017 篇)电影微服务接入Feign,添加 fallbackFactory 属性来触发请求进行容灾降级...
生活随笔
收集整理的這篇文章主要介紹了
SpringCloud(第 017 篇)电影微服务接入Feign,添加 fallbackFactory 属性来触发请求进行容灾降级...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
SpringCloud(第 017 篇)電影微服務接入Feign,添加 fallbackFactory 屬性來觸發請求進行容災降級
一、大致介紹
1、在一些場景中,簡單的觸發在 FeignClient 加入 Fallback 屬性即可,而另外有一些場景需要訪問導致回退觸發的原因,那么這個時候可以在 FeignClient 中加入 FallbackFactory 屬性即可; 2、而在使用 Fallback 和 FallbackFactory 時候,我僅僅表述個人觀點,發現二者混合一起用的話,會發生沖突情況,所以大家用的時候注重考慮一下場景,二者屬性用其一即可。二、實現步驟
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-with-hystrix-factory</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><!-- 客戶端發現模塊 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka</artifactId></dependency><!-- Java HTTP 客戶端開發的工具的模塊 --><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 添加應用配置文件(springms-consumer-movie-feign-with-hystrix-factory\src\main\resources\application.yml)
spring:application:name: springms-consumer-movie-feign-with-hystrix-factory server:port: 8115 eureka:client: # healthcheck: # enabled: trueserviceUrl:defaultZone: http://admin:admin@localhost:8761/eurekainstance:prefer-ip-address: trueinstance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}# 解決第一次請求報超時異常的方案,因為 hystrix 的默認超時時間是 1 秒,因此請求超過該時間后,就會出現頁面超時顯示 : # # 這里就介紹大概三種方式來解決超時的問題,解決方案如下: # # 第一種方式:將 hystrix 的超時時間設置成 5000 毫秒 hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000 # # 或者: # 第二種方式:將 hystrix 的超時時間直接禁用掉,這樣就沒有超時的一說了,因為永遠也不會超時了 # hystrix.command.default.execution.timeout.enabled: false # # 或者: # 第三種方式:索性禁用feign的hystrix支持 # feign.hystrix.enabled: false ## 索性禁用feign的hystrix支持# 超時的issue:https://github.com/spring-cloud/spring-cloud-netflix/issues/768 # 超時的解決方案: 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.timeoutInMilliseconds2.3 添加實體用戶類User(springms-consumer-movie-feign-with-hystrix-factory\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 添加訪問遠端用戶微服務 Feign 客戶端(springms-consumer-movie-feign-with-hystrix-factory\src\main\java\com\springms\cloud\feign\UserFeignHystrixFactoryClient.java)
package com.springms.cloud.feign;import com.springms.cloud.entity.User; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.*;/*** 用戶Http請求的客戶端。** 注解FeignClient的傳參:表示的是注冊到 Eureka 服務上的模塊名稱。** @author hmilyylimh** @version 0.0.1** @date 2017/9/24**/ @FeignClient(name = "springms-provider-user", /*fallback = HystrixClientFallback.class,*/ fallbackFactory = HystrixClientFallbackFactory.class) public interface UserFeignHystrixFactoryClient {/*** 這里有兩個坑需要注意:<br/>** <li>這里需要設置請求的方式為 RequestMapping 注解,用 GetMapping 注解是運行不成功的,即 GetMapping 不支持。</li>* <li>注解 PathVariable 里面需要填充變量的名字,不然也是運行不成功的。</li>** @param id* @return*/@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)public User findById(@PathVariable("id") Long id); }2.5 添加訪問遠端用戶微服務 Fallback 類(springms-consumer-movie-feign-with-hystrix-factory\src\main\java\com\springms\cloud\feign\HystrixClientFallback.java)
package com.springms.cloud.feign;import com.springms.cloud.entity.User; import org.springframework.stereotype.Component;/*** Hystrix 客戶端回退機制類。** 這里加上注解 Component 的目的:就是因為沒有這個注解,運行時候會報錯,報錯會說沒有該類的這個實例,所以我們就想到要實例化這個類,因此加了這個注解。** @author hmilyylimh** @version 0.0.1** @date 2017/9/24**/ @Component public class HystrixClientFallback implements UserFeignHystrixFactoryClient {@Overridepublic 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.6 添加訪問遠端用戶微服務 FallbackFactory 類(springms-consumer-movie-feign-with-hystrix-factory\src\main\java\com\springms\cloud\feign\HystrixClientFallbackFactory.java)
package com.springms.cloud.feign;import com.springms.cloud.entity.User; import feign.hystrix.FallbackFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;/*** Hystrix 客戶端回退機制類。** 這里加上注解 Component 的目的:就是因為沒有這個注解,運行時候會報錯,報錯會說沒有該類的這個實例,所以我們就想到要實例化這個類,因此加了這個注解。** @author hmilyylimh** @version 0.0.1** @date 2017/9/24**/ @Component public class HystrixClientFallbackFactory implements FallbackFactory<UserFeignHystrixFactoryClient> {private static final Logger Logger = LoggerFactory.getLogger(HystrixClientFallbackFactory.class);@Overridepublic UserFeignHystrixFactoryClient create(Throwable e) {Logger.info("fallback; reason was: {}", e.getMessage());System.out.println("======== UserFeignHystrixFactoryClient.create " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());return new UserFeignWithFallBackFactoryClient(){@Overridepublic User findById(Long id) {System.out.println("======== findById FallBackFactory " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());User tmpUser = new User();tmpUser.setId(-1L);return tmpUser;}};} }/****************************************************************************************@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)protected interface HystrixClient {@RequestMapping(method = RequestMethod.GET, value = "/hello")Hello iFailSometimes();}@Componentstatic class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {@Overridepublic HystrixClient create(Throwable cause) {return new HystrixClientWithFallBackFactory() {@Overridepublic Hello iFailSometimes() {return new Hello("fallback; reason was: " + cause.getMessage());}};}}****************************************************************************************/2.7 添加回退處理客戶端類(springms-consumer-movie-feign-with-hystrix-factory\src\main\java\com\springms\cloud\feign\UserFeignWithFallBackFactoryClient.java)
package com.springms.cloud.feign;/*** 回退處理客戶端。** @author hmilyylimh** @version 0.0.1** @date 2017/9/24**/ public interface UserFeignWithFallBackFactoryClient extends UserFeignHystrixFactoryClient{ }2.8 添加Web訪問層Controller(springms-consumer-movie-feign-with-hystrix-factory\src\main\java\com\springms\cloud\controller\MovieFeignHystrixFactoryController.java)
package com.springms.cloud.controller;import com.springms.cloud.entity.User; import com.springms.cloud.feign.UserFeignHystrixFactoryClient; 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 MovieFeignHystrixFactoryController {@Autowiredprivate UserFeignHystrixFactoryClient userFeignHystrixFactoryClient;@GetMapping("/movie/{id}")public User findById(@PathVariable Long id) {System.out.println("======== findById Controller " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());return userFeignHystrixFactoryClient.findById(id);} }2.9 添加電影微服務啟動類(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;/*** 電影微服務接入Feign,添加 fallbackFactory 屬性來觸發請求進行容災降級。** Feign: Java HTTP 客戶端開發的工具。** 注解 EnableFeignClients 表示該電影微服務已經接入 Feign 模塊。** @author hmilyylimh** @version 0.0.1** @date 2017/9/24**/ @SpringBootApplication @EnableEurekaClient @EnableFeignClients public class MsConsumerMovieFeignHystrixFactoryApplication {public static void main(String[] args) {SpringApplication.run(MsConsumerMovieFeignHystrixFactoryApplication.class, args);System.out.println("【【【【【【 電影Feign-HystrixFactory微服務 】】】】】】已啟動.");} }三、測試
/****************************************************************************************一、電影微服務接入Feign,添加 fallbackFactory 屬性來觸發請求進行容災降級(測試正常接入功能):1、注解:EnableFeignClients;2、編寫類 HystrixClientFallbackFactory 回退處理機制類,并給該類加上注解 Component ;加入 FeignClient 注解// @FeignClient(name = "springms-provider-user", fallback = HystrixClientFallback.class )3、啟動 springms-discovery-eureka 模塊服務,啟動1個端口;4、啟動 springms-provider-user 模塊服務,啟動1個端口;5、啟動 springms-consumer-movie-feign-with-hystrix-factory 模塊服務;6、在瀏覽器輸入地址 http://localhost:8115/movie/1 可以看到具體的用戶信息(即用戶ID != 0 的用戶)成功的被打印出來;****************************************************************************************//****************************************************************************************二、電影FeignHystrix-HystrixFactory微服務接入 HystrixFactory 功能模塊(測試斷路器功能):1、注解:EnableFeignClients;2、編寫類 HystrixClientFallbackFactory 回退處理機制類,并給該類加上注解 Component,UserFeignHystrixFactoryClient 加上 fallbackFactory 屬性;// @FeignClient(name = "springms-provider-user", fallback = HystrixClientFallback.class, fallbackFactory = HystrixClientFallbackFactory.class )3、啟動 springms-discovery-eureka 模塊服務,啟動1個端口;4、啟動 springms-provider-user 模塊服務,啟動1個端口;5、啟動 springms-consumer-movie-feign-with-hystrix-factory 模塊服務;6、在瀏覽器輸入地址 http://localhost:8115/movie/1 可以看到具體的用戶信息(即用戶ID != 0 的用戶)成功的被打印出來;7、停止 springms-provider-user 模塊服務;8、在瀏覽器輸入地址http://localhost:8115/movie/1 可以看到用戶信息ID = 0 的用戶成功的被打印出來,但隨著問題也來了;9、HystrixClientFallbackFactory 截獲的異常卻沒有被打印出來,本來用戶微服務停止的話,請求鏈接就已經鏈接超時了,但是為啥異常沒有打印出來呢?請看下面第三中測試方法。****************************************************************************************//****************************************************************************************三、電影FeignHystrix-HystrixFactory微服務接入 HystrixFactory 功能模塊(測試斷路器功能):1、注解:EnableFeignClients;2、編寫類 HystrixClientFallbackFactory 回退處理機制類,并給該類加上注解 Component,UserFeignHystrixFactoryClient 去掉 fallback 屬性,然后加上 fallbackfactory 屬性;// @FeignClient(name = "springms-provider-user", fallbackFactory = HystrixClientFallbackFactory.class )3、啟動 springms-discovery-eureka 模塊服務,啟動1個端口;4、啟動 springms-provider-user 模塊服務,啟動1個端口;5、啟動 springms-consumer-movie-feign-with-hystrix-factory 模塊服務;6、在瀏覽器輸入地址 http://localhost:8115/movie/1 可以看到具體的用戶信息(即用戶ID != 0 的用戶)成功的被打印出來;7、停止 springms-provider-user 模塊服務;8、在瀏覽器輸入地址http://localhost:8115/movie/1 可以看到用戶信息ID = -1 的用戶成功的被打印出來,而且異常信息日志也被打印出來了,這就正常了;注意:第2步驟:UserFeignHystrixFactoryClient 去掉 fallback 屬性,然后加上 fallbackfactory 屬性;所以這里目前暫時謹記,fallback 和 fallbackfactory 屬性會有沖突,所以只要其一就行了;****************************************************************************************/四、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接
歡迎關注,您的肯定是對我最大的支持!!!
轉載于:https://my.oschina.net/hmilyylimh/blog/1542418
總結
以上是生活随笔為你收集整理的SpringCloud(第 017 篇)电影微服务接入Feign,添加 fallbackFactory 属性来触发请求进行容灾降级...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2中dtd失效,代码不提示问
- 下一篇: Java8之Stream-函数式接口