===^^===
《榴芒客服系统》是我们工作室开发的在线客服系统,欢迎下载试用:
《榴芒客服系统》
https://blog.csdn.net/look4liming/article/details/164755808
S pring Boot 熔断
在Spring Boot中实现熔断可以使用Spring Cloud Netflix的Hystrix库。
1、在pom.xml中添加Hystrix依赖:
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <dependencies> <!-- ... -> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> <!-- ... -> </dependencies> |
- 在Spring Boot主类上添加 @EnableCircuitBreaker 注解来启用Hystrix:
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableCircuitBreaker @EnableDiscoveryClient public class MyApp { public static void main(String\[\] args) { SpringApplication.run(MyApp.class, args); } } |
- 使用 @HystrixCommand 注解定义熔断逻辑:
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.stereotype.Service; @Service public class MyService { @HystrixCommand (fallbackMethod = "fallbackMethod") public String getData() { Return "DATA"; } public String fallbackMethod() { return "Service unavailable, please try again later."; } } |