SpringBoot之数据库连接池(druid)

1.介绍


SpringBoot默认使用 org.apache.tomcat.jdbc.pool.DataSource 

Tomcat 在 7.0 以前的版本都是使用 commons-dbcp 做为连接池的实现,但是 dbcp 饱受诟病,原因有:

  1. dbcp 是单线程的,为了保证线程安全会锁整个连接池
  2. dbcp 性能不佳
  3. dbcp 太复杂,超过 60 个类
  4. dbcp 使用静态接口,在 JDK 1.6 编译有问题
  5. dbcp 发展滞后

因此很多人会选择一些第三方的连接池组件,例如 c3p0 , bonecp, druid (@wenshao ) 等。

为此,Tomcat 从 7.0 开始引入一个新的模块:Tomcat jdbc pool

  1. tomcat jdbc pool 近乎兼容 dbcp ,性能更高
  2. 异步方式获取连接
  3. tomcat jdbc pool 是 tomcat 的一个模块,基于 tomcat JULI,使用 Tomcat 的日志框架
  4. 使用 javax.sql.PooledConnection 接口获取连接
  5. 支持高并发应用环境
  6. 超简单,核心文件只有8个,比 c3p0 还
  7. 更好的空闲连接处理机制
  8. 支持 JMX
  9. 支持 XA Connection

tomcat jdbc pool 的优点远不止这些,详情请看这里。

tomcat jdbc pool 可在 Tomcat 中直接使用,也可以在独立的应用中使用。

Tomcat 中直接使用的方法:

数据源配置:

01 <Resource name="jdbc/TestDB"
02       auth="Container"
03       type="javax.sql.DataSource"
04       factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
05       testWhileIdle="true"
06       testOnBorrow="true"
07       testOnReturn="false"
08       validationQuery="SELECT 1"
09       validationInterval="30000"
10       timeBetweenEvictionRunsMillis="30000"
11       maxActive="100"
12       minIdle="10"
13       maxWait="10000"
14       initialSize="10"
15       removeAbandonedTimeout="60"
16       removeAbandoned="true"
17       logAbandoned="true"
18       minEvictableIdleTimeMillis="30000"
19       jmxEnabled="true"
20       jdbcInterceptors=
21 "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
22       username="root"
23       password="password"
24       driverClassName="com.mysql.jdbc.Driver"
25       url="jdbc:mysql://localhost:3306/mysql"/>

异步获取连接的方法:

