一. 基本使用
-
pom.xml添加依赖
<dependencies>
<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-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
-
application.yml
server:
port: 9000
#服务的名称
spring:
application:
name: api-gateway
#指定注册中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
-
启动类中添加注解@EnableZuulProxy
@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
@EnableZuulProxy注解包含@EnableCircuitBreaker,会默认开启断路器
@EnableCircuitBreaker
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({ZuulProxyMarkerConfiguration.class})
public @interface EnableZuulProxy {
}
-
通过网关进行访问
-
默认访问规则: http://gateway:port/service-id/**
-
例子:
-
默认:/order-service/api/v1/order/save?user_id=2&product_id=1
-
自定义:/apigateway/api/v1/order/save?user_id=2&product_id=1
-
-
二. 自定义路由映射,并统一入口
-
在application.yml中添加配置
#服务的名称
spring:
application:
name: api-gateway
#指定注册中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
#/order-service/api/v1/order/save?user_id=2&product_id=1
#自定义路由映射
zuul:
routes:
order-service: /apigateway/**
product-service: /apigateway/**
#统一入口为上面的配置,其他入口忽略,机器网络隔离,但是直接访问服务还是能够访问,但是部署的时候,其他的服务ip不提供出来
ignored-patterns: /*-service/**
#忽略整个服务,对外提供接口
#ignored-services: product-service
三. 常见问题
-
在配置文件中会有路由映射重复覆盖的问题:取名的时候避免重复,比如上面的地方
zuul:
routes:
order-service: /apigateway/order/**
product-service: /apigateway/product/**
-
Http请求头过滤问题
-
默认token可以传递,不可以传递"Cookie", "Set-Cookie", "Authorization"
-
因为源码中:private Set<String> sensitiveHeaders = new LinkedHashSet(Arrays.asList("Cookie", "Set-Cookie", "Authorization"));
-
-
解决:在配置文件中添加sensitive-headers
-
zuul:
routes:
order-service: /apigateway/order/**
product-service: /apigateway/product/**
#统一入口为上面的配置,其他入口忽略
ignored-patterns: /*-service/**
#处理http请求头为空的问题:里面是个集合,如果什么都不加,就是请求头所有可以带过去
sensitive-headers:
-
过滤器执行顺序:
-
一般自定义过滤器都在“pre”filters里面进行编写
-
order(权值)order越小,越先执行
-
-
HTTPRequest 通过RequestContext共享上下文