Explain the current limiting operation of spring cloud gateway in detail
When developing high concurrency systems, there are three sharp tools to protect the system: caching, degradation and current limiting.
API gateway serves as the entrance of all requests, with a large number of requests. We can limit the speed of concurrent access requests to protect the availability of the system.
Common current limiting algorithms include token bucket algorithm, leaky bucket algorithm, counter algorithm, etc.
In zuul, we can implement the function of current limiting by ourselves (how to limit current in zuul is explained in detail in my book spring cloud microservices - full stack technology and case analysis). The emergence of spring cloud gateway itself is used to replace zuul.
To replace it, it must have powerful functions. In addition to the performance advantages, spring cloud gateway also provides many new functions. For example, the current limiting operation we want to talk about today is very simple to use. Today, we'll learn how to limit current in spring cloud gateway.
At present, redis based implementation is provided for current limiting, and we need to add corresponding dependencies:
You can specify the current limiting key through keyresolver. For example, we need to limit the current according to the user, IP, etc.
IP current limiting
The request information can be obtained through the exchange object. The hostname is used here. If you want to limit the flow according to the user, you can obtain the user ID or user name of the current request, such as:
User current limiting
To limit the current in this way, the userid parameter must be carried in the request path.
Interface current limiting
Obtain the URI of the request address as the current limiting key.
Then configure the current limiting filter information:
You can access the interface for testing. At this time, there will be corresponding data in redis:
127.0. 0.1:6379> keys * 1) "request_rate_limiter.{localhost}.timestamp" 2) "request_rate_limiter.{localhost}.tokens"
In the braces are our current limiting key, here is IP, and the local is localhost
The current restriction provided by spring cloud gateway is relatively simple. In practice, there are many situations in our current restriction strategy, such as:
Of course, we can also implement our own current limiting strategy by redisratelimiter, which will be introduced later.
Current limiting source code
Lua script in:
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.