spring cloud gateway - 熔断

spring cloud gateway - 熔断

搭建API网关

技术栈:spring cloud gateway + hystrix + erueka client
网关的项目配置都是基于代码方式(除了一些必要的配置)

实现熔断

pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

application.properties

server.port=8061
spring.application.name=service-gateway
eureka.client.serviceUrl.defaultZone=http://localhost:8080/eureka/

# hystrix配置
hystrix.shareSecurityContext=true
# hystrix设置超时时间 (default - 为默认,可改为某一配置名,即本服务的hystrixName,超时时间单位为毫秒)
# hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
hystrix.command.hystrixName.execution.isolation.thread.timeoutInMilliseconds=5000

RouterConfig.java

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RouterConfig {

    /**
     * 权限微服务
     * @param builder 路由设置
     * @return RouteLocator
     */
    @Bean
    public RouteLocator routeLocatorPermission(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("permission", r -> r.path("/demo/permission/**")
                        .filters(f -> f
                                .stripPrefix(2)
                                .hystrix(config -> config.setName("hystrixName").setFallbackUri("forward:/fallback"))
                        )
                        .uri("lb://BOSS-BES-PERMISSION")).build();
    }
}

RouterController.java

@RestController
public class RouterController {

    /**
     * 熔断回调
     * @return Mono
     */
    @RequestMapping("/fallback")
    public Mono<String> fallback() {
        return Mono.just("熔断的回调");
    }
}

BossBesGatewayApplication.java

@SpringBootApplication
@EnableEurekaClient
public class BossBesGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(BossBesGatewayApplication.class, args);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值