Spring Cloud Api gateway basics
- Mark Kendall
- Mar 1
- 3 min read
Alright, let's craft a simple Spring Cloud Gateway application with some basic route locator beans. We'll start with a "Hello, World!" example and then add a few more common routing scenarios.
1. Basic "Hello, World!" Route
```java
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Configuration
public class SimpleGatewayConfig {
@Bean
public RouteLocator basicRoute(RouteLocatorBuilder builder) {
return builder.routes()
.route("hello_route", r -> r.path("/hello")
.filters(f -> f.rewritePath("/hello", "/api/hello")) // optional: rewrite the path
.uri("http://localhost:8081")) // Replace with your service's URI
.build();
}
@Bean
public RouterFunction<ServerResponse> helloHandler() {
return RouterFunctions.route(RequestPredicates.GET("/api/hello"),
request -> ServerResponse.ok().body(Mono.just("Hello, World!")));
}
}
```
Explanation:
*`@Configuration`:** Marks this class as a configuration class.
*`RouteLocator basicRoute(RouteLocatorBuilder builder)`:**
* This method creates a `RouteLocator` bean.
* `builder.routes()` starts the definition of routes.
* `.route("hello_route", ...)` defines a route with an ID "hello\_route".
* `.path("/hello")` matches requests with the path `/hello`.
* `.filters(f -> f.rewritePath("/hello", "/api/hello"))` optional, rewrites the path from `/hello` to `/api/hello` before forwarding.
`.uri("http://localhost:8081")` forwards the request to the specified URI. *Replace this with the actual URI of your service.**
*`RouterFunction<ServerResponse> helloHandler()`:**
* This is a webflux router function. It will respond with "Hello, World!" when a GET request is sent to /api/hello.
* If you don't have a service running on port 8081, this will allow you to test.
* If you want to remove this, and only use the routing, then remove this entire method.
2. Routing Based on Host
```java
@Bean
public RouteLocator hostRoute(RouteLocatorBuilder builder) {
return builder.routes()
.route("host_route", r -> r.host("*.example.com")
.uri("http://localhost:8082")) // Replace with your service's URI
.build();
}
```
* This route matches requests with a host that ends in `example.com`.
* It forwards the request to `http://localhost:8082`.
3. Routing Based on Multiple Predicates
```java
@Bean
public RouteLocator multiPredicateRoute(RouteLocatorBuilder builder) {
return builder.routes()
.route("multi_route", r -> r.path("/api/**")
.and().method("GET")
.uri("http://localhost:8083")) // Replace with your service's URI
.build();
}
```
* This route matches requests with paths starting with `/api/` and the HTTP GET method.
* It forwards the request to `http://localhost:8083`.
To deploy and test:
1. Create a Spring Boot project: Use Spring Initializr or your IDE. Add the Spring Cloud Gateway dependency.
2. Create the `SimpleGatewayConfig` class: Copy the code into your project.
3. Configure `application.properties` or `application.yml`:
* Set the `server.port` if you want a port other than 8080.
4. Run the application: Start the Spring Boot application.
5. Test the routes:
* Send requests to `http://localhost:8080/hello` (or the port you configured).
* If you kept the helloHandler, send a request to `http://localhost:8080/api/hello`.
* Send requests to `http://your-subdomain.example.com:8080` (if you configured DNS or use a hosts file).
* Send GET requests to `http://localhost:8080/api/some-path`.
Important:
* Replace `http://localhost:8081`, `http://localhost:8082`, and `http://localhost:8083` with the actual URIs of your backend services.
* If you do not have backend services running, the helloHandler method will allow you to test the gateway.
* If you do have backend services, delete the helloHandler method.
* Ensure the services at those URIs are running and accessible.
* If you have a DNS server, or are using a hosts file, you can test the host based routing.
Comentarios