1. 背景
首先项目需要实现只暴漏一个端口就能访问各微服务,通过每个微服务的名称可以访问对应应用,把网关和微服务都注册到服务治理中心eureka,同时添加下面配置:
discovery:
locator:
enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
lower-case-service-id: true #开启默认serverID小写
之后开发了公共方法,这些方法只想让微服务之间调用,不想暴漏到外网,所以需要网关拦截一下。
2. 方法
同时使用routes和discovery,这里注意routes配置好了并不能覆盖
discovery。例如:
我要访问一个应用服务,application.name=app1:http://www.xxx.com:8000/common/showVersion
那我需要访问网关
http://www.xxx.com:9000/app1/common/showVersion
配置文件
server:
port: 9000
#微服务名称
spring:
cloud:
gateway:
routes:
- id: app1-perdict2
uri: lb://app1
order: -1
predicates:
- Path=/app1/common/**
filters:
- SetStatus=BAD_REQUEST
discovery:
locator:
enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
lower-case-service-id: true #开启默认serverID小写
application:
name: gateway-cpwx
#Eureka settings
eureka:
client:
enabled: true
service-url:
defaultZone: http://1.1.1.1:8756/eureka/
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
lease-expiration-duration-in-seconds: 30
logging:
level:
org.springframework.cloud.gateway: debug
这里假设网关需要屏蔽的访问链接是http://www.xxx.com:9000/app1/common/**
而不屏蔽其他接口的访问
其他接口访问日志
Route matched: ReactiveCompositeDiscoveryClient_APP1
2021-06-29 15:49:53.784 DEBUG 54575 --- [or-http-epoll-2] o.s.c.g.h.RoutePredicateHandlerMapping : Mapping [Exchange: POST http://www.xxx.com:8000/app1/test] to Route{id='ReactiveCompositeDiscoveryClient_APP1, uri=lb://APP1, order=0, predicate=Paths: [/app1/**], match trailing slash: true, gatewayFilters=[[[RewritePath /app1/(?<remaining>.*) = '/${remaining}'], order = 1]], metadata={pfpj.inst-grp-code=default, pfpj.sys-code=app1, spring.application.name=app1, pfpj.pid=54336, management.port=9000, pfpj.hystrix-stream-enabled=false}}
可以看到是下面配置生效,order=0
discovery:
locator:
enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
lower-case-service-id: true #开启默认serverID小写
所以routes中一定要配置order<0才能先匹配到routes中的路由:
routes:
- id: app1-perdict2
uri: lb://app1
order: -1
predicates:
- Path=/app1/common/**
filters:
- SetStatus=BAD_REQUEST
日志:
2021-06-29 16:12:16.417 DEBUG 54575 --- [or-http-epoll-2] o.s.c.g.h.RoutePredicateHandlerMapping : Route matched: app1-perdict2
2021-06-29 16:12:16.418 DEBUG 54575 --- [or-http-epoll-2] o.s.c.g.h.RoutePredicateHandlerMapping : Mapping [Exchange: POST http://www.xxx.com:8000/app1/common/queryWxAppdef] to Route{id='app1-perdict2', uri=lb://app1, order=-1, predicate=Paths: [/app1/common/**], match trailing slash: true, gatewayFilters=[[[SetStatus status = 'BAD_REQUEST'], order = 1]], metadata={}}
这里只屏蔽一部分方法,如果整个微服务都不想暴漏接口到外网,可以直接这样写:
routes:
- id: app1-perdict2
uri: lb://app1
order: -1
predicates:
- Path=/app1/**
filters:
- SetStatus=BAD_REQUEST