Search code examples
spring-bootconsulspring-cloud-gateway

How to specify a route in a spring boot application?


I am working on a spring boot application and have specified the following properties in the application.yml file:

server:  
  port: 8000
spring:
  application:
    name: "ai-gy"  

So this will register the current application as "ai-gy" in consul. I want to achieve the following for this application:
Add the route "/tran" and route it to "po-ms". The prefix for the route should be "ai"
"po-ms" is the name of another project which is registered with consul.
I am not sure what property changes in the current application.yml I can make to achieve this or do I have to write some spring code or do something in consul

I do see the following configurations in some places:

spring:
  cloud:
    gateway:
      routes:

But I am not completely sure where to specify /tran po-ms and the prefix ai
The intention is that a call to HTTP://localhost:8000/ai/tran/1001 should be routed to HTTP://localhost:2222/tran/1001
The po-ms service is running on port 2222


Solution

  • You can do this with just yaml config.

    Here is the config:

    
    spring:
      cloud:
        gateway:
          routes:
            - id: tran-route
              uri: http://localhost:2222
              predicates:
                - Path=/ai/**
              filters:
                - RewritePath=/ai(?<segment>/?.*), /$\{segment}
    

    The RewritePath is to rewrite the URL to remove /ai path when forwarding the request to the downstream service.