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