在spring cloud gateway中可以使用Hystrix。Hystrix是 spring cloud中一个服务熔断降级的组件,在微服务系统有着十分重要的作用。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cntaiping.tpa</groupId>
<artifactId>hystrix-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hystrix-gateway</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>com.cntaiping.tpa</groupId>
<artifactId>gateway</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
</project>
server.port= 7011
package com.cntaiping.tpa.hystrixgateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class HystrixGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixGatewayApplication.class, args);
}
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("path-route",p -> p
//断言为“/get”,凡是访问路由网关中的“/get”路径
.path("/get")
//在请求头中增加“Hello”—“World”键值对
.filters(f -> f.addRequestHeader("Hello", "World"))
//转发到http://httpbin.org
.uri("http://httpbin.org"))
//使用hystrix
.route("hystrix-route",p -> p
//当请求头中的Host为*.hystrix.com,进入此路由
.host("*.hystrix.com")
//设置Hystrix熔断,当请求(转发到http://httpbin.org)超时时,请求转发到Gateway中的“/fallback”
.filters(f -> f.hystrix(
config -> config.setName("cmd").setFallbackUri("forward:/fallback")))
//转发到http://httpbin.org
.uri("http://httpbin.org"))
.build();
}
}
package com.cntaiping.tpa.hystrixgateway.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class MessageController {
@RequestMapping("/fallback")
public Mono<String> fallback() {
return Mono.just("fallback");
}
}
http://httpbin.org/delay/3表示3秒后请求超时。
curl --dump-header - --header Host:www.hystrix.com http://localhost:7011/delay/3