Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of times REST API was called

Tags:

java

json

rest

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

like image 807
rahulnikhare Avatar asked Nov 23 '25 02:11

rahulnikhare


2 Answers

you can use static type if you want counter behavior as follows

  • Counter is common for all clients calling APIs.
  • Counter will restart to 0 as soon as server will restart.

@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.

like image 179
MADHAVI KUMARI Avatar answered Nov 24 '25 16:11

MADHAVI KUMARI


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.

First:

You need to define your Resource class as Singleton and initiate the AtomicInteger.

private AtomicInteger count = new AtomicInteger();

Second:

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();

Finally:

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.

like image 21
Thamizharasu Avatar answered Nov 24 '25 16:11

Thamizharasu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!