There are two ways to write redis as a current limiter:

Long size = redisTemplate.opsForList().size("apiRequest"); if (size < 1000) { redisTemplate.opsForList().leftPush("apiRequest", System.currentTimeMillis()); } else { Long start = (Long) redisTemplate.opsForList().index("apiRequest", -1); If ((system.currentTimemillis () -start) < 60000) {throw new RuntimeException(" Exceeded traffic limiting threshold "); } else { redisTemplate.opsForList().leftPush("apiRequest", System.currentTimeMillis()); redisTemplate.opsForList().trim("apiRequest", -1, -1); }}Copy the code

Use a list to store a list of values. Each request puts the current time in. If the list is 1000, then it will be called 1000 times. If the difference between the current time and the initial time on the 1000th call is less than 60 seconds, then there are more than 1000 calls per minute. Otherwise, the previous values of the list are emptied

Method 2:

Integer count = (Integer) redisTemplate.opsForValue().get("apiKey"); Integer integer = Optional.ofNullable(count).orElse(0); If (integer > 1000) {throw new RuntimeException(" Exceeding traffic limiting threshold "); } if (redisTemplate.getExpire("apiKey", TimeUnit.SECONDS).longValue() < 0) { redisTemplate.multi(); redisTemplate.opsForValue().increment("apiKey", 1); redisTemplate.expire("apiKey", 60, TimeUnit.SECONDS); redisTemplate.exec(); } else { redisTemplate.opsForValue().increment("apiKey", 1); }Copy the code

The expiration time is 1 minute. The value is the number of times the API is called within this minute

Comparison: Method 1 consumes memory, accurate current limiting. Method 2 results have some errors. The number of calls in a minute when key exists is limited to less than 1000, but it does not mean that the number of calls in a minute in any period is less than 1000