In the SpringCloud GateWay routing and forwarding rules introduction article, we explained the assertions and predicates provided by the SpringCloud GateWay, which allow us to combine more precise business scenarios for requests. Since SpringCloud GateWay plays the role of GateWay, Zuul can automatically forward by service name before, can SpringCloud GateWay implement automatic forwarding?

Initialize the Gateway service

The Spring Cloud Gateway can forward the packets according to the configured assertions and predicates. It can also automatically synchronize the service list in the service registry to specify the serviceId prefix. ServiceId is the spring. Application. Name configuration parameter of the business service.

SpringCloud version control dependencies

Add the SpringCloud version dependency to pom.xml as follows:

/ /...<properties>
  <java.version>1.8</java.version>
  <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<! --Spring Cloud version Control -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>/ /...Copy the code

In this chapter, we use Eureka as the service registry to complete the service request forwarding instruction. We need to register the Spring Cloud Gateway Gateway project with Eureka Server as a Client. First, we take a look at the added dependency, pom.

/ /...<dependencies>
  <! --Spring Cloud Gateway-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
  </dependency>
  <! --Eureka Client-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  </dependency>
</dependencies>
//....
Copy the code

Then we need to enable the discovery configuration of the Gateway service registry to automatically synchronize the service list of the service registry. The application. Yml configuration file is as follows:

# service name
spring:
  application:
    name: spring-cloud-gateway
  Enable Gateway service registry service discovery
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
# Eureka Server configuration
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10000/eureka/
Configure the Gateway log level to output the forwarding details
logging:
  level:
    org.springframework.cloud.gateway: debug
Copy the code

The configuration parameters are described as follows:

  • spring.application.name: the service name
  • spring.cloud.gateway.discovery.locator.enabledOpen:SpringCloud GatewayRegistry discovery configuration, enabled to automatically pull the list of services from the service registry, through each servicespring.application.nameForwarding as a prefix. The default value isfalse.
  • eureka.client.service-url.defaultZoneConfiguration:Eureka ServerDefault spatial address
  • logging.level.org.springframework.cloud.gatewaySet:SpringCloud GatewayThe log level isdebugIs used to output detailed logs for forwarding, facilitating the view of detailed processes.

Register gateway to Eureka

Add the corresponding annotation to the entry class to enable automatic service registration, as shown below:

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudGatewayApplication {
    public static void main(String[] args) { SpringApplication.run(SpringCloudGatewayApplication.class, args); }}Copy the code

Service Registry

Corresponding to the address of Eureka Server configured by the gateway above, we need to add the corresponding configuration, pom.xml as follows:

/ /...<dependencies>
  <! --Eureka Server-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  </dependency>
</dependencies>/ /...Copy the code

After adding dependencies, configure Eureka Server. The configuration file application.yml is as follows:

# service name
spring:
  application:
    name: sample-eureka-server
# port
server:
  port: 10000

# Eureka configuration information
eureka:
  client:
    service-url:
      defaultZone: http://localhost:${server.port}/eureka/
    fetch-registry: false
    register-with-eureka: false
Copy the code

Here we change the default port number to 10000, in order to match the configuration information in the gateway project, as for the fetch-registry, register-with-Eureka can be seen in my previous article, SpringCloud component: Registering service providers to eureka cluster

Open the Eureka Server

We start the service with the @enableeurekaserver annotation, as follows:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); }}Copy the code

Now that we have the Gateway and service registry in place, we can write a business logic service to verify that SpringCloud Gateway can forward requests based on serviceId.

Single service

We simply write a GET request address, output string information, and pom.xml add dependency as follows:

<dependencies>
  <! --Web-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <! --Eureka Client-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  </dependency>
</dependencies>
Copy the code

The configuration file application.yml looks like this:

# service name
spring:
  application:
    name: user-service
# Register with Eureka
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10000/eureka/
# Service port number
server:
  port: 9090

Copy the code

