SpringCloud using Zuul restrictor (Zuul + Ratelimit)

The development of micro-services API to do sometimes need to limit protection against network attacks, such as making a verification code SMS API, the client's request rate limit can withstand an SMS to a certain extent bombing attack, reduce losses. Micro gateway service must pass through the entrance of each request, very suitable for some of the API limit, like how to operate the certification, this article describes Zuul limit the current operation of the Zuul do not understand can refer to my article: SpringCloud component of Zuul

A, Ratelimit configuration Introduction

1, limiting policy

Limiting particle size / type Explanation
Authenticated User Use the user name authenticated or "anonymous"
Request Origin Using the user's original request
URL Use service request path downstream
ROLE Using an authenticated user roles
Request method Using the HTTP request method
Global configuration per service This does not validate the request Origin, Authenticated User, or URI, to use this, do not set type

2, available implementations

Storage Type Explanation
consul Based consul
repeat Based redis, dependent correlation must be introduced using redis
JPA Based SpringDataJPA, need to use a database
MEMORY Based on local memory, default
BUKET4J Based token bucket algorithm limiting a library written in Java

Bucket4j achieve bean @Qualifier ( "RateLimit") relevant to the needs of :

  • JCache - javax.cache.Cache
  • Hazelcast - com.hazelcast.core.IMap
  • Ignite - org.apache.ignite.IgniteCache
  • Infinispan - org.infinispan.functional.ReadWriteMap

3, common configuration properties

Property name value Defaults
enabled true/false false
behind-proxy true/false false
add-response-header true/false false
key-prefix string ${spring.application.name:rate-limit-application}
repository CONSUL, REDIS, JPA, BUCKET4J_JCACHE, BUCKET4J_HAZELCAST, BUCKET4J_INFINISPAN, BUCKET4J_IGNITE -
default-policy-list list-of-policy -
policy-list Map of Lists of Policy -
postFilterOrder int FilterConstants.SEND_RESPONSE_FILTER_ORDER - 10
preFilterOrder int FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER

policy relevant attributes

Property name value Defaults
limit number of calls -
quota time of calls -
refresh-interval seconds 60
type [ORIGIN, USER, URL, ROLE] []

4, how to handle the error occurred

  @Bean
  public RateLimiterErrorHandler rateLimitErrorHandler() {
    return new DefaultRateLimiterErrorHandler() {
        @Override
        public void handleSaveError(String key, Exception e) {
            // custom code
        }

        @Override
        public void handleFetchError(String key, Exception e) {
            // custom code
        }

        @Override
        public void handleError(String msg, Exception e) {
            // custom code
        }
    }
  }

Second, build Zuul combined Ratelimit Service

1, import-dependent

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
    <groupId>com.marcosbarbero.cloud</groupId>
    <artifactId>spring-cloud-zuul-ratelimit</artifactId>
    <version>2.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2, start the class labeling solution

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

3, the configuration file

server:
  port: 8080
spring:
  application:
    name: zuul-ratelimit
  redis:
    host: localhost
    password: 
zuul:
  # 配置路由
  routes:
    demo:
      path: /demo/**
      serviceId: demo
  # 配置限流
  ratelimit:
    enabled: true
    # 对应存储类型(用来统计存储统计信息)
    repository: redis
    # 配置路由的策略
    policy-list:
      demo:
        # 每秒允许多少个请求
        - limit: 2
          # 刷新时间(单位秒)
          refresh-interval: 1
          # 根据什么统计
          type:
            - url

4, after starting a visit

Since we only allowed one second configuration of the two requests, when we exceeded, an exception will be thrown too many requests

error

This paper came to an end, more knowledge can go: the Spring-Cloud-Zuul-ratelimit , this demo Address: SpringCloud-Demo

Guess you like

Origin yq.aliyun.com/articles/707059