Search code examples
spring-boottomcatdatabase-connectionmicroservicesconnection-pooling

how to limit the database connection created by spring boot application running microservices


I am working on my school project to make an application with microService architecture (with maven and spring boot JPA) hardware i am using: aws RDS (max DB connection is 66, and this caused my problem) aws ec2-instance free tier I am having 3 microservices: employee,salary and leave. However, with only 3 micro services running, my DB connection reached 40+. I cannot figure out how to limit the number of DB connection a service can create.

After some research i encountered the term "connection pool", so i tried to set up tomcat connection pool.

this is the configuration(i did both for) but it does not work am i right to say that if the configuration is right, my application would only make max 5 active connection?

spring.datasource.tomcat.initial-size=5
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=5
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=1
spring.datasource.tomcat.default-auto-commit=true   

this is the code for the query

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
    @Query(
            value = "select * from itsa.Employee;",
            nativeQuery = true)
    List<Employee> findAllEmployee();

    @Query(
            value = "SELECT * FROM Employee where id = :id",
            nativeQuery = true)
    List<Employee> findEmp(@Param("id") int id);

Solution

  • Default CP in Spring boot is HikariCP. as soon as you include spring-boot-starter-data-jpa in pom.xml, you will have HikariCP configured for you with default values.

    if you want you configuration get effective, you need to exclude HikariCP and include tomcat-cp. for this, you need to make below changes to your pom.xml.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <exclusions>
            <exclusion>
                <groupId>com.zaxxer</groupId>
                <artifactId>HikariCP</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jdbc</artifactId>
        <version>9.0.10</version>
    </dependency>
    

    Hope this helps solving your issue.