Druid连接池(无框架)

关于连接池有不少技术可以用,例如c3p0,druid等等,因为druid有监控平台,性能在同类产品中算top0的。所以我采用的事druid连接池。

首先熟悉一个技术,我们要搞明白,为什么要用他, 他能帮我们解决什么问题?

如果不使用连接池会出现的情况:
a.占用服务器的内存资源
b.导致服务器的速度非常慢
1.准备

下载druid1.9的jar包和对应数据库的驱动包。

https://mvnrepository.com/artifact/com.alibaba/druid/1.0.9

2.代码

2.1db.properties

driverClassName=net.sourceforge.jtds.jdbc.Driver
url=jdbc:jtds:sqlserver:/XXXXX:1433/szqxjimg;SelectMethod=Cursor;DatabaseName=szqxjimg
username=sa
password=123456

# 配置参数,让ConfigFilter解密密码
#connectionProperties=config.decrypt=true;config.decrypt.key=xxxx

# 监控统计拦截的filters
filters=stat

# 初始化时建立物理连接的个数,初始化发生在显示调用init方法,或者第一次getConnection时
initialSize=1
# 最大连接池数量
maxActive=10
# 最小连接池数量
minIdle:1
# 获取连接等待超时的时间,单位毫秒
maxWait=60000

# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
# 有两个含义:1) Destroy线程会检测连接的间隔时间  2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明
timeBetweenEvictionRunsMillis=60000
# 一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis=300000

# 用来检测连接是否有效
validationQuery=SELECT 1
# 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
testWhileIdle=true
# 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnBorrow=false
# 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnReturn=false

# 是否缓存preparedStatement,也就是PSCache
poolPreparedStatements=true

maxPoolPreparedStatementPerConnectionSize=200

2.2代码

package com.qihui.qxj.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.qihui.qxj.services.system.Brand;

public class DruidUtil {

    private static Properties p;
    private static DataSource dataSource;

    static {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = loader.getResourceAsStream("db.properties");
            p = new Properties();
            p.load(inputStream);
            // 通过工厂类获取DataSource对象
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close(Connection conn, Statement state, ResultSet result) {

        try {
            if (result != null) {
                result.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (state != null) {
                        state.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Brand brand = new Brand();
        long startTIme =System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            String selectBrand = brand.getSelectBrand();
        }
        long endTime =System.currentTimeMillis();
        System.out.println(endTime- startTIme);
    }
}

3.结论

通过多次测试,发现,循环查询1000次,不使用连接池,查询性能为7500ms,使用连接池后,查询速度为1515ms,可以看出查询性能优化勒很多。

原文地址:https://www.cnblogs.com/diaozhaojian/p/11212320.html

时间: 2024-08-03 23:31:01

Druid连接池(无框架)的相关文章

SpringMVC+Spring+Mybatis整合,使用druid连接池,声明式事务,maven配置

一直对springmvc和mybatis挺怀念的,最近想自己再搭建下框架,然后写点什么. 暂时没有整合缓存,druid也没有做ip地址的过滤.Spring的AOP简单配置了下,也还没具体弄,不知道能不能用,log也不知道能不能用,`(*∩_∩*)′哈哈,有点不负责任...... 直接上代码: 使用的eclipse和eclipse自带的maven,参考了网上的资料,有些代码是拷贝的,不过都自己测试过了.嗯,可以跑起来... 先上项目结构: 新建maven项目,选择web,然后配置pom: <pro

SpringBoot2.0 基础案例(07):集成Druid连接池,配置监控界面

一.Druid连接池 1.druid简介 Druid连接池是阿里巴巴开源的数据库连接池项目.Druid连接池为监控而生,内置强大的监控功能,监控特性不影响性能.功能强大,能防SQL注入,内置Loging能诊断Hack应用行为.Druid连接池是阿里巴巴内部唯一使用的连接池,在内部数据库相关中间件TDDL/DRDS 都内置使用强依赖了Druid连接池,经过阿里内部数千上万的系统大规模验证,经过历年双十一超大规模并发验证. 2.druid特点 1)稳定性特性,阿里巴巴的业务验证 2)完备的监控信息,

使用druid连接池的超时回收机制排查连接泄露问题

在工程中使用了druid连接池,运行一段时间后系统出现异常: Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 60009, active 50 at org.springfr

Druid连接池-阿里巴巴开源JDBC组件

Druid在连接池领域里可以说是比较火的,是阿里巴巴开源的JDBC连接池.监控组件,下面就简单介绍它一下. 它包括三部分:  DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系. DruidDataSource 高效可管理的数据库连接池. SQLParser . 功能:     .  可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助.     .  替换D

spring 4 + jpa(hibernate 3/4) + spring mvc 多数据源配置(二)+Druid连接池

接上一个博文(http://www.loveweir.com/html/18.html),没有数据库连接池,纯粹用jpa的官方链接. 所以这次要加上连接池本文用Druid连接池来实现多数据源的配置. persistence.xml 这个文件可以省略了,全部配置在applicationContext.xml 里面: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www

Druid连接池及监控在spring中的配置

Druid连接池及监控在Spring配置如下: [html] view plaincopy <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url.user.password --> <property 

druid连接池

近期一直报连接池连接的错误,主要就是那个什么last packet 多少ms以前. 所以就研究了下. druid连接池和mysql的连接关系可以简单理解为下面的案例. 有10个接线员A和远程10个接口员B在通讯,如果不用连接池,那么每用一次就要拨号.建立链接.通话.挂断,非常浪费时间.所以如果10个接线员A提前就和B接通,然后一直不挂断,这样需要时只要喊话一下就行了,效率高,真正的基于TCP连接可以参考下载 但是这样会导致一个问题,如果B偷懒,偷偷的将电话挂断,而A不知道,再讲话就会出错了. 针

使用druid连接池,配置sql防火墙发现的sql注入问题

最近在使用druid连接池,同时也配置了web和spring的关联监控,检测到select * from tables param like #{param1} "%"的语句被拦截了.做个笔记. 解决方法有两种: 一. select * from tables param like concat(${param1},"%"). 二.传入 参数的时候动态拼接 param1=param1+"%"; select * from tables param

SpringBoot配置MySql数据库和Druid连接池

1.pom文件增加相关依赖,我这里因为上面引入了父pom,所以不需要在当前pom文件下加版本 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifact