天天看點

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);
    }

}
           

繼續閱讀