Bucket algorithm

Put the flow into the leakage bucket, the leakage bucket at a certain rate of water, when the incoming flow is greater than the discharge flow, excess water will be stored in the bucket, forced to limit the flow request

Bucket capacity: maximum number of concurrent requests. If the bucket is full, subsequent requests cannot be stored in the bucket and excess requests are discarded.

This is similar to the idea of using message queue peaking. Using queue consumption rate, the produced messages are consumed at a steady rate, and more messages are stored in the queue for consumption.

Disadvantages: Cannot face the burst of large traffic. Once the bucket exceeds the upper limit, all other requests are rejected.

Ideas:

1. Before entering the bucket, check whether the bucket is full. If no, enter the bucket

2. Refresh the real-time capacity and refresh time of the bucket

Simple manual thread testing

1. Define constants

  • The maximum capacity
  • Discharge rate
  • Current time (used to determine if the request is accessible)
  • Update time (when refreshing at a specified time, the current time minus the last update time is required to determine how many requests have flowed out)

The Controller to achieve

When the initialization enters the first request, you need to refresh the update time; otherwise, the bucket capacity will be emptied instantly.

Perform the subtraction operation first to improve the timeliness of the capacity. Then perform the judgment to add the operation.

Public Boolean allow(String request) {// Initialize when receiving a request, If (currentCapacity == 0) {this.refrshtime = system.currentTimemillis (); } long now = system.currentTimemillis (); CurrentCapacity = math.toinTEXAct (math.max (0, 0)); this.currentCapacity - ((now - this.refrshTime) / 1000 * this.outSpeed))); this.refrshTime = now; If (currentCapacity >= this.capacity) {system.out.println (" full "); return false; } this.currentCapacity ++; this.requestQueue.add(request); return true; }Copy the code

Integrate flow-limiting functionality into the request

@PostMapping("/lt") public String lt(HttpServletRequestrequest) { If (lt.allow(long.toString (system.currentTimemillis ()))) {// call the interface} return "Please try again later "; }Copy the code