Spring Cloud Gateway 服务网关的部署与使用详细介绍
warning:
这篇文章距离上次修改已过227天,其中的内容可能已经有所变动。
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
在这个配置中,我们定义了两条路由规则:
- 当请求路径为
/api/**
时,转发到http://localhost:8081
- 当请求路径为
/api-hystrix/**
时,转发到http://localhost:8082
,并应用 Hystrix 断路器保护
- 创建启动类:
@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 = serviceId;
}
@Override
protected String run() throws Exception {
return restTemplate.getForObject("http://" + serviceId +
评论已关闭