preface

Because of the microservices architecture, the project needed to have a unified entry point, so the gateway was developed. In this project, the gateway is used for authentication, logging, traffic limiting, and forwarding.

Based on IP flow limiting filter

Limited flow filter configuration

spring:
  cloud:
    gateway:
      routes:
        - id: request_rate_limiter_route
          predicates:
            - Path=/**
          filters:
            - name: RequestRateLimiter
              args:
                denyEmptyKey: true
                emptyKeyStatus: SERVICE_UNAVAILABLE
                keyResolver: '#{@ipAddressKeyResolver}'
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20
          uri: http://127.0.0.1:8888
Copy the code

Where ‘#{@ipAddressKeyResolver}’ specifies the use of a custom ipResolver.

IpAddressKeyResolver implementation

/** * Description: Ip request limiter **@author xhsf
 * @create2020/11/25 15:04 * /
@Service
public class IpAddressKeyResolver implements KeyResolver {
    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        returnMono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()); }}Copy the code

Rely on

The flow-limiting filter is implemented using Redis, so you need to import Redis dependencies and configure the account password URL.

		<! -- Redis -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
		</dependency>
Copy the code