ApiGateway/Api网关的两种实现
-
Zuul实现
-
比较新的Gateway实现
1) Zuul实现
1.引入依赖
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
2.配置Application类
// 标注当前应用为路由
@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
3.配置application.yml
server:
port: 8080
# 服务注册者配置
eureka:
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://localhost:8761/eureka
# 路由配置
zuul:
routes:
- path: /qc/** # 127.0.0.1:8080/qc/**的所有请求
serviceId: qc # 路由到qc服务上,对应服务注册者的spring.application.name
retryable: true # 重试
- path: /tdp/**
serviceId: tdp
retryable: true
2) Gateway实现
1.引入依赖
compile('org.springframework.cloud:spring-cloud-starter-gateway')
2.配置application.yml
server:
port: 8080
# 服务注册者配置
eureka:
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://localhost:8761/eureka
# Gateway配置
spring:
cloud:
gateway:
discovery:
locator:
enabled: false # 开启则可以以下格式访问服务'http://网关地址/服务名称(大写)/**'
routes: # 配置路由
- id: qc # 可选,默认值为随机字符串
uri: lb://qc/ # 转发到qc,lb为eureka服务协议,qc对应服务注册者spring.application.name
predicates: # 配置捕获地址,predicates是一个List,需传入'Path=xxx'格式的字符串
- Path=/qc/**
- id: tdp
uri: lb://tdp/
predicates:
- Path=/tdp/**
3) 差别
使用上呢以上两种配置
- 前者发起/qc/qc请求会路由到qc服务的/qc上
- 后者发起/qc/qc请求会路由到qc服务的/qc/qc上