I am writing a Rest API using Spring boot. I want to calculate time between a request and the previous request, and if the time is less than 2 min I want to return an object json, trace and black list the elements of the request. How can i do this ?
- Add more details in this question - do you want to track the interval between all requests, requests based on a parameter id, etc.Shankar– Shankar2020-07-10 21:51:28 +00:00Commented Jul 10, 2020 at 21:51
- first of all I want to get the time between request and previous request.Sarah– Sarah2020-07-10 21:56:01 +00:00Commented Jul 10, 2020 at 21:56
- you can maintain a static Date variable. Store the time of first request and compare with the next request.Shankar– Shankar2020-07-10 21:59:59 +00:00Commented Jul 10, 2020 at 21:59
- 1can you give me more detail pleaseSarah– Sarah2020-07-10 22:01:44 +00:00Commented Jul 10, 2020 at 22:01
Add a comment |
1 Answer
Do something like this:
@RestController @RequestMapping("/test") public class TestController { private static long lastRequest = Long.MAX_VALUE; @RequestMapping("/post") public String postTest() { long currentTime = System.currentTimeMillis(); if (currentTime - lastRequest < 120000){ //DO WHAT YOU WANT } else { lastRequest = currentTime; } } 4 Comments
Sarah
Yes i did the same logic with LocalDateTime.now() Thank you so much Sir
Eduardo Briguenti Vieira
No problem. Just accept the answer if that is correct. Thank you.
Sarah
Do you have any idea if we want to calculate currentTime - lastRequest for each User(because in your response you are calculating the time between two request for any request)
Eduardo Briguenti Vieira
For each user you will need something to identify the user. REST architecture are normally stateless. What it is possible is the request to pass a header parameter to identify the user. You could create question here on stackoverflow about how to identify the user in a Rest request.