Visitor counter using Spring Boot

Asked

Viewed 359 times

1

I have a project of Mangas using Spring Boot with Angularjs and, I wanted to implement a counter of views, accesses, for each visualized manga. So I could classify the Manga in Category of most viewed by Week, By Month and Total Views, like Mangadex

Example.

{
    "id": 113,
    "nome": "HUNTER X HUNTER",
    "viewsCount": 35
},
{
    "id": 44,
    "nome": "ONE PIECE",
    "viewsCount": 215
}

How could I do this count? Maybe add a counter to the endpoint and add up each time you access each sleeve?

200 GET /user/manga/113 viewsCount:0
200 PUT /user/manga/113 viewsCount:1
  • 2

    It will depend a lot on the architecture of your solution. I would encapsulate it within a Service that offers access to the sleeves. Whenever the method getById, service was accessed, it would increase the counter. I would not delegate it to the frontend, since you would be required to make 2 requests.

1 answer

2


One solution is simply to count the moment the GET the image is accessed.

GET /user/manga/113

To know the number of views, you can have an endpoint for this:

GET /user/manga/113/views

Each access will generate a record in a table, with some visitor data or simply a simple record of the visit. To know how many times it was visited, just count the records in the table. This solution, if you save information from the user you viewed, enables you to count views and count views excluding multiple visits from the same user (this is the concept of "unique visitors").

You could also create a "counter" column in the table and increment each view, as long as you make one UPDATE in the direct counter in the database:

UPDATE manga SET views = views +1 WHERE id = ?

Letting the database itself handle the writing competition problem if multiple people are accessing the same image at the same time.

If you choose, for any reason, to make a SELECT value, increment and then do the UPDATE, you will have competition writing problems of this value. For example, if two calls from GET occur at the same time in an image with 5 views, both will take the current value of the bank, increment in 1, and save. So instead of having 7 views you might have saved only 6 in the database.

  • The competition problem can be mitigated by updating the table counter directly (ex UPDATE manga SET views = views +1 WHERE id = ?) instead of doing the select to then do the update.

  • @Leonardolima, it’s true, had only thought about the select and then update. I’ll add this option in the reply. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.