欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot开发web api应用实践(三)使用proxool连接池 博客分类: spring boot 实践笔记 spring bootproxool 

程序员文章站 2024-03-13 18:49:15
...

在第一篇文章(spring boot开发web api应用实践(一)入门),简单介绍了如何利用spring boot搭建一个web应用,第二篇文章(spring boot开发web api应用实践(二)操作数据库)介绍了如何引入DAO层数据库操作,本篇将介绍如何将spring boot默认的tomcat-jdbc连接池换成proxool连接池。

 

proxool连接池的初始化,可以单独写个listener来初始化,正好说说spring boot如何初始化servlet、filter和listener等(虽然很简单)。

一、编辑pom.xml文件:

      引入proxool的依赖:

   	    <dependency>
   	       	    <groupId>org.logicalcobwebs</groupId> 
   	       	    <artifactId>com.springsource.org.logicalcobwebs.proxool</artifactId>
   	       	    <version>0.9.1</version>
   	    </dependency>

    修改spring-boot-starter-jdbc依赖,排除tomcat-jdbc的连接池引用:

 

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
			<scope>compile</scope>
			<exclusions>
			   <exclusion>
			       <groupId>org.apache.tomcat</groupId>
			       <artifactId>tomcat-jdbc</artifactId>
			   </exclusion>
			</exclusions>
		</dependency>

 

 

二、编写proxool连接池初始化的listener(ProxoolLoaderListener.java):

 

package com.zweichxu.springboot.proxool;

import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebListener;

import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
 
import com.zweichxu.platform.util.Util;

/**
 * @author huangzw
 * 
 */
@WebListener
public class ProxoolLoaderListener implements ServletContextListener {
    public static final String PROXOOL_CONFIG_LOCATION = "proxoolConfigLocation";

    private static Logger log = LoggerFactory.getLogger(ProxoolLoaderListener.class);

    @Override
    public void contextDestroyed(ServletContextEvent event){
        // do nothing
    }

    @Override
    public void contextInitialized(ServletContextEvent event){
        proxoolLoaderInit(event.getServletContext());
    }

    private void proxoolLoaderInit(ServletContext sc){
        String xmlpath = sc.getInitParameter(PROXOOL_CONFIG_LOCATION);
        log.info("proxoolLoaderInit, the initParam config path: {}", xmlpath);
        if(xmlpath == null){
            xmlpath = "classpath:proxool.xml";
        }

        xmlpath = xmlpath.trim().toLowerCase();
        InputStream is = null;
        try{
            if(xmlpath.startsWith("classpath:")){
                is = this.getClass().getClassLoader().getResourceAsStream(xmlpath.split(":")[1]); 
                org.logicalcobwebs.proxool.configuration.JAXPConfigurator.configure(new InputSource(is), false);
            }else{
                String appDir = sc.getRealPath("/");
                try{
                    org.logicalcobwebs.proxool.configuration.JAXPConfigurator.configure(appDir + "/" + xmlpath, false);
                }catch(ProxoolException e){
                    log.error("loadding proxool config error: {}/{}", appDir, xmlpath, e);
                    is = this.getClass().getClassLoader().getResourceAsStream(xmlpath.split(":")[1]);
                    org.logicalcobwebs.proxool.configuration.JAXPConfigurator.configure(new InputSource(is), false);
                }
            }
            
            //对连接池增加监控:监控连接的创建与释放、sql的执行时长等
            //ProxoolSqlListener类为自定义的继承自org.logicalcobwebs.proxool.ConnectionListenerIF的普通类
            String[] aliasArr = ProxoolFacade.getAliases();
            ProxoolSqlListener sqlListener = new ProxoolSqlListener();
            if (Util.isNotEmpty(aliasArr)){
                for (String alias: aliasArr){
                   if (alias.startsWith("proxool.")){
                        alias = alias.substring(alias.indexOf('.') + 1);
                   }
                 
                   ProxoolFacade.addConnectionListener(alias, sqlListener);
                }
            }
        }catch(ProxoolException e){
            log.error("loadding proxool config error form classpath: {}", xmlpath, e);
        }finally{
        	   org.apache.commons.io.IOUtils.closeQuietly(is);
        }
    }
}

   注意:该类使用了@WebListener注解,这是Servlet3.0+新增的注解

 

   要想ProxoolLoaderListener.java生效,还需要修改应用启动类(参看spring boot开发web api应用实践(一)入门),增加@ServletComponentScan注解,该注解将自动扫描应用中的@WebFilter、@WebServlet以及@WebListener注解标注的类