01 Connection con = null;
02 try {
03   Future future = datasource.getConnectionAsync();
04   while (!future.isDone()) {
05       System.out.println("Connection is not yet available. Do some background work");
06       try {
07       Thread.sleep(100); //simulate work
08       }catch (InterruptedException x) {
09       Thread.currentThread().interrupted();
10       }
11   }
12   con = future.get(); //should return instantly
13   Statement st = con.createStatement();
14   ResultSet rs = st.executeQuery("select * from user");

在独立的应用中使用:

01 import java.sql.Connection;
02 import java.sql.ResultSet;
03 import java.sql.Statement;
04  
05 import org.apache.tomcat.jdbc.pool.DataSource;
06 import org.apache.tomcat.jdbc.pool.PoolProperties;
07  
08 public class SimplePOJOExample {
09  
10     public static void main(String[] args) throws Exception {
11     PoolProperties p = new PoolProperties();
12     p.setUrl("jdbc:mysql://localhost:3306/mysql");
13     p.setDriverClassName("com.mysql.jdbc.Driver");
14     p.setUsername("root");
15     p.setPassword("password");
16     p.setJmxEnabled(true);
17     p.setTestWhileIdle(false);
18     p.setTestOnBorrow(true);
19     p.setValidationQuery("SELECT 1");
20     p.setTestOnReturn(false);
21     p.setValidationInterval(30000);
22     p.setTimeBetweenEvictionRunsMillis(30000);
23     p.setMaxActive(100);
24     p.setInitialSize(10);
25     p.setMaxWait(10000);
26     p.setRemoveAbandonedTimeout(60);
27     p.setMinEvictableIdleTimeMillis(30000);
28     p.setMinIdle(10);
29     p.setLogAbandoned(true);
30     p.setRemoveAbandoned(true);
31     p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
32       "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
33     DataSource datasource = new DataSource();
34     datasource.setPoolProperties(p);
35  
36     Connection con = null;
37     try {
38       con = datasource.getConnection();
39       Statement st = con.createStatement();
40       ResultSet rs = st.executeQuery("select * from user");
41       int cnt = 1;
42       while (rs.next()) {
43           System.out.println((cnt++)+". Host:" +rs.getString("Host")+
44         " User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
45       }
46       rs.close();
47       st.close();
48     finally {
49       if (con!=nulltry {con.close();}catch (Exception ignore) {}
50     }
51     }
52  
53 }

以上只是简单的介绍,具体的使用方法还需参考:

https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html




Druid是一个JDBC组件库,包括数据库连接池、SQL Parser等组件。DruidDataSource是最好的数据库连接池。SpringBoot支持任何一种数据库链接池的配置,在这里用druid作为例子进行讲解

2.快速开始

这块先以spring的JdbcTemplate为列子进行讲解

pom.xml


    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>1.4.1.RELEASEversion>
        parent>
        <modelVersion>4.0.0modelVersion>

        <artifactId>springboot-6artifactId>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starterartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-jdbcartifactId>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>5.1.39version>
            dependency>
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>1.0.26version>
            dependency>
        dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                    <version>1.4.1.RELEASEversion>
                    <configuration>
                        <fork>truefork>
                    configuration>
                plugin>
            plugins>
        build>

    project>

 
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

配置统一的DataSource,这种方式不太合适生产环境,SpringBoot可以统一的配置application.yaml,但是目前仅仅支持dbcp、dbcp2、hikari 
下面这种方式无法不支持的DruidDataSource的其他参数

application.yaml


    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        username: root
        password: qq123456
        url: jdbc:mysql://localhost:3306/test1
        type: com.alibaba.druid.pool.DruidDataSource

 
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

通过代码的方式进行配置


    @SpringBootApplication
    public class AppApplication {

        public static void main(String[] args) throws Exception {
            SpringApplication.run(AppApplication.class, args);
        }

        /**
         * 注册DruidServlet
         *
         * @return
         */
        @Bean
        public ServletRegistrationBean druidServletRegistrationBean() {
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
            servletRegistrationBean.setServlet(new StatViewServlet());
            servletRegistrationBean.addUrlMappings("/druid/*");
            return servletRegistrationBean;
        }

        /**
         * 注册DruidFilter拦截
         *
         * @return
         */
        @Bean
        public FilterRegistrationBean duridFilterRegistrationBean() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
            filterRegistrationBean.setFilter(new WebStatFilter());
            Map initParams = new HashMap();
            //设置忽略请求
            initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
            filterRegistrationBean.setInitParameters(initParams);
            filterRegistrationBean.addUrlPatterns("/*");
            return filterRegistrationBean;
        }

        /**
         * 配置DataSource
         * @return
         * @throws SQLException
         */
        @Bean
        public DataSource druidDataSource() throws SQLException {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUsername("root");
            druidDataSource.setPassword("qq123456");
            druidDataSource.setUrl("jdbc:mysql://localhost:3306/test1");
            druidDataSource.setMaxActive(100);
            druidDataSource.setFilters("stat,wall");
            druidDataSource.setInitialSize(10);
            return druidDataSource;
        }

    }


 
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

这块采用的是ServletRegistrationBean 和FilterRegistrationBean的方式进行注册Servlet和Filter,这种是SpingBoot里面提供支持原生的方式 
除了这种方式还可以采用其他方式进行配置,采用Servlet3.0的注解Servlet进行配置

这块配置基本就完事了,可以访问本地链接http://localhost:8080/druid/datasource.html查看监控信息

官方资料

其他的详细配置可以查看官方文档进行配置,这里不过多讲述 
https://github.com/alibaba/druid/wiki/%E9%A6%96%E9%A1%B5

你可能感兴趣的:(spring,boot,springboot,连接池,数据库连接池)