Set the service name to user-service, which corresponds to the serviceId of the SpringCloud Gateway.

Register services to Eureka

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class UserServiceApplication {
    /** * logger instance */
    static Logger logger = LoggerFactory.getLogger(UserServiceApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
        logger.info("「「「「「 User service startup complete. 」」」」」");
    }

    @GetMapping(value = "/index")
    public String index(a) {
        return "this is user index"; }}Copy the code

User-service provides the requested address of /index. When accessing the user, this is user index is output.

Test service request forwarding

Next, we verify, and the test sequence is as follows:

Step 1: Start Eureka Server

Step 2: Start the SpringCloud Gateway

After successful startup, the console will print the log information of registering to Eureka, as shown below:

DiscoveryClient_SPRING - CLOUD - GATEWAY / 192.168.1.56: spring -- CLOUD - GATEWAY: registering service... Netty started on port(s): 8080Copy the code

The SpringCloud Gateway internally forwards requests to the WebServer through Netty.

Step 3: Start the user-service service

After successful startup, the console prints the corresponding registration log, as shown below:

DiscoveryClient_USER - SERVICE / 192.168.1.56: user - SERVICE: 9090: registering SERVICE... Tomcat started on port(s): 9090 (http) with context path' '
Copy the code

Step 4: Test access

The SpringCloud Gateway redefines routes after pulling down the service list every 30 seconds. The log information is as follows:

# Spring Cloud GatewayRouteDefinition CompositeDiscoveryClient_SPRING-CLOUD-GATEWAY applying {pattern=/SPRING-CLOUD-GATEWAY/**} to Path RouteDefinition CompositeDiscoveryClient_SPRING-CLOUD-GATEWAY applying filter {regexp=/SPRING-CLOUD-GATEWAY/(? <remaining>.*), replacement=/${remaining}} to RewritePath
RouteDefinition matched: CompositeDiscoveryClient_SPRING-CLOUD-GATEWAY
# User ServiceRouteDefinition CompositeDiscoveryClient_USER-SERVICE applying {pattern=/USER-SERVICE/**} to Path RouteDefinition CompositeDiscoveryClient_USER-SERVICE applying filter {regexp=/USER-SERVICE/(? <remaining>.*), replacement=/${remaining}} to RewritePath
RouteDefinition matched: CompositeDiscoveryClient_USER-SERVICE
Copy the code

From the above log information we can already infer that the SpringCloud Gateway maps the value of Spring.application. name as the service path prefix, but in uppercase, Expect we can through the http://localhost:8080/USER-SERVICE/index access to the corresponding information.

The access tests are as follows:

~ curl http://localhost:8080/USER-SERVICE/index
this is user index
Copy the code

The format for accessing services through the gateway is http://gateway IP: gateway port number /serviceId/**

Multi-service load balancing

ifEureka ServerTwo of them are the sameserviceIdThe service of,SpringCloud GatewayLoad balancing is automatically completed.

Copy a user-service instance and change the service port number as follows:

# service name
spring:
  application:
    name: user-service
# Eureka Server
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10000/eureka/
# Service port number
server:
  port: 9091
Copy the code

Use the same spring.application.name in the replicated project to keep the serviceId consistent and only change the port number. To distinguish between GateWay load balancing, we change the return content of /index request as follows:

@GetMapping(value = "/index")
public String index(a) {
  return "this is user lb index";
}
Copy the code

Go to http://localhost:8080/USER-SERVICE/index, the output content is as follows:

this is user lb index
this is user index
this is user lb index
this is user index
...
Copy the code

conclusion

In this chapter, we have a simple understanding of SpringCloud Gateway’s forwarding. After pulling the service list from the service registry, it will automatically map the path prefix according to the serviceId, and load balancing will be automatically implemented when the service with the same name has multiple instances.

Source location

Gitee:gitee.com/hengboy/spr…

ApiBoot:gitee.com/hengboy/api… , github.com/hengboy/api…