简体   繁体   English

Spring 云网关作为网关以及 web 应用

[英]Spring Cloud Gateway as a gateway as well as web application

I have a spring cloud gateway application and what I want is like if there are two routes then on one route it should redirect to some external application but for other route it should forward the request to same app with a particular url.我有一个 spring 云网关应用程序,我想要的是,如果有两条路由,那么在一条路由上它应该重定向到某个外部应用程序,但对于其他路由,它应该将请求转发到具有特定 url 的同一个应用程序。

-id: my_local_route
 predicates:
   - Path="/services/local"
 uri: "/mylocal/services/local" //can we do something like that

Please note I want to create my rest services in same app as in spring cloud gateway.请注意,我想在与 spring 云网关相同的应用程序中创建我的 rest 服务。 I understand it is not correct approach but for my knowledge I wanted to know whether it is possible or not.我知道这不是正确的方法,但据我所知,我想知道这是否可能。

If you have some rest APIs within your spring-cloud-gateway project, you don't need to explicitly put the routes for it.如果您的 spring-cloud-gateway 项目中有一些 rest API,则无需显式为其放置路由。 So suppose you have following rest api in gateway project因此,假设您在网关项目中有以下 rest api

@RestController
@RequestMapping("test")
class Controller{
    @GetMapping("hello")
    public String hello(){
        return "hello";
    }
}

and for external-url, you want to send some traffic to let's say https://httpbin.org .对于 external-url,您想发送一些流量到https://httpbin.org So in gateway application.yml could look something like this:所以在网关 application.yml 可能看起来像这样:

spring:
  cloud:
    gateway:
      routes:
        - id: websocket-sockjs-route
          uri: https://httpbin.org
          predicates:
            - Path=/status/**

With this request like有了这个请求

  • http://localhost:8080/test/hello will be resolved by your rest controller http://localhost:8080/test/hello将由您的 rest controller 解决
  • http://localhost:8080/status/200 will be redirected to httpbin site http://localhost:8080/status/200将被重定向到 httpbin 站点

If for some reason you have the same root path for both cases, the controller will have precedence.如果由于某种原因您在两种情况下都有相同的根路径,则 controller 将具有优先权。

If you have the same endpoint in gateway predicates and controller, by default controller will take precedence over predicates, if you want predicates to take precedence over controller, just create a BeanPostProcessor to adjust the order:如果您在网关谓词和 controller 中具有相同的端点,默认情况下 controller 将优先于谓词,如果您希望谓词优先于 Z594C103F2C6E04C3D8AB059F031

@Component
public class RequestMappingHandlerMappingBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RequestMappingHandlerMapping) {
            ((RequestMappingHandlerMapping) bean).setOrder(2); // After RoutePredicateHandlerMapping
        }
        return bean;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM