spring cloud gateway microservice gateway

Posted by frenchpl on Wed, 29 Dec 2021 23:18:25 +0100

Recently, I am also writing a distributed project of microservices, which will use the springcloud gateway. Here I share some simple knowledge with you.

handout

First, we have to understand the concept of microservice gateway. In our microservice projects, different services may have different network addresses. However, when the client completes a business requirement, it may need to call the interfaces of multiple services to complete a business requirement. Therefore, there will be many problems when the client communicates directly with each service. These problems can be well solved by using the gateway.

Generally speaking, the gateway is a thing between the client and the server. All external requests need to go through the gateway and then allocate the requested services. Microservice gateway is a system. By exposing the microservice gateway system, it is convenient for us to perform authentication, security control, log unified processing and other operations

Spring cloud gateway is a concrete implementation of microservice gateway.

Microservice gateway construction

step

In fact, the implementation is also very simple

Step 1: introduce dependency

Step 2: write a startup class

Step 3: configure the application file yml

Step 4. Write our two filters, IpFilter and UrlFilter

Schema / directory

 

realization

Introduce dependency

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

Startup class

Because gateway itself is also a service, we need to register with our registry. Here we need to have service discovery annotations. This time, the service discovery framework I use is Eureka, so the annotation is @ EnableEurekaClient. If other partners use other registries, such as nacos, they can be replaced with other annotations. For example, @ EnableDiscoveryClient

/**
 * Service gateway startup class
 * @author: shenwang
 * Date: 2021/8/8
 */
@SpringBootApplication
@EnableEurekaClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class,args);
    }
}

application.yml

spring:
  application:
    name: sysgateway #service name
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]': # Match all requests
            allowedOrigins: "*" #Cross domain processing allows all domains
            allowedMethods: # Supported methods
              - GET
              - POST
              - PUT
              - DELETE
      routes:
        - id: goods #Routing id
          uri: lb://goods # because load balancing is required, the service name is used
          predicates:
            - Path=/goods/** #Asserts that the path needs to be matched for routing
          filters:
            - StripPrefix= 1
        - id: system
          uri: lb://system
          predicates:
            - Path=/system/**
          filters:
            - StripPrefix= 1
server:
  port: 9101 #Gateway port number
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:6868/eureka
  instance:
    prefer-ip-address: true

Filter (IpFilter, UrlFilter)

IpFilter code implementation:

/**
 * @author: shenwang
 * Date: 2021/8/8
 */
@Component
public class IpFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("Pass through the 1st filter IpFilter");

        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();

        System.out.println("ip:"+remoteAddress.getHostName());

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

UrlFilter code implementation:

/**
 * @author: shenwang
 * Date: 2021/8/8
 */
@Component
public class UrlFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        System.out.println("Through the second filter UrlFilter");

        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();

        System.out.println("url:"+url);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}

Here, we have finished building a simple microservice gateway~

Of course, there are many knowledge points behind, such as gateway current limiting, password encryption, authentication and other operations, which I will share with you later

Recently, the epidemic situation is quite serious. For your safety and everyone's safety, try to reduce going out. You must also remember to wear a mask when you go out~

                ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​

Topics: Spring Cloud