springboot写熔断--方式1
Spring Boot 中可以使用 Hystrix 实现熔断器模式。以下是一个简单的示例:
1.添加依赖到你的 pom.xml
:
<dependencies> <!-- 其他依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> </dependencies>
2.在启动类上添加 @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 public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
3。 创建一个服务类并使用 @HystrixCommand
注解指定回退方法:
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.stereotype.Service; @Service public class MyService { @HystrixCommand(fallbackMethod = "fallbackMethod") public String serviceMethod() { // 调用远程服务或者复杂逻辑 // 如果这里抛出异常或者超时,将会调用fallbackMethod } public String fallbackMethod() { // 返回备选响应 return "Service is unavailable, please try again later."; } }
在上述代码中,serviceMethod
是主要的业务逻辑方法,它被 @HystrixCommand
注解装饰。当 serviceMethod
调用失败或者执行超时时,Hystrix 会自动调用定义的回退方法 fallbackMethod
。
确保你的 Spring Boot 应用配置了合适的 Hystrix 参数,比如超时时间、断路器的开关策略等,以便于正确实现熔断模式。