SpringCloud-Gateway网关的使用
Spring Cloud Gateway是Spring Cloud的一个全新项目,该项目是基于Spring 5.0,Spring WebFlux和Project Reactor等技术构建的API网关,提供的功能包括:路由转发、权限校验、负载均衡等。
以下是一个简单的Spring Cloud Gateway网关的配置示例:
- 在
pom.xml
中添加依赖:
<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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 配置application.yml:
spring:
cloud:
gateway:
routes:
- id: after_route
uri: http://localhost:8081
predicates:
- Path=/api/**
- id: hystrix_route
uri: http://localhost:8082
predicates:
- Path=/api-hystrix/**
filters:
- Hystrix=myCommand
default-filters:
- AddResponseHeader=X-Response-Default-Header, DefaultValue
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000
在这个配置中,我们定义了两条路由规则:
- 当请求路径为
/api/**
时,转发到http://localhost:8081
- 当请求路径为
/api-hystrix/**
时,转发到http://localhost:8082
,并使用Hystrix命令名为myCommand
的断路器保护
- 创建启动类:
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
- 使用Hystrix的命令创建类:
@Component
public class HystrixCommand extends HystrixCommand<String> {
private RestTemplate restTemplate;
private String serviceId;
public HystrixCommand(Setter setter, RestTemplate restTemplate, String serviceId) {
super(setter);
this.restTemplate = restTemplate;
this.serviceId = ser
评论已关闭