简体   繁体   中英

Hot to get count of API calls in Spring Boot

I have a simple class (Model) with 3 variables id (pk and auto increment) url (String) count (int)

Client can add url and can fetch url by id. The problem is I need to count how many times each url is been called.

My Pojo ->

@Entity
@Data
@NoArgsConstructor
public class Sortner {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String url;
    private Integer counter;
}

Controller ->

  @GetMapping("/findById")
    public ResponseEntity<?> findById(Integer id) {
        return new ResponseEntity<>(sortnerService.findById(id), HttpStatus.OK);
    }

Repo is just extending JpaRepository..

Service ->

public String findById(Integer id) {
        Sortner sortner = new Sortner();
        
        return "no. of times api called =>"+sortner.getCounter()+1  ;
    }
    

That's what I have tried to do but this is not returning response as I wanted its just returning 1 no matter how many times I call api using Swagger (YES the logic is really shit) I don't know how to resolve this and make it work please help

Sortner class

 public class Sortner {
  Long id;
  URL url;
 }

Controller

 @GetMapping("/findUrlById")
 public void findSortnerById(Integer id, HttpServletResponse response) throws 
 IOException {
   List<Sortner> urls = sortnerService.findUrlById(id);
   if(urls != null && urls.size() > 0) {
       response.sendRedirect(urls.get(0).getUrl().toString());
   }
     response.sendError(HttpServletResponse.SC_NOT_FOUND)
   }

https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#sendError(int) redirects to the required URL https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#sendError(int) response.sendError returns 404 as the URL cannot be found in the database

You can use the Spring Boot Actuator to get the details. It will not only provide the count for the API hits but also provide the duration, status response code any many more details and you can filter them as required.

You just need to add the following dependency in the pom file

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

Then make a hit at the given URL:

http://localhost:8080/actuator/metrics/http.server.requests

You can filter the response using the URI, status and exception as required

localhost:8080/actuator/metrics/http.server.requests?tag=uri:<endPoint>
localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/asset/getAllAssets
localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/asset/getAllAssets&tag=status:200

The response will be as follow

{
    "name": "http.server.requests",
    "description": null,
    "baseUnit": "seconds",
    "measurements": [
        {
            "statistic": "COUNT",
            "value": 3
        },
        {
            "statistic": "TOTAL_TIME",
            "value": 0.21817219999999998
        },
        {
            "statistic": "MAX",
            "value": 0.1379249
        }
    ],
    "availableTags": [
        {
            "tag": "exception",
            "values": [
                "MethodArgumentTypeMismatchException",
                "None"
            ]
        },
        {
            "tag": "method",
            "values": [
                "GET"
            ]
        },
        {
            "tag": "uri",
            "values": [
                "/{id}.*",
                "/user/asset/getAsset/{assetId}",
                "/user/asset/getAllAssets"
            ]
        },
        {
            "tag": "outcome",
            "values": [
                "CLIENT_ERROR",
                "SUCCESS"
            ]
        },
        {
            "tag": "status",
            "values": [
                "400",
                "404",
                "200"
            ]
        }
    ]
}

More details have been explained here

Spring Boot: Count Page Views - Actuators

Metrics Collection for Spring Boot REST APIs

In case you want to analyze the API details with the dashboards in more details you can follow the given blogs

Application Monitoring Using Spring Boot Admin

Application Monitoring with Prometheus and Grafana

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM