Spring Boot Rest Api stucked after N parallel save requests

Luigi De Cosmis :

I'm creating a Rest Api with Spring Boot. I'm using the default configuration of Hikari, so it has a pool size of 10 connections. I encountered an error when i try to post 10 parallel requests to a specific route. The error says Connection is not available, request timed out after 30001ms. This route saves data into a MySQL database, it usually takes some milliseconds to complete one save operation. Why is this problem happening? Should it complete the save operation and then free the database connection for the next operation? This error seems to appear only with saving operations where the save function creates a new entity.

Properties

spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.url=jdbc:mysql://192.168.1.88:3306/question?serverTimezone=UTC
spring.datasource.username=luigi
spring.datasource.password=root

Repository

public interface RandomRepository extends CrudRepository<Random, Integer> {
}

Controller

@RestController
public class RandomController {
    private RandomRepository randomRepository;

    public RandomController(RandomRepository randomRepository) {
        this.randomRepository = randomRepository;
    }

    @GetMapping("/")
    public String createRandom() {
        return String.valueOf(Math.random());
    }

    @PostMapping("save")
    public Random save(){
        Random random = new Random();
        random.setNumber(Math.random());

        randomRepository.save(random);

        return random;
    }
}

I've found a solution by making the save method synchronized. Is this the right way? Did someone encountered the same problem?

Possible solution

@PostMapping("save")
public synchronized Random save(){
    Random random = new Random();
    random.setNumber(Math.random());

    randomRepository.save(random);

    return random;
}

I expected that the save operation would be completed easly, but it stucks until it crashes after 30 seconds

riorio :

We faced a very similar issue when working with Spring Boot & Couchbase.

When the number of requests was high, the connection to the DB got stuck.

The solution that we used was to move to Async method calls for all levels - from the controller down to the DB operations.

See this post & answer

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166335&siteId=1