在https://blog.csdn.net/sdmanooo/article/details/115490907 这篇文章中已经介绍了routes里面RibbonRoutingFilter和SimpleHostRoutingFilter的配置使用。
1、RibbonRoutingFilter核心的配置点是serviceId
yaml设置:
zuul:
routes:
provider2:
path: /mysuibian/**
serviceId: service-sms
因为在其shouldFilter方法里面核心对这个进行了判断:
在执行context封装的时候,会将serviceId中的内容,封装到SERVICE_ID_KEY中。
2、SimpleHostRoutingFilter核心配置就是path+url,并且url是目标服务的ip+端口号
yaml配置:
zuul:
routes:
##配置path+url 走SimpleHostRoutingFilter 跳转到指定的 URL 中
# 使用 http://localhost:9100/mytttttt/send/msg 可以访问
##provider1这个名称随便写
provider1:
path: /mytttttt/**
url: http://localhost:8001/
其源码判断逻辑:
在执行context封装的时候,会将url中的内容,封装到routeHost中。
3、SendForwardFilter
那么还有一个routes类型的filter,就是SendForwardFilter,这个filter是实现跳转,但这个跳转是对自己服务的url跳转,所以用处不是很大。具体使用可以通过path+url,并且url是forward:/格式才行。yaml配置如下:
zuul:
routes:
# path+url 并且url中配置forward:/ 会走SendForwardFilter,这个是对当前自身服务url的跳转
provider4:
path: /forward1/**
url: forward:/test
这样会在访问http://网关ip:网关端口/forward1 的时候会跳转到网关的/test接口。如果网关没有/test接口,会404。
如果访问的是/forward1/xx/xx, 那么会访问网关的/test/xx/xx接口,如果网关无此接口会404。
SendForwardFilter的shouldFilter判断逻辑源码:
在执行context封装的时候,会判断url中有没有forward:,如果有将forward:后面配置的信息替换掉请求的url中path设置的“/forward1”,将替换后的url封装到FORWARD_TO_KEY中。
举个例子:
如果配置的path是 /forward1/v/**,url配置的是forward:/test,(注意forward:后面不能跟空格)
那么访问http://localhost9100/forward1/v 等同于访问 http://localhost9100/test
如果访问http://localhost9100/forward1/v/send/msg 等同于访问 http://localhost9100/test/send/msg
意思就是将url的forward:后面的内容,全部替换为 path里面除了/**之外的内容。
如果访问http://localhost9100/forward1 会报404,因为没有这样的path匹配,配置文件中没有,eureka中也没有。
4、另外还可以通过自己写Filter继承ZuulFilter来实现各种routes规则。具体就不展示了