淘先锋技术网

首页 1 2 3 4 5 6 7

Druid 有两种配置方法:一种是基于spring的配置,另一种是手动创建链接。
下面简述这两种方法。

一、Spring配置
把数据源改为以下配置:
1:applicationContext.xml




















配置web.xml 开启Druid的内置监控页面
2:在web.xml中添加以下代码


DruidStatView
com.alibaba.druid.support.http.StatViewServlet


DruidStatView
/druid/*


DruidWebStatFilter
com.alibaba.druid.support.http.WebStatFilter

exclusions
.js,.gif,.jpg,.png,.css,.ico,/druid/*



DruidWebStatFilter
/*

配置完后,重启工程,访问监控页面:http://ip:port/projectName/druid/index.html
二、手动创建链接。

采用new DruidDataSource ()或者DruidDataSourceFactory .createDataSource(properties)的方式均可,前者需要手动设置参数值,后者自动从配置文件中读取,可根据需要使用
1:新建DBUtil 类
package demo.test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DBUtil {
private static DataSource ds = null;
static {
try{
InputStream in = DBUtil.class.getClassLoader().getResourceAsStream(“ds.properties”);
Properties props = new Properties();
props.load(in);
ds = DruidDataSourceFactory.createDataSource(props);
}catch(Exception ex){
ex.printStackTrace();
}
}
public static Connection openConnection() throws SQLException{
return ds.getConnection();
}
}
2:ds.properties
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/yuan_web
username = **
password = **

initialSize = 5
maxActive = 10
minIdle = 3
maxWait = 60000
removeAbandoned = true
removeAbandonedTimeout = 180
timeBetweenEvictionRunsMillis = 60000
minEvictableIdleTimeMillis = 300000
validationQuery = SELECT 1 FROM DUAL
testWhileIdle = true
testOnBorrow = false
testOnReturn = false
poolPreparedStatements = true
maxPoolPreparedStatementPerConnectionSize = 50
filters = stat