您好,登錄后才能下訂單哦!
/*
* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.
*/
package com.ygsoft.gris.mapp.materialmanage.impl.util;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.ygsoft.ecp.service.tool.StringUtil;
import com.ygsoft.gris.mapp.materialmanage.service.model.EngineeringMaterialsOutVO;
import com.ygsoft.gris.mapp.materialmanage.service.model.QueryConditionsVO;
import com.ygsoft.gris.mapp.materialmanage.service.model.SupplierInvoiceInfoVO;
import com.ygsoft.gris.mapp.materialmanage.service.model.SupplierZanguSupplies;
import com.ygsoft.gris.mapp.materialmanage.service.model.Tm0001CatalogsVO;
/**
* sqlService數(shù)據(jù)庫連接.<br>
*
* @author mapengfei <br>
* @version 1.0.0 2016年10月13日<br>
* @see
* @since JDK 1.5.0
*/
public class SqlServerDbConnectionUtil {
private static boolean ISTESTDATA = true;
/**
* 內(nèi)部 內(nèi)部懶加載類.<br>
*
* @author mapengfei <br>
* @version 1.0.0 2016年5月31日<br>
* @see
* @since JDK 1.5.0
*/
private static class LazyHolder {
private static final SqlServerDbConnectionUtil INSTANCE = new SqlServerDbConnectionUtil();
}
/**
* 單例新實(shí)現(xiàn)
*
* @return
*/
public static final SqlServerDbConnectionUtil getInstance() {
return LazyHolder.INSTANCE;
}
/**
* @param args
*/
public static void main(final String[] args) {
// TODO Auto-generated method stub
// SqlServerDbConnectionUtil util = new SqlServerDbConnectionUtil();
// util.dbConnection();
// List<EngineeringMaterialsOutVO> list =
// SqlServerDbConnectionUtil.findAllMaterialsOutByCondition(null);
List<ExcelModel> list = findExcelExportByCondition(null, "ZGWZ");
System.out.println(list);
}
/**
* 獲取數(shù)據(jù)庫鏈接
*
* @return
*/
private static Connection getCurrentConnecton() {
// 初始化連接池
ConnectionPool pool = getPool();
// 取得當(dāng)前鏈接
Connection conn = pool.getCurrentConnecton();
if (conn != null) {
return conn;
}
return null;
}
/**
* 單例模式初始化一個(gè)連接池
*
* @return
*/
public static ConnectionPool getPool() {
return ConnectionPoolManager.getInstance().getPool("sqllitePool");
}
/**
* 根據(jù)條件查詢
*
* @return
*/
public static List<EngineeringMaterialsOutVO> findAllMaterialsOutByCondition(
final QueryConditionsVO queryCondition) {
if (ISTESTDATA) {
return TestData.findAllMaterialsOutByCondition(queryCondition);
}
List<EngineeringMaterialsOutVO> list = new ArrayList<EngineeringMaterialsOutVO>();
Connection conn = null;
try {
conn = getCurrentConnecton();
Statement stat = conn.createStatement();
String sql = setQueryConditionsSql(queryCondition, "CLCK", 1000);
ResultSet rs = stat.executeQuery(sql);
EngineeringMaterialsOutVO out = null;
int i = 1;
while (rs.next()) {
out = new EngineeringMaterialsOutVO();
out.setNo("" + i);
out.setTotal(rs.getBigDecimal(7));
out.setProDefinition(!StringUtil.isNotEmptyString(rs.getString(3)) ? "" : rs.getString(3).toString()); // 工程界定
out.setNotTaxAmount(BigDecimal.valueOf(rs.getDouble(4)));
out.setProName(!StringUtil.isNotEmptyString(rs.getString(2)) ? "" : rs.getString(2).toString()); // 名稱
out.setProNumber(!StringUtil.isNotEmptyString(rs.getString(1)) ? "" : rs.getString(1).toString()); // 編碼
out.setTax(rs.getDouble(6));
out.setTaxRate(rs.getDouble(5));
list.add(out);
i++;
}
rs.close();
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeConnection(conn);
}
return list;
}
/**
* 暫估物資匯總
*
* @return
*/
public static List<SupplierZanguSupplies> findAllSupplierZanguSuppliesByCondition(
final QueryConditionsVO queryCondition) {
if (ISTESTDATA) {
return TestData.findAllSupplierZanguSuppliesByCondition(queryCondition);
}
List<SupplierZanguSupplies> list = new ArrayList<SupplierZanguSupplies>();
Connection conn = null;
try {
conn = getCurrentConnecton();
Statement stat = conn.createStatement();
String sql = setQueryConditionsSql(queryCondition, "ZGWZ", 1000);
ResultSet rs = stat.executeQuery(sql);
SupplierZanguSupplies out = null;
int i = 0;
while (rs.next()) {
out = new SupplierZanguSupplies();
out.setNo("" + i);
out.setInStoragePrice(rs.getBigDecimal(3)); // 入庫價(jià)款
out.setInvoicePrice(rs.getBigDecimal(7)); // 發(fā)票價(jià)款
// out.setNo(rs.getString(1));
out.setNotInvoicePrice(rs.getBigDecimal(8)); // 未×××價(jià)格
out.setPurAmount(rs.getBigDecimal(2)); // 采購金額
out.setSupplier(rs.getString(1));
out.setTax(rs.getBigDecimal(5));
out.setTaxRate(rs.getBigDecimal(4));
out.setTotalPrice(rs.getBigDecimal(6)); // 入庫價(jià)稅合計(jì)
list.add(out);
i++;
}
rs.close();
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeConnection(conn);
}
return list;
}
/**
* 導(dǎo)出數(shù)據(jù)獲取
*
* @param supplier
* @param startTime
* @param endTime
* @return
*/
public static List<ExcelModel> findExcelExportByCondition(final QueryConditionsVO queryCondition,
final String type) {
if (ISTESTDATA) {
return TestData.findExcelExportByCondition(queryCondition, type);
}
List<ExcelModel> list = new ArrayList<ExcelModel>();
List<Tm0001CatalogsVO> tm001s = SqlServerDbConnectionUtil.findProductTypeAll();
Connection conn = null;
try {
conn = getCurrentConnecton();
Statement stat = conn.createStatement();
String sql = setQueryConditionsSql(queryCondition, type, 100000);
ResultSet rs = stat.executeQuery(sql);
ExcelModel out = null;
int col = rs.getMetaData().getColumnCount();
int row = 1;
while (rs.next()) {
out = new ExcelModel();
List<ExcelModel> suns = new ArrayList<ExcelModel>();
for (int i = 1; i < col; i++) { // X軸
out = new ExcelModel();
Object obj = rs.getObject(i) != null ? rs.getObject(i) : "";
if ("FPXX".equals(type)) { // 發(fā)票
switch (i) {
case 8:
case 10:
case 12:
case 13:
case 15:
case 17:
case 18:
case 19:
obj = formatMoney(obj.toString(), 2, true);
break;
case 11:
obj = formatMoney(obj.toString(), 0, false) + "%";
break;
case 9:
case 14:
case 16:
obj = 0;
if (StringUtil.isNotEmptyString(obj.toString())) {
long num = Long.parseLong(obj.toString());
obj = num;
}
break;
default:
break;
}
out.setData(obj);
} else if ("ZGWZ".equals(type)) { // 暫估物資
if (i == 1) {
ExcelModel out_no = new ExcelModel();
out_no.setData(row);
suns.add(out_no);
}
switch (i) {
case 2:
case 3:
case 5:
case 6:
case 7:
case 8:
obj = formatMoney(obj.toString(), 2, true);
break;
case 4:
obj = formatMoney(obj.toString(), 0, false) + "%";
break;
default:
break;
}
out.setData(obj);
} else {
switch (i) {
case 5: // 稅率
obj = formatMoney(obj.toString(), 0, false) + "%";
break;
case 3:
String newProtype = "";
Object proType = rs.getString("proType");
List<String> protypes = new ArrayList<String>();
for (Tm0001CatalogsVO c : tm001s) {
if (proType.equals(c.getID())) { // 找到節(jié)點(diǎn)
newProtype += c.getDisplayName() + "-";
searchProType(tm001s, newProtype, c, protypes);
}
}
obj = protypes.get(0);
break;
case 4:
case 6:
case 7:
obj = (Object) formatMoney(obj.toString(), 2, true);
break;
default:
out.setData(obj);
break;
}
out.setData(obj);
}
suns.add(out);
}
out.setDataList(suns);
list.add(out);
row++;
}
rs.close();
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeConnection(conn);
}
return list;
}
/**
* 查詢所有的項(xiàng)目分類
*
* @return
*/
public static List<Tm0001CatalogsVO> findProductTypeAll() {
if (ISTESTDATA) {
return TestData.findProductTypeAll();
}
// 獲得測(cè)試數(shù)據(jù)
List<Tm0001CatalogsVO> list = new ArrayList<Tm0001CatalogsVO>();
Connection conn = null;
try {
conn = getCurrentConnecton();
Statement stat = conn.createStatement();
StringBuffer sql = new StringBuffer(" SELECT * FROM TM0001_Catalogs WHERE FieldID=109 ");
ResultSet rs = stat.executeQuery(sql.toString());
Tm0001CatalogsVO out = null;
while (rs.next()) {
out = new Tm0001CatalogsVO();
out.setID(rs.getString(1));
out.setName(rs.getString(2));
out.setDisplayName(rs.getString(3));
out.setParentID(rs.getString(4));
out.setFieldID(rs.getString(5));
out.setObjectID(rs.getString(6));
out.setLevel(rs.getString(7));
out.setComment(rs.getString(8));
list.add(out);
}
rs.close();
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeConnection(conn);
}
return list;
}
/**
* 查詢登錄信息的方法
*
* @return
*/
public Map<String, Object> getLoginNameAndStatus() {
Connection conn = null;
try {
conn = getCurrentConnecton();
Statement stat = conn.createStatement();
StringBuffer sql = new StringBuffer(" SELECT * FROM TM0001_Catalogs WHERE FieldID=109 ");
ResultSet rs = stat.executeQuery(sql.toString());
while (rs.next()) {
}
rs.close();
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeConnection(conn);
}
return null;
}
/**
*
* @param newNoInvoiceTax
* @return
*/
public static List<SupplierInvoiceInfoVO> findAllSupplierInvoiceInfoVOByCondition(
final QueryConditionsVO queryCondition) {
if (ISTESTDATA) {
return TestData.findAllSupplierInvoiceInfoVOByCondition(queryCondition);
}
List<SupplierInvoiceInfoVO> list = new ArrayList<SupplierInvoiceInfoVO>();
Connection conn = null;
try {
conn = getCurrentConnecton();
Statement stat = conn.createStatement();
String sql = setQueryConditionsSql(queryCondition, "FPXX", 1000);
ResultSet rs = stat.executeQuery(sql);
SupplierInvoiceInfoVO out = null;
int i = 1;
while (rs.next()) {
out = new SupplierInvoiceInfoVO();
out.setNo("" + i);
out.setEngineeringCode(rs.getString(5)); // 工程編碼
out.setEngineeringName(rs.getString(6)); // 工程名稱
out.setInStorageAmount(rs.getBigDecimal(13)); // 入庫金額
out.setInStorageNum(rs.getLong(9)); // 入庫數(shù)量
out.setInStoreAmount(rs.getBigDecimal(10)); // 入庫價(jià)款
out.setInvoiceAmount(rs.getBigDecimal(15)); // 發(fā)票金額
out.setInvoiceNum(rs.getLong(14)); // 發(fā)票數(shù)量
out.setMaterialCode(rs.getString(2)); // 物資編碼
out.setMaterialName(rs.getString(3));
out.setNoInvoiceAmount(rs.getBigDecimal(17)); // 未開票金額
out.setNoInvoiceNum(rs.getLong(16)); // 未開票數(shù)量
out.setNoInvoiceTax(rs.getBigDecimal(18));
out.setPurAmount(rs.getBigDecimal(8)); // 采購金額
out.setPurQuantity(rs.getLong(7)); // 采購數(shù)量
out.setSpecificationsModel(rs.getString(4)); // 規(guī)格型號(hào)
out.setSupplier(rs.getString(1)); // 供應(yīng)商
out.setTax(rs.getBigDecimal(12)); // 稅款
out.setTaxRate(rs.getBigDecimal(11)); // 稅率
out.setTotalPrice(rs.getBigDecimal(19)); // 價(jià)稅合計(jì)
list.add(out);
i++;
}
rs.close();
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeConnection(conn);
}
return list;
}
/**
* 測(cè)試連接
*/
@SuppressWarnings("unused")
private void dbConnection() {
Connection conn = null;
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
// String url =
// "jdbc:sqlserver://192.168.0.2:1433;DatabaseName=msdb";
// conn = DriverManager.getConnection(url, "sa", "lxm226855");
conn = getCurrentConnecton();
Statement stat = conn.createStatement();
// String sql = "call
// cq_gcclckhzb('1321','17','2013-10-21','2016-10-21')";
CallableStatement proc = conn.prepareCall("{call cq_gcclckhzb(?,?,?,?)}");
proc.setString(1, "1321");
proc.setString(2, "17");
proc.setString(3, "2013-10-21");
proc.setString(4, "2016-10-21");
// proc.registerOutParameter(5, Types.VARCHAR);
proc.execute();
ResultSet rs = stat.executeQuery("select * from temp_cq_gcclckhzb");
int col = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= col; i++) {
System.out.print(rs.getString(i) + "\t");
if ((i == 2) && (rs.getString(i).length() < 8)) {
System.out.print("\t");
}
}
System.out.println("");
}
rs.close();
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeConnection(conn);
}
}
/**
* 刪除一個(gè)連接池
*
* @param conn
*/
private static void closeConnection(final Connection conn) {
ConnectionPoolManager.getInstance().closeConnection("sqllitePool", conn);
}
/**
* 構(gòu)造查詢條件
*
* @param conditions
* @return
*/
private static String setQueryConditionsSql(final QueryConditionsVO conditions, final String type, final int top) {
StringBuffer sql = new StringBuffer();
if ("ZGWZ".equals(type)) { // 暫估物資
sql.append("SELECT TOP " + top + " * FROM CQ_GYSZGWZHZB WHERE 1=1 ");
} else if ("FPXX".equals(type)) { // 發(fā)票信息
sql.append("SELECT TOP " + top + " * FROM CQ_GYSFPXXTJB WHERE 1=1 ");
} else {
sql.append("SELECT TOP " + top + " * FROM CQ_GCCLCKHZB WHERE 1=1 ");
}
if (conditions != null) {
if (StringUtil.isNotEmptyString(conditions.getSupplier())) {
String[] supplier = conditions.getSupplier().split(",");
sql.append(" and (");
for (int i = 0; i < supplier.length; i++) {
sql.append(" supplier like '%" + supplier[i] + "%'");
if (i != supplier.length - 1) {
sql.append(" or ");
}
}
sql.append(" )");
}
if (StringUtil.isNotEmptyString(conditions.getMaterials())) { // 物資
String[] materials = conditions.getMaterials().split(",");
sql.append(" and (");
for (int i = 0; i < materials.length; i++) {
sql.append(" materials like '%" + materials[i] + "%'");
if (i != materials.length - 1) {
sql.append(" or ");
}
}
sql.append(" )");
}
if (StringUtil.isNotEmptyString(conditions.getProject())) { // 項(xiàng)目工程
String[] projects = conditions.getProject().split(",");
sql.append(" and (");
for (int i = 0; i < projects.length; i++) {
sql.append(" project like '%" + projects[i] + "%' ");
if (i != projects.length - 1) {
sql.append(" or ");
}
}
sql.append(" )");
}
if (StringUtil.isNotEmptyString(conditions.getTaxRate())) { // 稅率
String[] taxRates = conditions.getTaxRate().split(",");
sql.append(" and taxRate in ( ");
for (int i = 0; i < taxRates.length; i++) {
int taxRate = Integer.valueOf(taxRates[i].indexOf("%") > -1
? taxRates[i].substring(0, taxRates[i].length() - 1) : taxRates[i]);
if (i != taxRates.length - 1) {
sql.append(taxRate + ",");
} else {
sql.append(taxRate);
}
}
sql.append(" )");
}
if (StringUtil.isNotEmptyString(conditions.getProType())) { // 分類
String[] proTypes = conditions.getProType().split(",");
sql.append(" and proType in ( ");
for (int i = 0; i < proTypes.length; i++) {
if (i != proTypes.length - 1) {
sql.append("'" + proTypes[i] + "',");
} else {
sql.append("'" + proTypes[i] + "'");
}
}
sql.append(" )");
}
if (StringUtil.isNotEmptyString(conditions.getStartTime())) { // 起始日期
sql.append(" and BusinessDate >='" + conditions.getStartTime() + "'");
}
if (StringUtil.isNotEmptyString(conditions.getEndTime())) { // 結(jié)束日期
sql.append(" and BusinessDate <= '" + conditions.getEndTime() + "'");
}
}
sql.append(" order by rand()");
return sql.toString();
}
/**
* 格式化金額類型
*
* @param s
* 帶格式化字符串
* @param len
* 小數(shù)點(diǎn)保留長度
* @return
*/
public static String formatMoney(final String s, final int len, final boolean isEndTag) {
if (!StringUtil.isNotEmptyString(s) || s.length() < 1) {
return "";
}
NumberFormat formater = null;
double num = Double.parseDouble(s);
if (len == 0) {
formater = new DecimalFormat("###,###,###");
} else {
StringBuffer buff = new StringBuffer();
buff.append("###,###,###.");
for (int i = 0; i < len; i++) {
buff.append("#");
}
formater = new DecimalFormat(buff.toString());
}
String result = formater.format(num);
if (result.indexOf(".") == -1 && isEndTag) {
result = result + ".00";
}
return result;
}
private static void searchProType(final List<Tm0001CatalogsVO> list, String newProtype, final Tm0001CatalogsVO c,
final List<String> protypes) {
for (Tm0001CatalogsVO b : list) {
if (c.getParentID().equals(b.getID())) {
newProtype += b.getDisplayName() + "-";
if (Integer.valueOf(b.getLevel()) > 1) {
searchProType(list, newProtype, b, protypes);
} else {
String[] oldProTypes = newProtype.split("-");
StringBuffer proType = new StringBuffer();
for (int i = oldProTypes.length - 1; i >= 0; i--) {
if (i != 0) {
proType.append(oldProTypes[i] + "-");
} else {
proType.append(oldProTypes[i]);
}
}
protypes.add(proType.toString());
break;
}
}
}
}
}
/**************************************8ConnectionPool************/
/*
* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.
*/
package com.ygsoft.gris.mapp.materialmanage.impl.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import com.ygsoft.ecp.service.log.EcpLogFactory;
import com.ygsoft.ecp.service.log.IEcpLog;
/**
* 連接池基本處理.<br>
*
* @author mapengfei <br>
* @version 1.0.0 2016年5月12日<br>
* @see
* @since JDK 1.5.0
*/
public class ConnectionPool {
// 連接池配置屬性
private DBbean dbBean;
// 連接池活動(dòng)狀態(tài)
private boolean isActive = false;
// 記錄創(chuàng)建的總的連接數(shù)
private int contActive = 0;
// 空閑連接
private List<Connection> freeConnection = new Vector<Connection>();
// 活動(dòng)連接
private List<Connection> activeConnection = new Vector<Connection>();
// 將線程和連接綁定,保證事務(wù)能統(tǒng)一執(zhí)行
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
/**
* 日志
*/
private static final IEcpLog LOG = EcpLogFactory.getLog(ConnectionPool.class);
/**
* 構(gòu)造函數(shù)
*
* @param dbBean
*/
public ConnectionPool(final DBbean dbBean) {
super();
// 取得配置參數(shù)
this.dbBean = dbBean;
// 初始化鏈接池
if (contActive == 0) {
init();
} else {
if (LOG.isInfoEnabled()) {
LOG.info("連接池中已有鏈接,不能再初始化");
}
}
// 連接池校驗(yàn)
cheackPool();
}
// 初始化
public void init() {
// Class.forName(dbBean.getDriverName());
if (LOG.isInfoEnabled()) {
LOG.info("取得足夠數(shù)量的連接數(shù)");
}
// 取得足夠數(shù)量的連接數(shù)
for (int i = 0; i < dbBean.getInitConnections(); i++) {
// 獲得新的鏈接
Connection conn = newConnection();
// 初始化最小連接數(shù)
if (conn != null) {
if (LOG.isInfoEnabled()) {
LOG.info("寫入空閑的連接池集合表");
}
freeConnection.add(conn); // 寫入空閑的連接池集合表
// 連接池計(jì)數(shù)器
contActive++;
}
}
if (LOG.isInfoEnabled()) {
LOG.info("本次總共初始化" + contActive + "個(gè)鏈接.");
}
/**
* 設(shè)置連接池活動(dòng)狀態(tài)
*/
isActive = true;
}
/**
* 獲得當(dāng)前連接 當(dāng)前鏈接可以在線程中拿
*
* @return
*/
public Connection getCurrentConnecton() {
// 默認(rèn)線程里面取
Connection conn = threadLocal.get();
if (!isValid(conn)) {
conn = getConnection();
}
return conn;
}
/**
* 獲得連接
*
* @return
*/
public synchronized Connection getConnection() {
Connection conn = null;
try {
// 判斷是否超過最大連接數(shù)限制
if (contActive < this.dbBean.getMaxActiveConnections()) {
if (freeConnection.size() > 0) { // 空線程有沒被占用的
if (LOG.isInfoEnabled()) {
LOG.info("獲得空線程中的第一個(gè)鏈接給");
}
conn = freeConnection.get(0); // 獲得空線程中的第一個(gè)鏈接給
if (conn != null) {
if (LOG.isInfoEnabled()) {
LOG.info("將獲取到的鏈接賦給線程(線程是安全帶鎖的");
}
threadLocal.set(conn); // 將獲取到的鏈接賦給線程(線程是安全帶鎖的)
}
if (LOG.isInfoEnabled()) {
LOG.info("將線程池中的鏈接從空鏈接池中析出");
}
freeConnection.remove(0); // 將線程池中的鏈接從空鏈接池中析出
} else {
conn = newConnection(); // 如果沒有了空的鏈接數(shù),則重新創(chuàng)建一個(gè)鏈接
}
} else {
// 繼續(xù)獲得連接,直到從新獲得連接
if (LOG.isInfoEnabled()) {
LOG.info("由于鏈接已達(dá)到或超過設(shè)定的總的連接數(shù)上限故等待鏈接被定時(shí)器回收");
}
wait(this.dbBean.getConnTimeOut()); // 等待鏈接被定時(shí)器
conn = getConnection();
}
// 校驗(yàn)鏈接是否可用
if (isValid(conn)) {
activeConnection.add(conn); // 將鏈接添加到活動(dòng)的連接池中
contActive++; // 鏈接池
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return conn;
}
/**
* 獲得新連接
*
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
private synchronized Connection newConnection() {
Connection conn = null;
if (dbBean != null) {
try {
Class.forName(dbBean.getDriverName()).newInstance();
conn = DriverManager.getConnection(dbBean.getUrl(), dbBean.getUserName(), dbBean.getPassword());
} catch (ClassNotFoundException e) {
if (LOG.isInfoEnabled()) {
LOG.info("連接池驅(qū)動(dòng)獲取失敗");
}
e.printStackTrace();
} catch (SQLException e) {
if (LOG.isInfoEnabled()) {
LOG.info("DriverManager 鏈接失敗");
}
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
}
/**
* 釋放連接
*
* @param conn
* @throws SQLException
*/
public synchronized void releaseConn(final Connection conn) throws SQLException {
// 當(dāng)前空閑鏈接數(shù)大于設(shè)置的最大連接池?cái)?shù)時(shí)釋放部分連接池
if (LOG.isInfoEnabled()) {
LOG.info("當(dāng)前空閑鏈接數(shù)大于設(shè)置的最大連接池?cái)?shù)時(shí)釋放部分連接池");
}
if (isValid(conn) && !(freeConnection.size() > dbBean.getMaxConnections())) {
freeConnection.add(conn);
activeConnection.remove(conn);
contActive--;
threadLocal.remove();
// 喚醒所有正待等待的線程,去搶連接
if (LOG.isInfoEnabled()) {
LOG.info("調(diào)用notifyAll()方法喚醒所有正待等待的線程,去搶連接");
}
notifyAll();
} else {
if (LOG.isInfoEnabled()) {
LOG.info("由于該鏈接已被關(guān)閉或空閑連接池?cái)?shù)>設(shè)定的最大數(shù),這里采取強(qiáng)制關(guān)閉");
}
conn.close();
}
}
/**
* 判斷連接是否可用
*
* @param conn
* @return
*/
private boolean isValid(final Connection conn) {
try {
if (conn == null || conn.isClosed()) {
return false;
}
} catch (SQLException e) {
if (LOG.isInfoEnabled()) {
LOG.info("判斷連接是否可用時(shí)出現(xiàn)異常");
}
e.printStackTrace();
}
return true;
}
/**
* 銷毀連接池
*/
public synchronized void destroy() {
/**
* 銷毀空閑連接池
*/
for (Connection conn : freeConnection) {
try {
if (isValid(conn)) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 銷毀自定義連接池
*/
for (Connection conn : activeConnection) {
try {
if (isValid(conn)) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
isActive = false;
contActive = 0;
}
/**
* 連接池狀態(tài)
*
* @return
*/
public boolean isActive() {
return isActive;
}
/**
* 定時(shí)檢查連接池情況
*/
public void cheackPool() {
if (dbBean.isCheakPool()) {
if (LOG.isInfoEnabled()) {
LOG.info("開啟連接池定時(shí)檢查任務(wù),當(dāng)前設(shè)置的檢查頻率為" + dbBean.getPeriodCheck() + ",檢查間歇時(shí)間為" + dbBean.getLazyCheck());
}
// 啟動(dòng)一個(gè)定時(shí)器類的時(shí)鐘任務(wù),用于檢測(cè)當(dāng)前使用的線程情況
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// 1.對(duì)線程里面的連接狀態(tài)
// 2.連接池最小 最大連接數(shù)
// 3.其他狀態(tài)進(jìn)行檢查,因?yàn)檫@里還需要寫幾個(gè)線程管理的類,暫時(shí)就不添加了
if (LOG.isInfoEnabled()) {
LOG.info("空線池連接數(shù):" + freeConnection.size());
LOG.info("活動(dòng)連接數(shù)::" + activeConnection.size());
LOG.info("總的連接數(shù):" + contActive);
}
}
}, dbBean.getLazyCheck(), dbBean.getPeriodCheck());
}
}
}
/***********************************ConnectionPoolManager**********/
/*
* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.
*/
package com.ygsoft.gris.mapp.materialmanage.impl.util;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import com.ygsoft.ecp.service.log.EcpLogFactory;
import com.ygsoft.ecp.service.log.IEcpLog;
/**
* 連接池管理.<br>
*
* @author mapengfei <br>
* @version 1.0.0 2016年5月12日<br>
* @see
* @since JDK 1.5.0
*/
public class ConnectionPoolManager {
/**
* 連接池存放
*/
public Hashtable<String, ConnectionPool> pools = new Hashtable<String, ConnectionPool>();
/**
* 日志
*/
private static final IEcpLog LOG = EcpLogFactory.getLog(ConnectionPoolManager.class);
/**
* 構(gòu)造函數(shù)
*/
private ConnectionPoolManager() {
init();
}
/**
* 單例實(shí)現(xiàn)
*
* @return
*/
public static ConnectionPoolManager getInstance() {
return Singtonle.INSTANCE; // 啟動(dòng)單例模式
}
/**
*
* 啟用單例<br>
*
* @author mapengfei <br>
* @version 1.0.0 2016年5月12日<br>
* @see
* @since JDK 1.5.0
*/
private static class Singtonle {
private static ConnectionPoolManager INSTANCE = new ConnectionPoolManager();
}
/**
* 初始化所有的連接池
*/
public void init() {
/**
* 將連接池放入管理
*/
for (int i = 0; i < DBInitInfo.beans.size(); i++) {
DBbean bean = DBInitInfo.beans.get(i);
ConnectionPool pool = new ConnectionPool(bean);
if (pool != null) {
pools.put(bean.getPoolName(), pool); // 寫入集合
if (LOG.isInfoEnabled()) {
LOG.info("信息:初始化連接池成功 ->" + bean.getPoolName());
}
}
}
}
/**
* 獲得連接,根據(jù)連接池名字 獲得連接
*
* @param poolName
* 連接池名稱
* @return
*/
public Connection getConnection(final String poolName) {
Connection conn = null;
if (pools.size() > 0 && pools.containsKey(poolName)) {
conn = getPool(poolName).getConnection();
} else {
if (LOG.isInfoEnabled()) {
LOG.info("Error:沒有找到該鏈接 ->" + poolName);
}
}
return conn;
}
/**
* 關(guān)閉,回收連接
*
* @param poolName
* 連接池名稱
* @param conn
* 鏈接
*/
public void closeConnection(final String poolName, final Connection conn) {
if (LOG.isInfoEnabled()) {
LOG.info("啟動(dòng)鏈接關(guān)閉回收機(jī)制 來關(guān)閉名為"+poolName+"的連接池的鏈接"+conn);
}
ConnectionPool pool = getPool(poolName);
try {
if (pool != null) {
pool.releaseConn(conn);
}
} catch (SQLException e) {
if (LOG.isInfoEnabled()) {
LOG.info("連接池已經(jīng)銷毀");
}
e.printStackTrace();
}
}
/**
* 清空連接池
*
* @param poolName
* 連接池名稱
*/
public void destroy(final String poolName) {
ConnectionPool pool = getPool(poolName);
if (pool != null) {
pool.destroy();
}
}
/**
* 獲得連接池
*
* @param poolName
* 連接池名稱
* @return
*/
public ConnectionPool getPool(final String poolName) {
ConnectionPool pool = null;
if (pools.size() > 0) {
pool = pools.get(poolName);
}
return pool;
}
}
/****************************DBbean******************/
package com.ygsoft.gris.mapp.materialmanage.impl.util;
/**
* 這是外部可以配置的連接池屬性
* 可以允許外部配置,擁有默認(rèn)值
* @author Ran
*
*/
public class DBbean {
// 連接池屬性
private String driverName;
private String url;
private String userName;
private String password;
private String poolName; // 鏈接池的名稱
private int minConnections = 1; // 空閑池,最小連接數(shù)
private int maxConnections = 10; // 空閑池,最大連接數(shù)
private int initConnections = 5;// 初始化連接數(shù)
private long connTimeOut = 1000;// 重復(fù)獲得連接的頻率
private int maxActiveConnections = 10;// 最大允許的連接數(shù),和數(shù)據(jù)庫對(duì)應(yīng)
private long connectionTimeOut = 1000*60;// 連接超時(shí)時(shí)間,默認(rèn)1分鐘
private boolean isCurrentConnection = true; // 是否獲得當(dāng)前連接,默認(rèn)true
private boolean isCheakPool = true; // 是否定時(shí)檢查連接池
private long lazyCheck = 1000*60;// 延遲多少時(shí)間后開始 檢查
private long periodCheck = 1000*60;// 檢查頻率
/**
*
* @param driverName 驅(qū)動(dòng)名稱
* @param url
* @param userName
* @param password
* @param poolName 連接池名稱
*/
public DBbean(final String driverName, final String url, final String userName,final String password, final String poolName) {
super();
this.driverName = driverName;
this.url = url;
this.userName = userName;
this.password = password;
this.poolName = poolName;
}
public DBbean() {
}
public String getDriverName() {
if(driverName == null){
driverName = this.getDriverName()+"_"+this.getUrl();
}
return driverName;
}
/**
* 獲取url.
* @return the url
*/
public String getUrl() {
return url;
}
/**
* 設(shè)置url.
* @param newUrl the url to set
*/
public void setUrl(final String newUrl) {
url = newUrl;
}
/**
* 獲取userName.
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* 設(shè)置userName.
* @param newUserName the userName to set
*/
public void setUserName(final String newUserName) {
userName = newUserName;
}
/**
* 獲取password.
* @return the password
*/
public String getPassword() {
return password;
}
/**
* 設(shè)置password.
* @param newPassword the password to set
*/
public void setPassword(final String newPassword) {
password = newPassword;
}
/**
* 獲取poolName.
* @return the poolName
*/
public String getPoolName() {
return poolName;
}
/**
* 設(shè)置poolName.
* @param newPoolName the poolName to set
*/
public void setPoolName(final String newPoolName) {
poolName = newPoolName;
}
/**
* 獲取minConnections.
* @return the minConnections
*/
public int getMinConnections() {
return minConnections;
}
/**
* 設(shè)置minConnections.
* @param newMinConnections the minConnections to set
*/
public void setMinConnections(final int newMinConnections) {
minConnections = newMinConnections;
}
/**
* 獲取maxConnections.
* @return the maxConnections
*/
public int getMaxConnections() {
return maxConnections;
}
/**
* 設(shè)置maxConnections.
* @param newMaxConnections the maxConnections to set
*/
public void setMaxConnections(final int newMaxConnections) {
maxConnections = newMaxConnections;
}
/**
* 獲取initConnections.
* @return the initConnections
*/
public int getInitConnections() {
return initConnections;
}
/**
* 設(shè)置initConnections.
* @param newInitConnections the initConnections to set
*/
public void setInitConnections(final int newInitConnections) {
initConnections = newInitConnections;
}
/**
* 獲取connTimeOut.
* @return the connTimeOut
*/
public long getConnTimeOut() {
return connTimeOut;
}
/**
* 設(shè)置connTimeOut.
* @param newConnTimeOut the connTimeOut to set
*/
public void setConnTimeOut(final long newConnTimeOut) {
connTimeOut = newConnTimeOut;
}
/**
* 獲取maxActiveConnections.
* @return the maxActiveConnections
*/
public int getMaxActiveConnections() {
return maxActiveConnections;
}
/**
* 設(shè)置maxActiveConnections.
* @param newMaxActiveConnections the maxActiveConnections to set
*/
public void setMaxActiveConnections(final int newMaxActiveConnections) {
maxActiveConnections = newMaxActiveConnections;
}
/**
* 獲取connectionTimeOut.
* @return the connectionTimeOut
*/
public long getConnectionTimeOut() {
return connectionTimeOut;
}
/**
* 設(shè)置connectionTimeOut.
* @param newConnectionTimeOut the connectionTimeOut to set
*/
public void setConnectionTimeOut(final long newConnectionTimeOut) {
connectionTimeOut = newConnectionTimeOut;
}
/**
* 獲取isCurrentConnection.
* @return the isCurrentConnection
*/
public boolean isCurrentConnection() {
return isCurrentConnection;
}
/**
* 設(shè)置isCurrentConnection.
* @param newIsCurrentConnection the isCurrentConnection to set
*/
public void setCurrentConnection(final boolean newIsCurrentConnection) {
isCurrentConnection = newIsCurrentConnection;
}
/**
* 獲取isCheakPool.
* @return the isCheakPool
*/
public boolean isCheakPool() {
return isCheakPool;
}
/**
* 設(shè)置isCheakPool.
* @param newIsCheakPool the isCheakPool to set
*/
public void setCheakPool(final boolean newIsCheakPool) {
isCheakPool = newIsCheakPool;
}
/**
* 獲取lazyCheck.
* @return the lazyCheck
*/
public long getLazyCheck() {
return lazyCheck;
}
/**
* 設(shè)置lazyCheck.
* @param newLazyCheck the lazyCheck to set
*/
public void setLazyCheck(final long newLazyCheck) {
lazyCheck = newLazyCheck;
}
/**
* 獲取periodCheck.
* @return the periodCheck
*/
public long getPeriodCheck() {
return periodCheck;
}
/**
* 設(shè)置periodCheck.
* @param newPeriodCheck the periodCheck to set
*/
public void setPeriodCheck(final long newPeriodCheck) {
periodCheck = newPeriodCheck;
}
/**
* 設(shè)置driverName.
* @param newDriverName the driverName to set
*/
public void setDriverName(final String newDriverName) {
driverName = newDriverName;
}
}
/********************************************DBInitInfo********************/
/*
* Copyright 2000-2020 YGSoft.Inc All Rights Reserved.
*/
package com.ygsoft.gris.mapp.materialmanage.impl.util;
import java.util.ArrayList;
import java.util.List;
import com.ygsoft.gris.mapp.materialmanage.impl.ext.config.BaseConfig;
/**
* 初始化,模擬加載所有的配置文件 .<br>
* @author mapengfei <br>
* @version 1.0.0 2016年5月12日<br>
* @see
* @since JDK 1.5.0
*/
public class DBInitInfo {
public static List<DBbean> beans = null;
static{
beans = new ArrayList<DBbean>();
// 這里數(shù)據(jù) 可以從xml 等配置文件進(jìn)行獲取
// 為了測(cè)試,這里我直接寫死
DBbean beanOracle = new DBbean();
beanOracle.setDriverName(BaseConfig.get("DriverName"));
beanOracle.setUrl(BaseConfig.get("JdbcUrl"));
beanOracle.setMinConnections(Integer.valueOf(BaseConfig.get("MinConnections")));
beanOracle.setMaxConnections(Integer.valueOf(BaseConfig.get("MaxConnections")));
beanOracle.setPoolName(BaseConfig.get("PoolName"));
beanOracle.setUserName(BaseConfig.get("dbusername"));
beanOracle.setPassword(BaseConfig.get("dbpassword"));
beans.add(beanOracle);
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。