Spring Cloud的服务熔断(resilience4j)

为什么我会将Hystrix的熔断器换成resilience4j,因为尝试了半天发现虽然Hystrix的熔断器可以正常使服务降级,单个api接口可以返回fallback错误信息,但是不能使得服务熔断,具体原因可能就是注解失效,被放弃了,所以后面边将熔断器换成了当前的熔断器resilience4j

具体可以看看这篇博客,这篇博客详细写了如何使用resilience4j熔断器去使服务下降和服务熔断。OpenFeign熔断与降级_openfeign熔断降级-优快云博客

紧接上文的熔断器使服务降级

resilience4j的依赖下载:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
        </dependency>

架构如图所示:

IProductClientServiceFallbackFactory

package com.gaolang.fallback;

import com.gaolang.FeignClient.OrderFeignClient;
import com.gaolang.entities.CommonResult;
import com.gaolang.entities.Payment;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;



public class IProductClientServiceFallbackFactory implements FallbackFactory<OrderFeignClient> {

    @Override
    public OrderFeignClient create(Throwable cause) {

        return new OrderFeignClient() {
            @Override
            public CommonResult create(Payment payment) {
                return new CommonResult<>(444,"服务降级返回,---PaymentFallbackService");
            }

            @Override
            public CommonResult getPaymentById(Long id) {
                return new CommonResult<>(444,"服务降级返回,---PaymentFallbackService");
            }

        };
    }
}

OrderFeignClient

package com.gaolang.FeignClient;


import com.gaolang.entities.CommonResult;
import com.gaolang.entities.Payment;
import com.gaolang.fallback.IProductClientServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@FeignClient(value  = "cloud-provider-payment8001", fallbackFactory  = IProductClientServiceFallbackFactory.class) // 指定调用的服务名称
public interface OrderFeignClient {

    @PostMapping(value = "/payment/create")
    CommonResult create(Payment payment); // 创建支付记录

    @GetMapping(value = "/payment/{id}")
    CommonResult getPaymentById(@PathVariable("id") Long id); // 根据 ID 获取支付记录
}

FallbackConfig

package com.gaolang.config;

import com.gaolang.fallback.IProductClientServiceFallbackFactory;
import org.springframework.context.annotation.Bean;

public class FallbackConfig {
    @Bean
    public IProductClientServiceFallbackFactory iArticleClientFallbackFactory() {
        return new IProductClientServiceFallbackFactory();
    }
}

OrderMain80

package com.gaolang;


import com.gaolang.config.FallbackConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
//import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;



@SpringBootApplication
@EnableFeignClients(basePackages = "com.gaolang", defaultConfiguration = FallbackConfig.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }

    @LoadBalanced // 使 RestTemplate 自动支持 Ribbon 负载均衡
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

单启动该模块后,对api进行测试http://localhost:80/customer/payment/1后的结果如图所示:

成功使得服务熔断。

### Spring Cloud Gateway 中集成 Resilience4j 实现容错和限流 #### 配置依赖项 为了在 Spring Cloud Gateway 中使用 Resilience4j 的功能,首先需要引入相应的 Maven 或 Gradle 依赖。 对于 Maven 用户,在 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- 添加 Resilience4j Starter --> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot2</artifactId> </dependency> <!-- 如果还需要其他模块比如限流 --> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-ratelimiter</artifactId> </dependency> ``` #### 应用配置文件设置 接着,在应用程序的配置文件 (`application.yml`) 中定义所需的 Resilience4j 组件参数。这里展示了一个简单的例子来说明如何配置熔断器以及限流策略: ```yaml resilience4j: ratelimiter: instances: myServiceRateLimiter: limitForPeriod: 10 # 每秒允许的最大请求数量 limitRefreshPeriod: 1s # 刷新周期时间间隔 timeoutDuration: 0ms # 请求等待队列中的最大超时时间 circuitbreaker: configs: default: registerHealthIndicator: true slidingWindowSize: 10 minimumNumberOfCalls: 5 permittedNumberOfCallsInHalfOpenState: 3 automaticTransitionFromOpenToHalfOpenEnabled: true waitDurationInOpenState: 5s failureRateThreshold: 50 instances: backendA: baseConfig: default ``` #### 创建过滤器并应用到路由上 创建自定义全局过滤器或特定路径下的局部过滤器以启用 Resilience4j 功能。下面是一个基于 Java DSL 定义带有熔断逻辑和服务调用重试机制的例子: ```java import io.github.resilience4j.circuitbreaker.CircuitBreaker; import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class CustomGlobalFilter { @Autowired private CircuitBreakerRegistry circuitBreakerRegistry; @Bean public GlobalFilter customGlobalFilter() { return (exchange, chain) -> { String routeId = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ID_ATTR); // 使用默认注册表获取名为 "backendA" 的熔断器实例 CircuitBreaker cb = circuitBreakerRegistry.circuitBreaker("backendA"); Supplier<Mono<Void>> supplier = () -> chain.filter(exchange).then(Mono.empty()); Mono<ResponseEntity<String>> result = cb.executeCompletionStage(supplier::get) .toCompletableFuture() .exceptionally(throwable -> { System.out.println("Circuit breaker opened"); return null;}) .thenApply(r -> ResponseEntity.ok().body("{\"message\":\"Fallback response\"}")) .toMono(); return result.flatMap(response -> ServerResponse.from(exchange.getResponse()) .status(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON_UTF8) .syncBody(response.getBody()).build()); }; } } ``` 以上代码片段展示了如何利用 Resilience4j 提供的服务保护能力增强微服务架构的安全性和稳定性[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值