Whenever you expose a web service / api endpoint,you need to implement a rate limiter to prevent abuse of the service (DOS attacks).
Implement a RateLimiter Class with an isAllow method. Every request comes in with a unique clientID,deny a request if that client has made more than 100 requests in the past second.
1 public class RateLimiter { 2 private final Map<String,LinkedList<Long>> clientHitMap = new HashMap<>(); 3 private final int REQUEST_LIMIT = 3; 4 private final long TIME_LIMIT = 1000L; 5 6 public boolean isAllow(String client_id) { 7 LinkedList<Long> list = clientHitMap.get(client_id); 8 long curTime = System.currentTimeMillis(); 9 if (list == null) { 10 clientHitMap.put(client_id,new LinkedList<Long>()); 11 } 12 while (!list.isEmpty() && curTime - list.peek() >= TIME_LIMIT) { 13 list.poll(); 14 } 15 if (list.size() < REQUEST_LIMIT) { 16 list.offer(curTime); 17 return true; 18 } 19 return false; 20 } 21 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。