SpringCloud(第 017 篇)電影微服務(wù)接入Feign帮掉,添加 fallbackFactory 屬性來(lái)觸發(fā)請(qǐng)求進(jìn)行容災(zāi)降級(jí)
一、大致介紹
1窒典、在一些場(chǎng)景中蟆炊,簡(jiǎn)單的觸發(fā)在 FeignClient 加入 Fallback 屬性即可,而另外有一些場(chǎng)景需要訪問(wèn)導(dǎo)致回退觸發(fā)的原因瀑志,那么這個(gè)時(shí)候可以在 FeignClient 中加入 FallbackFactory 屬性即可涩搓;
2、而在使用 Fallback 和 FallbackFactory 時(shí)候劈猪,我僅僅表述個(gè)人觀點(diǎn)昧甘,發(fā)現(xiàn)二者混合一起用的話,會(huì)發(fā)生沖突情況战得,所以大家用的時(shí)候注重考慮一下場(chǎng)景充边,二者屬性用其一即可。
二常侦、實(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-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>
<!-- 客戶端發(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-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: 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}}
# 解決第一次請(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-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 添加訪問(wèn)遠(yuǎn)端用戶微服務(wù) 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請(qǐng)求的客戶端漂佩。
*
* 注解FeignClient的傳參:表示的是注冊(cè)到 Eureka 服務(wù)上的模塊名稱脖含。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/24
*
*/
@FeignClient(name = "springms-provider-user", /*fallback = HystrixClientFallback.class,*/ fallbackFactory = HystrixClientFallbackFactory.class)
public interface UserFeignHystrixFactoryClient {
/**
* 這里有兩個(gè)坑需要注意:<br/>
*
* <li>這里需要設(shè)置請(qǐng)求的方式為 RequestMapping 注解,用 GetMapping 注解是運(yùn)行不成功的仅仆,即 GetMapping 不支持器赞。</li>
* <li>注解 PathVariable 里面需要填充變量的名字,不然也是運(yùn)行不成功的墓拜。</li>
*
* @param id
* @return
*/
@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id);
}
2.5 添加訪問(wèn)遠(yuǎn)端用戶微服務(wù) 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 客戶端回退機(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 HystrixClientFallback implements UserFeignHystrixFactoryClient {
@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.6 添加訪問(wèn)遠(yuǎn)端用戶微服務(wù) 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 客戶端回退機(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 HystrixClientFallbackFactory implements FallbackFactory<UserFeignHystrixFactoryClient> {
private static final Logger Logger = LoggerFactory.getLogger(HystrixClientFallbackFactory.class);
@Override
public 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(){
@Override
public 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();
}
@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClientWithFallBackFactory() {
@Override
public 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訪問(wèn)層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 {
@Autowired
private 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 添加電影微服務(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,添加 fallbackFactory 屬性來(lái)觸發(fā)請(qǐng)求進(jìn)行容災(zāi)降級(jí)棚放。
*
* 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 MsConsumerMovieFeignHystrixFactoryApplication {
public static void main(String[] args) {
SpringApplication.run(MsConsumerMovieFeignHystrixFactoryApplication.class, args);
System.out.println("【【【【【【 電影Feign-HystrixFactory微服務(wù) 】】】】】】已啟動(dòng).");
}
}
三飘蚯、測(cè)試
/****************************************************************************************
一馍迄、電影微服務(wù)接入Feign,添加 fallbackFactory 屬性來(lái)觸發(fā)請(qǐng)求進(jìn)行容災(zāi)降級(jí)(測(cè)試正常接入功能):
1局骤、注解:EnableFeignClients攀圈;
2、編寫類 HystrixClientFallbackFactory 回退處理機(jī)制類峦甩,并給該類加上注解 Component 赘来;加入 FeignClient 注解
// @FeignClient(name = "springms-provider-user", fallback = HystrixClientFallback.class )
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-with-hystrix-factory 模塊服務(wù)球凰;
6狮腿、在瀏覽器輸入地址 http://localhost:8115/movie/1 可以看到具體的用戶信息(即用戶ID != 0 的用戶)成功的被打印出來(lái)腿宰;
****************************************************************************************/
/****************************************************************************************
二、電影FeignHystrix-HystrixFactory微服務(wù)接入 HystrixFactory 功能模塊(測(cè)試斷路器功能):
1缘厢、注解:EnableFeignClients吃度;
2、編寫類 HystrixClientFallbackFactory 回退處理機(jī)制類贴硫,并給該類加上注解 Component椿每,UserFeignHystrixFactoryClient 加上 fallbackFactory 屬性;
// @FeignClient(name = "springms-provider-user", fallback = HystrixClientFallback.class, fallbackFactory = HystrixClientFallbackFactory.class )
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-with-hystrix-factory 模塊服務(wù)痴突;
6、在瀏覽器輸入地址 http://localhost:8115/movie/1 可以看到具體的用戶信息(即用戶ID != 0 的用戶)成功的被打印出來(lái)狼荞;
7辽装、停止 springms-provider-user 模塊服務(wù);
8粘秆、在瀏覽器輸入地址http://localhost:8115/movie/1 可以看到用戶信息ID = 0 的用戶成功的被打印出來(lái)如迟,但隨著問(wèn)題也來(lái)了收毫;
9攻走、HystrixClientFallbackFactory 截獲的異常卻沒(méi)有被打印出來(lái),本來(lái)用戶微服務(wù)停止的話此再,請(qǐng)求鏈接就已經(jīng)鏈接超時(shí)了昔搂,但是為啥異常沒(méi)有打印出來(lái)呢?請(qǐng)看下面第三中測(cè)試方法输拇。
****************************************************************************************/
/****************************************************************************************
三摘符、電影FeignHystrix-HystrixFactory微服務(wù)接入 HystrixFactory 功能模塊(測(cè)試斷路器功能):
1、注解:EnableFeignClients策吠;
2逛裤、編寫類 HystrixClientFallbackFactory 回退處理機(jī)制類,并給該類加上注解 Component猴抹,UserFeignHystrixFactoryClient 去掉 fallback 屬性带族,然后加上 fallbackfactory 屬性;
// @FeignClient(name = "springms-provider-user", fallbackFactory = HystrixClientFallbackFactory.class )
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-with-hystrix-factory 模塊服務(wù)肚邢;
6壹堰、在瀏覽器輸入地址 http://localhost:8115/movie/1 可以看到具體的用戶信息(即用戶ID != 0 的用戶)成功的被打印出來(lái);
7骡湖、停止 springms-provider-user 模塊服務(wù)缀旁;
8、在瀏覽器輸入地址http://localhost:8115/movie/1 可以看到用戶信息ID = -1 的用戶成功的被打印出來(lái)勺鸦,而且異常信息日志也被打印出來(lái)了并巍,這就正常了;
注意:第2步驟:UserFeignHystrixFactoryClient 去掉 fallback 屬性换途,然后加上 fallbackfactory 屬性懊渡;
所以這里目前暫時(shí)謹(jǐn)記,fallback 和 fallbackfactory 屬性會(huì)有沖突军拟,所以只要其一就行了剃执;
****************************************************************************************/
四、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接
歡迎關(guān)注懈息,您的肯定是對(duì)我最大的支持!!!