SpringCloud微服務 之hystrix(三)
阿新 • • 發佈:2018-11-09
前言
本小節我們學習一下如何是Feign擁有Hystrix的熔斷功能。
案例
-
Eureka Server端編寫(參考前例)。
-
Eureka Client端服務提供方編寫。
-
專案結構
-
CoreCode
<?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>microservice-deal-broker-cloud-hystrix-with-feign</artifactId> <packaging>jar</packaging> <name>microservice-deal-broker-cloud-hystrix-with-feign</name> <description>Demo project for Spring Boot</description> <parent> <groupId>com.example</groupId> <artifactId>microservice-deal-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <dependencies> <!-- Eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- Feignf --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- springCloud Hystrix依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> </dependencies> </project>
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients //開啟FeignClient註解 @EnableCircuitBreaker //開啟Hystrix熔斷機制 public class MicroserviceDealBrokerHystrixWithFeignApplication { public static void main(String[] args) { SpringApplication.run(MicroserviceDealBrokerHystrixWithFeignApplication.class, args); } }
@FeignClient(name = "microservice-deal-cloud",fallback = HystrixFallBackMethod.class) public interface FeignConfig { //第一個坑:使用Feign的時候,如果引數中帶有@PathVariable形式的引數,則要用value=""標明對應的引數,否則會丟擲IllegalStateException異常 @GetMapping("/deal/{id}") public Deal findById(@PathVariable(value="id") Long id); }
@Component public class HystrixFallBackMethod implements FeignConfig { @Override public Deal findById(Long id) { Deal deal = new Deal(); deal.setId(id.intValue()); deal.setName("Dustyone"); return deal; } }
@RestController public class BrokerController { @Autowired private FeignConfig feignConfig; @GetMapping("/deal/{id}") public Deal findById(@PathVariable(value="id") Long id) { return this.feignConfig.findById(id); } }
-
-
Eureka Client端服務提消費編寫(單例項) (參考前例)。
-
手動shutdown 服務提供者:
-
訪問:http://localhost:8082/deal/2
此時FeignClient中宣告的 Hystrix熔斷機制開啟了。
小結
- 在FeignClient中宣告Hystrix熔斷機制需要在@FeignClient中宣告fallback方法,同時配置檔案中宣告Feign對Hystrix的支援:feign:hystrix:enabled: true。
- 在主類中聲明瞭@EnableFeignClients可以不需要對@EnableCircuitBreaker做宣告(feign:hystrix:enabled: true一被宣告)。
- 本小節使用的案例:microservice-deal-eureka、microservice-deal-cloud、microservice-deal-broker-cloud-hystrix-with-feign