How to manage database connection pool in spring jpa?

前端 未结 2 809
星月不相逢
星月不相逢 2021-02-05 07:40

I am using spring-boot in my web application and use spring-jpa to read/write from/to my database. It works very well but I want to understand how to manage the database connect

2条回答
  •  旧时难觅i
    2021-02-05 08:18

    You have already found that you can configure this from application.properties You can find all the possible properties here.

    Notice that from Spring Boot 1.4 there are datasource properties for every datasource vendor that spring integrates with, out of the box. There is spring.datasource.dbcp.*,spring.datasource.tomcat.* and so on. See 1.4 docs

    If that's not enought, and you need something very specific, you can declare the datasource bean yourself. Here is the example with Tomcat datasource:

    @Bean
    public DataSource dataSource(){
         PoolProperties p = new PoolProperties();
              p.setUrl("jdbc:mysql://localhost:3306/mysql");
              p.setDriverClassName("com.mysql.jdbc.Driver");
              p.setUsername("root");
              p.setPassword("password");
              p.setJmxEnabled(true);
              p.setTestWhileIdle(false);
              p.setTestOnBorrow(true);
              p.setValidationQuery("SELECT 1");
              p.setTestOnReturn(false);
              p.setValidationInterval(30000);
              p.setTimeBetweenEvictionRunsMillis(30000);
              p.setMaxActive(100);
              p.setInitialSize(10);
              p.setMaxWait(10000);
              p.setRemoveAbandonedTimeout(60);
              p.setMinEvictableIdleTimeMillis(30000);
              p.setMinIdle(10);
              p.setLogAbandoned(true);
              p.setRemoveAbandoned(true);
              p.setJdbcInterceptors(
                "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
                "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
              DataSource datasource = new DataSource();
              datasource.setPoolProperties(p);
              return datasource ;
    }
    

提交回复
热议问题