If I have a HTTP REST API : example /getCount
Sample Code
@RestController
public class CountController {
long count = 0;
@Getmapping("/getCount")
public long getCount(){
count++; // Here is the problem, how to keep the latest count if the API was hit by multiple Application/clients
return count;
}
}
Problem Description: Every time any app/system call the above mentioned API, count will be increased by 1 and the caller entity can get the exact number of hit.
Condition: Its a open API.Need guidance how to achieve it. This is the only problem statement I am having
you can use static type if you want counter behavior as follows
@RestController
public class CountController {
static long count = 0;
@Getmapping("/getCount")
public long getCount(){
count++; // Here is the problem, how to keep the latest count if the API was hit by multiple Application/clients
return count;
}
}
If You want different counter for all client or want to hold counter value even if server is shutdown or restart then you need to use DB to store counter.
Java provides a nice capability through AtomicInteger. This is a thread-safe object and you can rely on to increment whenever your counter method is called.
You need to define your Resource class as Singleton and initiate the AtomicInteger.
private AtomicInteger count = new AtomicInteger();
You need to add the following code inside your rest method to increment the current counter by one. This will be automatically taken care by the following method,
count.incrementAndGet();
When you need to get the current counter you can have a REST method to get the details like below,
@GetMapping("count")
public int getCount() {
return this.count.get();
}
I hope this would clarify your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With