initial commit
This commit is contained in:
78
src/com/nms/server/util/DruidPool.java
Normal file
78
src/com/nms/server/util/DruidPool.java
Normal file
@@ -0,0 +1,78 @@
|
||||
package com.nms.server.util;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import com.nms.server.common.Constants;
|
||||
|
||||
public class DruidPool {
|
||||
private static DruidDataSource ds;
|
||||
private static Logger logger = Logger.getLogger(DruidPool.class);
|
||||
|
||||
public static void initPool() throws SQLException {
|
||||
URL urlObj = DruidPool.class.getClassLoader().getResource("druid.properties");
|
||||
Properties properties = new Properties();
|
||||
if(urlObj==null){
|
||||
System.err.println("找不到配置文件:druid.properties");
|
||||
logger.error("No configuration file can be found: druid.properties");
|
||||
System.exit(0);
|
||||
}else{
|
||||
try {
|
||||
properties.load(new FileInputStream(urlObj.getPath().replaceAll("%20", " ")));
|
||||
logger.debug("配置文件:druid.properties 加载完成");
|
||||
} catch (IOException e) {
|
||||
logger.error("Reading properties file error"+"",e);
|
||||
}
|
||||
|
||||
}
|
||||
ds = new DruidDataSource();
|
||||
ds.setUrl(Constants.DB_URL);
|
||||
ds.setDriverClassName(Constants.DB_DRIVER);
|
||||
ds.setUsername(Constants.DB_USER_NAME);
|
||||
ds.setPassword(Constants.DB_PASSWORD);
|
||||
ds.configFromPropety(properties);
|
||||
ds.setName("Druid连接池");
|
||||
ds.init();
|
||||
logger.debug("Druid初始化连接池成功,"+ds.toString());
|
||||
}
|
||||
|
||||
|
||||
public static Connection getConnection() throws SQLException{
|
||||
Connection connection = ds.getConnection();
|
||||
logger.debug("获取连接成功");
|
||||
boolean closed = connection.isClosed();
|
||||
if( closed){
|
||||
logger.warn("connection.toString()->" + connection.toString());
|
||||
}
|
||||
logger.debug("closed("+closed+"),autoCommit="+connection.getAutoCommit()+", "+ ds.toString());
|
||||
connection.setAutoCommit(true);
|
||||
return connection;
|
||||
}
|
||||
|
||||
|
||||
public static void shutdown(){
|
||||
if(ds != null){
|
||||
ds.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
initPool();
|
||||
Connection connection = getConnection();
|
||||
System.out.println(connection);
|
||||
} catch (SQLException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user