SpringCloud Series Gateway (Gateway) Application

@

Foreword

Since the project uses a microservices architecture, business functions are in their respective modules. Each business module is run as an independent project and provides its own service interface. If there is no component like a gateway, the corresponding Power, current limit and other functions can not be unified configuration and management, everything is so elegant after the gateway. It just happens that the Spring Cloud Gateway component is used as the gateway in the new project, so record the commonly used configuration in the project.

Project version

spring-boot-version:2.2.5.RELEASE
spring-cloud.version:Hoxton.SR3

Gateway access

The sample project still continues the original sample code of the SpringCloud series, and the introduction of the gateway only requires the addition of the spring-cloud-gateway project.
Core pom.xml (see sample source code for details, at the end of the article)

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

bootstrap.yml

server:
  port: 9005
spring:
  application:
    name: springcloud-gateway-service
  cloud:
    config:
      discovery:
        enabled: true
        service-id: config-server
      profile: dev
      label: master
    gateway:
      enabled: true  #开启网关
      discovery:
        locator:
          enabled: true #开启自动路由,以服务id建立路由,服务id默认大写
          lower-case-service-id: true #服务id设置为小写
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9003/eureka/

ApiGatewayApplication.java

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

Visit the interface provided by the original spring-cloud-system-server module
http: // localhost: 9004 / web / system / getEnvName

Access through the gateway
http: // localhost: 9005 / system-server / web / system / getEnvName

If the request can be returned normally, it means that the gateway component has been integrated. Isn't it very simple? One line of configuration items is done, which is convenient to show that the properties configuration method is used here.

spring.cloud.gateway.discovery.locator.enabled=true

The basic configuration application to this gateway has been completed. The format of the request path for access through the gateway is as follows
: http: // gateway address : gateway port / respective service id / URL access provided by the respective service

Authentication configuration

Here, the spring-cloud-system-server module is introduced into the spring security security authentication component, and the code is added.
pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

application.properties

spring.security.user.name=test
spring.security.user.password=123456

After adjusting the service module, restart the module and access the external request interface. The authentication login interface appears indicating that the configuration is successful.
http: // localhost: 9004 / web / system / getEnvName

After entering the username and password configured in the above configuration items, the interface request returns to normal.

Request the gateway address, when you press the Enter key to access the service interface, it will jump to the service project authentication page, as follows
http: // localhost: 9005 / system-server / web / system / getEnvName

Next, adjust the gateway module accordingly
bootstrap.yml

spring:
  application:
    name: springcloud-gateway-service
  security:
    user:
      name: test
      password: 123456

Added
SecurityBasicAuthorizationFilter.java

@Component
public class SecurityBasicAuthorizationFilter implements GlobalFilter, Ordered {

    @Value("${spring.security.user.name}")
    private String username;
    @Value("${spring.security.user.password}")
    private String password;

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String auth = username.concat(":").concat(password);
        String encodedAuth = new sun.misc.BASE64Encoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " +encodedAuth;
        //headers中增加授权信息
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().header("Authorization", authHeader).build();
        ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
        return chain.filter(build);
    }
    /**
     * 优先级
     * 数字越大优先级越低
     * @return
     */
    public int getOrder() {
        return -1;
    }
}

Restart the gateway project, re-access the service address, and return to normal data. This means that it is best to open a new incognito window or clear the browser cache before testing. Otherwise, the session cache will cause the illusion that the security certification does not take effect.
http: // localhost: 9005 / system-server / web / system / getEnvName
Insert picture description here

Current limit configuration

SpringCloud Gateway has its own current limiting function, but based on redis, in this simple demonstration, the open source sentinel of Ali is not used in the project. The integrated sentinel component will be introduced later.
pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>

bootstrap.yml

spring:
  cloud:
    gateway:
      enabled: true  #开启网关
      discovery:
        locator:
          enabled: true #开启自动路由,以服务id建立路由,服务id默认大写
          lower-case-service-id: true #服务id设置为小写
      routes:
        - id: baidu_route
          uri: https://www.baidu.com/
          predicates:
          - Path=/baidu/**
          filters:
            - name: RequestRateLimiter
              args:
                key-resolver: "#{@apiKeyResolver}"
                redis-rate-limiter.replenishRate: 1 #允许每秒处理多少个请求
                redis-rate-limiter.burstCapacity: 5 #允许在一秒钟内完成的最大请求数
   redis:
    host: 192.168.28.142
    pool: 6379
    password: password
    database: 1              

RequestRateLimiterConfig.java

@Configuration
public class RequestRateLimiterConfig {
    @Bean
    @Primary
    public KeyResolver apiKeyResolver() {
        //URL限流,超出限流返回429状态
        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    }
}

Restart the gateway project, access the following request address, and request to jump to the Baidu home page. The current configuration item is configured to request 5 times within 1s. If more than 5 times, the current limit will be triggered, and the 429 status code will be returned. The following page
http: // localhost: 9005 / baidu / test

View redis information in real time through the monitor command

Directory structure of this gateway project

The same series of articles
1-SpringCloud series configuration center (Config) instructions
2-SpringCloud series service registration discovery (Eureka) application article
sample source code

Guess you like

Origin www.cnblogs.com/chinaWu/p/12731796.html