package com.zweichxu.springboot;  
  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
  
/** 
 *   
 * @author zweichxu 
 * @date 2017年3月30日 16:40:41 
 * @version 1.0 
 */  
@SpringBootApplication
@ServletComponentScan
public class AppMain {  
    public static void main(String[] args){  
          SpringApplication.run(AppMain.class, args);  
    }  
}  

 

三、数据源配置

   1.在工程的src\main\resources目录下面创建proxool.xml文件,配置proxool的连接池参数

<?xml version="1.0" encoding="UTF-8"?>
<!-- the proxool configuration can be embedded within your own application's.
     Anything outside the "proxool" tag is ignored. -->

<something-else-entirely>
     <proxool>
          <alias>proxool_dbpool</alias>
          <driver-url>jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false</driver-url>
          <driver-class>com.mysql.jdbc.Driver</driver-class>
          <driver-properties>
              <property name="user" value="root" />
              <property name="password" value="root" /> 
          </driver-properties>
          <!-- 最大连接数 -->
          <maximum-connection-count>20</maximum-connection-count>

          <!-- 最小连接数  默认值:5个 -->
          <minimum-connection-count>5</minimum-connection-count>

          <!-- 最少保持的空闲连接数 -->
          <prototype-count>5</prototype-count>
        
          <!-- 同时创建新的最大并发连接数 -->
          <simultaneous-build-throttle>30</simultaneous-build-throttle>

          <!-- 最大连接生命周期(毫秒数)  默认值:4小时,此处配为15分钟 -->
          <maximum-connection-lifetime>900000</maximum-connection-lifetime>
          
          <!-- 最大活动时间(毫秒数)   默认值:5分钟  -->
          <maximum-active-time>300000</maximum-active-time>
           
          <!-- 自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 -->
          <house-keeping-sleep-time>30000</house-keeping-sleep-time>
        
          <!-- 保持连接的测试SQL语句 -->
          <house-keeping-test-sql>
               select now()
          </house-keeping-test-sql>
          
          <test-before-use>true</test-before-use>
     </proxool>
</something-else-entirely>

 

   2.修改application.properties里的数据库配置

    注释掉原先的数据源配置,增加spring.datasource.type、spring.datasource.driver-class-name以及spring.datasource.url,其中spring.datasource.type设置为org.springframework.jdbc.datasource.DriverManagerDataSource类,spring.datasource.driver-class-name设置为org.logicalcobwebs.proxool.ProxoolDriver类,spring.datasource.url设置为proxool连接池的别名(proxool.连接池别名alias)

#spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.max-idle=20
#spring.datasource.min-idle=5
#spring.datasource.initial-size=5
#spring.datasource.max-wait=10000
#spring.datasource.validation-query=SELECT 1
#spring.datasource.test-on-borrow=false
#spring.datasource.test-while-idle=true
#spring.datasource.time-between-eviction-runs-millis=18800
#spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=3)

spring.datasource.type=org.springframework.jdbc.datasource.DriverManagerDataSource
spring.datasource.driver-class-name=org.logicalcobwebs.proxool.ProxoolDriver
spring.datasource.url=proxool.proxool_dbpool

 

四、启动应用,查看控制台日志,可以看到“Proxool 0.9.1 (23-Aug-2008 11:10) [org.logicalcobwebs.proxool.ProxoolFacade.registerConnectionPool(ProxoolFacade.java:86)] ”的提示。

 

 

相关标签: spring boot proxool