How to realize the current limit of stand-alone Interface in java
This article mainly shows you "java how to achieve stand-alone interface current limit", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "java how to achieve stand-alone interface current limit" this article.
To put it simply, an API is set to accept only a fixed number of requests at a certain time. For example, the / add API receives up to 100 requests per second, and many requests are rejected directly. This problem is very common, and the scenario is easy to understand. Go to the code directly:
/ * standalone current limit * / @ Slf4jpublic class FlowLimit {/ / Interface current limit upper limit and current limit time cache private static Cache localCache = CacheBuilder.newBuilder (). MaximumSize (100) .resolreAfterWrite (1000, TimeUnit.MILLISECONDS). Build (); / / the upper limit cache of each interface private static Map maxFlowLimitMap = new ConcurrentHashMap (); private static final FlowLimit instance = new FlowLimit () / / the purpose of this block is to initialize the upper limit of each interface. The following variables: apiFlowLimitConfigure / / when actually used, the upper limit value of each interface should be obtained from db or other places. / / this can dynamically adjust the upper limit of the interface, such as directly modifying db without publishing. You can adjust the current limit value of the interface static {new ScheduledThreadPoolExecutor (1, runnable-> {Thread thread = new Thread (runnable, "api-flowLimit-configure") / / thread.setDaemon (true); return thread;}) .scheduleAtFixedRate (()-> {try {String apiFlowLimitConfigure = "{\" doAdd\ ": 100}"; / / indicates that the / doAdd interface accepts 100 requests per second Map mapObj = JSONObject.parseObject (apiFlowLimitConfigure, Map.class) If (mapObj! = null) {mapObj.forEach ((key, value)-> {if (value! = null) {instance.setMaxFlowLimit (key.toString (), new Long (value.toString () } else {log.warn (key + "- set interface current limit discovery value is empty, set default value"); instance.setMaxFlowLimit (key.toString (), 100L);}}) }} catch (Exception e) {log.error ("exception {}", e);}}, 0,3, TimeUnit.SECONDS);} public static FlowLimit getInstance () {return instance;} private FlowLimit setMaxFlowLimit (String key, Long maxFlowLimit) {maxFlowLimitMap.put (key, maxFlowLimit); return this } public Boolean isAvailable (String key) {return checkAvailable (key, 1L);} public Boolean isAvailable (String key, Long incrNum) {return checkAvailable (key, incrNum);} private Boolean checkAvailable (String key, Long incrNum) {Long maxFlowLimit = maxFlowLimitMap.get (key); if (null = = maxFlowLimit | | maxFlowLimit = = 0) {return true;} if (incrAndGet (key, incrNum)