上一篇文章讲了c3p0连接数据库的方法,这一篇讲如何替换成druid连接池。毕竟druid连接池在监控和性能方面做的确实很出色。替换后主要实现几个功能,页面监控、数据库密码加密、慢sql日志记录等。
一、数据源配置druidDataSource.properties
driverClassName=oracle.jdbc.OracleDriver
dataBaseName=Oracle
url=jdbc:oracle:thin:@192.168.1.1:1521:orcl
username=root
password=FekGGtMKN0iy0eT22vK1QAg+M57i3842q305F1wSgQNCpnPhjHsD6hf+uufihVXXXJcA/IDNDJTqxUeHbOnEOQ==
filters=stat,config,log4j
#最大连接池数量
maxActive=120
#最小连接池数量
minIdle=30
#初始化的物理连接数量
initialSize=10
#获取连接时最大等待时间
maxWait=30000
#配置间隔多久进行一次检测,检测需要关闭的空闲连接
timeBetweenEvictionRunsMillis=60000
#配置一个连接在池中最小生存的时间
minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的的sql
validationQuery=SELECT 1 FROM DUAL
testWhileIdle=true
#申请连接执行validationQuery检测连接是否有效,会降低性能
testOnBorrow=false
#归还连接执行validationQuery检测连接是否有效,会降低性能
testOnReturn=false
#启用PSCache
maxOpenPreparedStatements=20
removeAbandoned=true
removeAbandonedTimeout=1800
logAbandoned=true
#慢sql记录(3秒)
druid.stat.slowSqlMillis=3000
druid.stat.logSlowSql=true
config.decrypt=true
config.decrypt.key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALPmG7ilbO46XRqE2YdBMtoRY4vecqqnRXRQTPIf2VWtGsnYmaJTYrglvdSNts4rsvWTihzOZl3fd/8piZUaLK8CAwEAAQ==
详细参数配置与其他连接池的区别,网上有很多,再此不表。
二、web.xml配置
<!--druid监控配置 -->
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
<init-param>
<!-- 用户名 -->
<param-name>loginUsername</param-name>
<param-value>druid</param-value>
</init-param>
<init-param>
<!-- 密码 -->
<param-name>loginPassword</param-name>
<param-value>druid</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
添加如上代码,其中用户名、密码用于登录druid monitor监控页面
三、替换数据源
// protected static ComboPooledDataSource ds=new ComboPooledDataSource(true);原先的c3p0
protected static DruidDataSource dds=new DruidDataSource();//druid连接池
protected static JdbcTemplate jdbcTemplate;
Properties pro = new Properties();
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("druidDataSource.properties");
pro.load(in);
static{
initDBInFo();
}
public static void initDBInFo(){
try {
dds.setUrl(pro.getProperty("url"));
try {
dds.setDriverClassName(pro.getProperty("driverClassName"));
} catch (Exception e) {
log.error("获取数据库驱动失败,原因为:" + e.getMessage());
e.printStackTrace();
}
dds.setUsername(pro.getProperty("username"));
dds.setPassword(pro.getProperty("password"));
dds.setInitialSize(Integer.valueOf(pro.getProperty("initialSize")));
dds.setMaxActive(Integer.valueOf(pro.getProperty("maxActive")));
dds.setMaxWait(Integer.valueOf(pro.getProperty("maxWait")));
dds.setRemoveAbandoned(Boolean.valueOf(pro.getProperty("removeAbandoned")));
dds.setRemoveAbandonedTimeout(Integer.valueOf(pro.getProperty("removeAbandonedTimeout")));
dds.setTimeBetweenEvictionRunsMillis(Integer.valueOf(pro.getProperty("timeBetweenEvictionRunsMillis")));
dds.setMinEvictableIdleTimeMillis(Integer.valueOf(pro.getProperty("minEvictableIdleTimeMillis")));
dds.setLogAbandoned(Boolean.valueOf(pro.getProperty("logAbandoned")));
dds.setFilters(pro.getProperty("filters"));
dds.setMinIdle(Integer.valueOf(pro.getProperty("minIdle")));
dds.setMaxOpenPreparedStatements(Integer.valueOf(pro.getProperty("maxOpenPreparedStatements")));
dds.setTestWhileIdle(Boolean.valueOf(pro.getProperty("testWhileIdle")));
dds.setTestOnBorrow(Boolean.valueOf(pro.getProperty("testOnBorrow")));
dds.setTestOnReturn(Boolean.valueOf(pro.getProperty("testOnReturn")));
dds.setValidationQuery(pro.getProperty("validationQuery"));
Properties connectProperties = new Properties();//数据库密码、慢sql相关配置
connectProperties.put("config.decrypt",pro.getProperty("config.decrypt"));
connectProperties.put("config.decrypt.key",pro.getProperty("config.decrypt.key"));
connectProperties.put("druid.stat.slowSqlMillis",pro.getProperty("druid.stat.slowSqlMillis"));
connectProperties.put("druid.stat.logSlowSql",pro.getProperty("druid.stat.logSlowSql"));
dds.setConnectProperties(connectProperties);
jdbcTemplate = new JdbcTemplate(dds);
} catch (Exception e) {
log.error("初始化数据库连接池失败,原因为:" + e.getMessage());
}
}
四、数据库密码加密
进入druid jar包目录下执行如上命令 后面跟的是要加密的密码
会得到privateKey、publicKey、password
将password、publickey存入druidDataSource.properties中的password和config.decrypt.key即可。
五、启动项目
进入:http://ip:端口/项目名/druid/login.html
输入web.xml里配置的用户名、密码
可以看到数据源的相关配置参数、sql监控等信息。是不是很简单。
六、配置log4j,让慢速sql输出到日志文件中
log4j.rootLogger = info,stdout,error,druid
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} %l-[%p] %m -(\:%L)%n
log4j.logger.info = info
log4j.appender.info = org.apache.log4j.RollingFileAppender
log4j.appender.info.Threshold = INFO
log4j.appender.info.File = ${catalina.home}/logs/info.log
log4j.appender.info.MaxFileSize=1024KB
log4j.appender.info.MaxBackupIndex=100000
log4j.appender.info.layout = org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} %l-[%p] %m -(\:%L)%n
log4j.logger.error = error
log4j.appender.error = org.apache.log4j.RollingFileAppender
log4j.appender.error.Threshold = ERROR
log4j.appender.error.File =${catalina.home}/logs/error.log
log4j.appender.error.MaxFileSize=1024KB
log4j.appender.error.MaxBackupIndex=100000
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} %l-[%p] %m -(\:%L)%n
log4j.logger.com.opensymphony.xwork2.ognl.OgnlValueStack=erro\u641C\u7D22r
# Druid
log4j.logger.druid.sql=warn,druid
log4j.logger.druid.sql.DataSource=WARN,druid
log4j.logger.druid.sql.Connection=WARN,druid
log4j.logger.druid.sql.Statement=WARN,druid
log4j.appender.druid=org.apache.log4j.DailyRollingFileAppender
log4j.appender.druid.layout=org.apache.log4j.PatternLayout
log4j.appender.druid.layout.ConversionPattern= [%d{HH\:mm\:ss}] %c{1} - %m%n
log4j.appender.druid.datePattern='.'yyyy-MM-dd
log4j.appender.druid.Threshold = warn
log4j.appender.druid.append=true
#log4j.appender.druid.File=${catalina.home}/logs/warn.log
log4j.appender.druid.File=d:/test/logs/slowsql.log
这里随便说一下,log4j.properties放置在src目录下,程序启动时就会自动去加载其中的配置信息。以前没亲手配置过,一直没深究,看了源码才知道。如上配置是开启了info级别的日志,定义了stdout、error、druid三个输出源。
相关目录下就有了,哈哈哈。