Spring Cloud Gateway uses simple configuration

Keywords: Spring Netty

Basic use of Spring Cloud Gateway

Spring Cloud Gateway is the second generation gateway framework officially launched by Spring Cloud, replacing Zuul gateway. Gateway as a traffic, plays a very important role in micro service system. The common functions of gateway include routing and forwarding, authority verification, current limiting control and so on.

Source code

Project structure
Project port description
Registration and discovery of Eureka server 8761 service
Service one 8081 service
Gateway client 8080 gateway
eureka-server
The Eureka server project is very simple to introduce

<dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

In the startup class

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

configuration file

spring:
  application:
    name: eureka-server

server:
  port: 8761
eureka:
  instance:
    hostname: localhostname
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:8761/eureka/
service-one project

It's very simple to build. Add dependencies

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

In the startup class

@EnableEurekaClient
@SpringBootApplication
public class ServiceOneApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceOneApplication.class, args);
    }
}

configuration file

spring:
  application:
    name: service-one
server:
  port: 8081

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
//Create the class controller UserController, http://localhost:8081/user/who

@RequestMapping("/user")
@RestController
public class UserController {

    @RequestMapping("who")
    public String who() {
        return "my name is liangwang";
    }
}
//Create the class controller OrderController, http://localhost:8081/order/info

@RequestMapping("/order")
@RestController
public class OrderController {

    @RequestMapping("/info")
    public String orderInfo() {
        return "order info date : " + new Date().toString();
    }
}

Gateway client project
Using Finchley.SR2 Version of, which already includes spring boot starter webmix
Add dependency

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

The Bean of RouteLocator is used for routing and forwarding. The request is processed and finally forwarded to the downstream service of the target

@SpringBootApplication
public class GatewayClientApplication {

@Value("${test.uri}")
private String uri;

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/order/**")
.uri(uri)
).build();
}

public static void main(String[] args) {
SpringApplication.run(GatewayClientApplication.class, args);
}
}
In the code above, we are accessing http://localhost:8080/order /, the gateway forwards to http://service-one:8081/order /, the service one service is registered in eureka, and finally it is the ip:port of the corresponding service

Use profile

application.yml

test:
  uri: lb://service-one
spring:
  application:
    name: gateway-client
  cloud:
    gateway:
      routes:
      - id: route_service_one
        uri: ${test.uri} # uri starts with lb: / / (lb stands for getting service from registry), followed by the name of the service you need to forward to
        predicates:
        - Path=/user/**

server:
  port: 8080

logging:
  level:
    org.springframework.cloud.gateway: TRACE
    org.springframework.http.server.reactive: DEBUG
    org.springframework.web.reactive: DEBUG
    reactor.ipc.netty: DEBUG
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
//among test.uri It is a user-defined property. The URI starts with lb / / (LB stands for getting services from the registry), followed by the name of the service you need to forward to. According to the above configuration, the http://localhost :8080/usr/** =>  http://service-one : 8081 / user / * * this project is built. Next, test it and start Eureka server, service one and gateway client in turn
//visit

http://localhost:8080/user/who
http://localhost:8080/order/info
WX20181113-180248@2x.png
WX20181113-180339@2x.png
Do not enable registry
Even if Eureka client is integrated, you don't want to use the registry service. You can close it

eureka.client.enabled=false
Use of StripPrefix property
According to the above configuration, each route can only correspond to the forwarding of one controller, which is not flexible enough. If I want to transfer the requests of the user API to the service one service, for example:

http://localhost:8080/userapi/user/who => http://localhost:8081/user/who
http://localhost:8080/userapi/order/info => http://localhost:8081/order/info
Add StripPrefix=1 to the routing configuration
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${ test.uri }The URI starts with lb: / / (lb stands for getting the service from the registry), followed by the name of the service you need to forward to
predicates:
- Path=/userapi/**
filters:
-StripPrefix=1 ා indicates that the user API is removed when forwarding
After modifying the configuration, restart the gateway client project

Using Hystrix
Introducing dependencies into gateway client projects

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>

Hystrix can be used in spring cloud gateway. Hystrix is a service degradation component in spring cloud, which plays an important role in microservice system.
Hystrix is used in spring cloud gateway in the form of filter. The code is as follows:

@SpringBootApplication
public class GatewayClientApplication {

@Value("${test.uri}")
private String uri;

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            //basic proxy
            .route(r -> r.path("/order/**")
                    .uri(uri)
            )
            .route(r -> r.path("/user/**")
                    .filters(f -> f
                            .hystrix(config -> config
                                    .setName("myserviceOne")
                                    .setFallbackUri("forward:/user/fallback")))
                    .uri(uri)).build();
}

public static void main(String[] args) {
    SpringApplication.run(GatewayClientApplication.class, args);
}

}
The above code adds a route and configures the fallbackUri of hystrix, and adds a FallBackController controller

@RestController
public class FallBackController {
@RequestMapping("/user/fallback")
public Mono fallback() {
return Mono.just("service error, jump fallback");
}
}
Restart the gateway client project, close the service one service, and access it in the browser http://localhost:8080/user/who

Configuring Hystrix with yml

spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${ test.uri }The URI starts with lb: / / (lb stands for getting the service from the registry), followed by the name of the service you need to forward to
predicates:
- Path=/userapi/**
filters:
-StripPrefix=1 ා indicates that the user API is removed when forwarding

  - id: userapi2_route
    uri: ${test.uri}
    predicates:
    - Path=/userapi2/**
    filters:
    - StripPrefix=1
    - name: Hystrix
      args:
        name: myfallbackcmd
        fallbackUri: forward:/user/fallback

A new route, userapi2, has been added to the configuration_ Route is also configured with Hystrix. When an error occurs, it will be forwarded to fallbackUri for test access http://localhost:8080/userapi2/order/info

Posted by POGRAN on Mon, 29 Jun 2020 20:10:52 -0700