Naresh Bharadwaj
Naresh Bharadwaj

Reputation: 302

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.

-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. I understand it is not correct approach but for my knowledge I wanted to know whether it is possible or not.

Upvotes: 8

Views: 7625

Answers (2)

Poison
Poison

Reputation: 409

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:

@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;
    }

}

Upvotes: 2

Dhananjay
Dhananjay

Reputation: 1225

If you have some rest APIs within your spring-cloud-gateway project, you don't need to explicitly put the routes for it. So suppose you have following rest api in gateway project

@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. So in gateway application.yml could look something like this:

spring:
  cloud:
    gateway:
      routes:
        - id: httpbin-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/status/200 will be redirected to httpbin site

If for some reason you have the same root path for both cases, the controller will have precedence.

Upvotes: 2

Related Questions