package org.nsg.dbsetting;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.ErrorCode;
import org.nsg.constant.PropertiesConst;
import org.nsg.exception.JdbcException;
import org.nsg.util.MyProperties;
import org.nsg.util.PropertiesUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
/**
* @Description MyJDBCAppender.java
* 用于Log4j的数据库Session管理[连接池用Druid]
* @author 泥沙砖瓦浆木匠
* @date 2014年12月7日下午1:50:56
* @version 1.0
*/
public class MyJDBCAppender extends JDBCAppender
{
/* Druid数据源 */
private DruidDataSource dataSource;
public MyJDBCAppender()
{
super();
}
@Override
protected void closeConnection(Connection con)
{
try
{
/* 如果数据库连接对象不为空和没有被关闭的话,关闭数据库连接 */
if ( con != null && !con.isClosed())
con.close();
}
catch (SQLException e)
{
errorHandler.error("Error closing MyJDBCAppender.closeConnection() 's connection",e,ErrorCode.GENERIC_FAILURE);
}
}
@Override
protected Connection getConnection() throws SQLException
{
/* 获取数据库配置property */
MyProperties properties = PropertiesUtil.loadPropertyFile(PropertiesConst.DB_CONFIG);
String className = String.valueOf(properties.getProperty("driverClassName",""));
String connUrl = String.valueOf(properties.getProperty("db_url",""));
String uname = String.valueOf(properties.getProperty("db_user",""));
String psw = String.valueOf(properties.getProperty("db_password",""));
System.out.println(className);
System.out.println(connUrl);
System.out.println(uname);
System.out.println(psw);
Properties result = new Properties();
result.put("driverClassName",className);
result.put("url",connUrl);
result.put("username",uname);
result.put("password",psw);
/* 其他配置 自然你也可以自己写property 然后获取set */
result.put("maxActive","30");
result.put("minIdle","3");
try
{
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(result);
}
catch (Exception e)
{
/* Druid数据库源对象产生失败后,取消初始化 */
try {uninitialize();} catch(Exception e2) {}
throw new JdbcException(e);
}
return dataSource.getConnection();
}
/* 取消初始化 */
public void uninitialize()
{
try
{
if (dataSource != null)
dataSource.close();
}
catch (Exception e)
{
throw new JdbcException(String.format("MyJDBCAppender uninitialize fail (%s)",e));
}
finally
{
super.close();
}
}
}