|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
他们对jsp,servlet,javabean进行封装就是为了展示他们的某个思想,与java的开发并没有必然的关系,也不见得在所以情况下,别人使用起来会简单。//文件:DbConnectionDefaultPool.java的第一部分
//请注重看内里说明的一处必要修正毗连参数的中央
packagecom.qingtuo.db.pool;
importjava.sql.*;
importjava.util.*;
importjava.io.*;
importjava.text.*;
importjava.util.Date;
/**
*DefaultJiveconnectionprovider.Itusestheexcellentconnectionpool
*availablefromhttp://www.javaexchange.com.Thisconnectionproviderisa
*agoodchoiceunlessyoucanuseacontainer-managedone.
*/
publicclassDbConnectionDefaultPoolextendsDbConnectionProvider{
privatestaticfinalStringNAME="DefaultConnectionPool";
privatestaticfinalStringDESCRIPTION="Thedefaultconnectionprovider"
+"thatusestheconnectionpoolfromjavaexchange.com.Itworkswith"
+"almostanydatabasesetup,iscustomizable,andoffersgoodperformance."
+"Usethisconnectionproviderunlessyouhaveyourownorcanusea"
+"containermanagedconnectionpool.";
privatestaticfinalStringAUTHOR="CoolServlets.com";
privatestaticfinalintMAJOR_VERSION=1;
privatestaticfinalintMINOR_VERSION=0;
privatestaticfinalbooleanPOOLED=true;
privateConnectionPoolconnectionPool=null;
privatePropertiesprops;
privatePropertiespropDescriptions;
privateObjectinitLock=newObject();
publicDbConnectionDefaultPool(){
//this.manager=manager;
props=newProperties();
propDescriptions=newProperties();
//Initializeallpropertyvalues
initializeProperties();
//Loadanyexistingpropertyvalues
loadProperties();
}
/**
*Returnsadatabaseconnection.
*/
publicConnectiongetConnection(){
if(connectionPool==null){
//blockuntiltheinithasbeendone
synchronized(initLock){
//ifstillnull,somethinghasgonewrong
if(connectionPool==null){
System.err.println("Warning:DbConnectionDefaultPool.getConnection()was"+
"calledwhentheinternalpoolhasnotbeeninitialized.");
returnnull;
}
}
}
returnnewConnectionWrapper(connectionPool.getConnection(),connectionPool);
}
/**
*Startsthepool.
*/
protectedvoidstart(){
//acquirelocksothatnoconnectionscanbereturned.
synchronized(initLock){
//Getproperties
Stringdriver=props.getProperty("driver");
Stringserver=props.getProperty("server");
Stringusername=props.getProperty("username");
Stringpassword=props.getProperty("password");
intminConnections=0,maxConnections=0;
doubleconnectionTimeout=0.0;
try{
minConnections=Integer.parseInt(props.getProperty("minConnections"));
maxConnections=Integer.parseInt(props.getProperty("maxConnections"));
connectionTimeout=Double.parseDouble(props.getProperty("connectionTimeout"));
}
catch(Exceptione){
System.err.println("Error:couldnotparsedefaultpoolproperties."+
"Makesurethevaluesexistandarecorrect.");
e.printStackTrace();
return;
}
StringlogPath=props.getProperty("logPath");
try{
connectionPool=newConnectionPool(driver,server,username,password,
minConnections,maxConnections,logPath,connectionTimeout);
}
catch(IOExceptionioe){
System.err.println("ErrorstartingDbConnectionDefaultPool:"+ioe);
ioe.printStackTrace();
}
}
}
/**
*Restartsthepooltotakeintoaccountanypropertychanges.
*/
protectedvoidrestart(){
//Killoffpool.
destroy();
//Reloadproperties.
loadProperties();
//Startanewpool.
start();
}
/**
*Destroystheconnectionpool.
*/
protectedvoiddestroy(){
if(connectionPool!=null){
try{
connectionPool.destroy(1);
}
catch(Exceptione){
e.printStackTrace();
}
}
//ReleasereferencetoconnectionPool
connectionPool=null;
}
/**
*Returnsthevalueofapropertyoftheconnectionprovider.
*
*@paramnamethenameoftheproperty.
*@returnsthevalueoftheproperty.
*/
publicStringgetProperty(Stringname){
return(String)props.get(name);
}
/**
*Returnsthedescriptionofapropertyoftheconnectionprovider.
*
*@paramnamethenameoftheproperty.
*@returnthedescriptionoftheproperty.
*/
publicStringgetPropertyDescription(Stringname){
return(String)propDescriptions.get(name);
}
/**
*Returnsanenumerationofthepropertynamesfortheconnectionprovider.
*/
publicEnumerationpropertyNames(){
returnprops.propertyNames();
}
/**
*Setsapropertyoftheconnectionprovider.Eachproviderhasasetnumber
*ofpropertiesthataredeterminedbytheauthor.Tryingtosetanon-
*existantpropertywillresultinanIllegalArgumentException.
*
*@paramnamethenameofthepropertytoset.
*@paramvaluethenewvaluefortheproperty.
*
*/
publicvoidsetProperty(Stringname,Stringvalue){
props.put(name,value);
saveProperties();
}
/**
*Givedefaultvaluestoallthepropertiesanddescriptions.
*/
privatevoidinitializeProperties(){
props.put("driver","");
props.put("server","");
props.put("username","");
props.put("password","");
props.put("minConnections","");
props.put("maxConnections","");
props.put("logPath","");
props.put("connectionTimeout","");
propDescriptions.put("driver","JDBCdriver.e.g.oracle.jdbc.driver.OracleDriver");
propDescriptions.put("server","JDBCconnectstring.e.g.jdbc:oracle:thin:@203.92.21.109:1526:orcl");
propDescriptions.put("username","Databaseusername.e.g.Scott");
propDescriptions.put("password","Databasepassword.e.g.Tiger");
propDescriptions.put("minConnections","Minimum#ofconnectionstostartwithinpool.Threeistherecommendedminimum");
propDescriptions.put("maxConnections","Maximum#ofconnectionsindynamicpool.Fifteenshouldgivegoodperformanceforanaverageload.");
propDescriptions.put("logPath","Absolutepathnameforlogfile.e.g.c:logsjiveDbLog.log");
propDescriptions.put("connectionTimeout","Timeindaysbetweenconnectionresets.e.g..5");
}
/**
*Loadwhateverpropertiesthatalreadyexist.
*/
privatevoidloadProperties(){
//在这里修正一些毗连参数
//in2000
/*
Stringdriver="org.gjt.mm.mysql.Driver";
Stringserver="jdbc:mysql://192.100.100.11/pcc";
Stringusername="pcc";
Stringpassword="pcc123";
StringminConnections="3";
StringmaxConnections="10";
StringlogPath="c: empqingtuoDbLog.log";
StringconnectionTimeout="0.5";
*/
//inLinux
Stringdriver="org.gjt.mm.mysql.Driver";
Stringserver="jdbc:mysql://192.100.100.1/qingtuo";
//Stringserver="jdbc:mysql://192.168.0.1/qingtuo";
Stringusername="qingtuo";
Stringpassword="qingtuo";
StringminConnections="3";
StringmaxConnections="20";
StringlogPath="c: empqingtuoDbLog.log";
//StringlogPath="/tmp/qingtuoDbLog.log";
StringconnectionTimeout="0.5";
if(driver!=null){props.setProperty("driver",driver);}
if(server!=null){props.setProperty("server",server);}
if(username!=null){props.setProperty("username",username);}
if(password!=null){props.setProperty("password",password);}
//if(database!=null){props.setProperty("database",database);}
if(minConnections!=null){props.setProperty("minConnections",minConnections);}
if(maxConnections!=null){props.setProperty("maxConnections",maxConnections);}
if(logPath!=null){props.setProperty("logPath",logPath);}
if(connectionTimeout!=null){props.setProperty("connectionTimeout",connectionTimeout);}
}
privatevoidsaveProperties(){
PropertyManager.setProperty("DbConnectionDefaultPool.driver",props.getProperty("driver"));
PropertyManager.setProperty("DbConnectionDefaultPool.server",props.getProperty("server"));
PropertyManager.setProperty("DbConnectionDefaultPool.username",props.getProperty("username"));
PropertyManager.setProperty("DbConnectionDefaultPool.password",props.getProperty("password"));
PropertyManager.setProperty("DbConnectionDefaultPool.minConnections",props.getProperty("minConnections"));
PropertyManager.setProperty("DbConnectionDefaultPool.maxConnections",props.getProperty("maxConnections"));
PropertyManager.setProperty("DbConnectionDefaultPool.logPath",props.getProperty("logPath"));
PropertyManager.setProperty("DbConnectionDefaultPool.connectionTimeout",props.getProperty("connectionTimeout"));
}
privateclassConnectionPoolimplementsRunnable{
privateThreadrunner;
privateConnection[]connPool;
privateint[]connStatus;
privatelong[]connLockTime,connCreateDate;
privateString[]connID;
privateStringdbDriver,dbServer,dbLogin,dbPassword,logFileString;
privateintcurrConnections,connLast,minConns,maxConns,maxConnMSec;
//available:settofalseondestroy,checkedbygetConnection()
privatebooleanavailable=true;
privatePrintWriterlog;
privateSQLWarningcurrSQLWarning;
privateStringpid;
/**
*CreatesanewConnectionBroker<br>
*dbDriver:JDBCdriver.e.g.oracle.jdbc.driver.OracleDriver<br>
*dbServer:JDBCconnectstring.e.g.jdbc:oracle:thin:@203.92.21.109:1526:orcl<br>
*dbLogin:Databaseloginname.e.g.Scott<br>
*dbPassword:Databasepassword.e.g.Tiger<br>
*minConns:Minimumnumberofconnectionstostartwith.<br>
*maxConns:Maximumnumberofconnectionsindynamicpool.<br>
*logFileString:Absolutepathnameforlogfile.e.g.c: empmylog.log<br>
*maxConnTime:Timeindaysbetweenconnectionresets.(Resetdoesabasiccleanup)<br>
*/
publicConnectionPool(StringdbDriver,StringdbServer,StringdbLogin,
StringdbPassword,intminConns,intmaxConns,
StringlogFileString,doublemaxConnTime)throwsIOException
{
connPool=newConnection[maxConns];
connStatus=newint[maxConns];
connLockTime=newlong[maxConns];
connCreateDate=newlong[maxConns];
connID=newString[maxConns];
currConnections=minConns;
this.maxConns=maxConns;
this.dbDriver=dbDriver;
this.dbServer=dbServer;
this.dbLogin=dbLogin;
this.dbPassword=dbPassword;
this.logFileString=logFileString;
maxConnMSec=(int)(maxConnTime*86400000.0);//86400sec/day
if(maxConnMSec<30000){//Recyclenolessthan30seconds.
maxConnMSec=30000;
}
try{
log=newPrintWriter(newFileOutputStream(logFileString),true);
//Cantopentherequestedfile.Openthedefaultfile.
}
catch(IOExceptione1){
System.err.println("Warning:DbConnectionDefaultPoolcouldnotopen""
+logFileString+""towritelogto.MakesurethatyourJava"+
"processhaspermissiontowritetothefileandthatthedirectoryexists."
);
try{
log=newPrintWriter(newFileOutputStream("DCB_"+
System.currentTimeMillis()+".log"),true
);
}
catch(IOExceptione2){
thrownewIOException("Cantopenanylogfile");
}
}
//Writethepidfile(usedtocleanupdead/brokenconnection)
SimpleDateFormatformatter
=newSimpleDateFormat("yyyy.MM.ddGathh:mm:ssazzz");
java.util.Datenowc=newjava.util.Date();
pid=formatter.format(nowc);
BufferedWriterpidout=newBufferedWriter(new
FileWriter(logFileString+"pid"));
pidout.write(pid);
pidout.close();
log.println("StartingConnectionPool:");
log.println("dbDriver="+dbDriver);
log.println("dbServer="+dbServer);
log.println("dbLogin="+dbLogin);
log.println("logfile="+logFileString);
log.println("minconnections="+minConns);
log.println("maxconnections="+maxConns);
log.println("Totalrefreshinterval="+maxConnTime+"days");
log.println("-----------------------------------------");
//Initializethepoolofconnectionswiththemininumconnections:
//Problemscreatingconnectionsmaybecausedduringrebootwhenthe
//servletisstartedbeforethedatabaseisready.Handlethis
//bywaitingandtryingagain.Theloopallows5minutesfor
//dbreboot.
booleanconnectionsSucceeded=false;
intdbLoop=20;
try{
for(inti=1;i<dbLoop;i++){
try{
for(intj=0;j<currConnections;j++){
log.println("CreateConn"+j);
createConn(j);
}
connectionsSucceeded=true;
break;
}
catch(SQLExceptione){
log.println("--->Attempt("+String.valueOf(i)+
"of"+String.valueOf(dbLoop)+
")failedtocreatenewconnectionssetatstartup:");
log.println(""+e);
log.println("Willtryagainin15seconds...");
try{Thread.sleep(15000);}
catch(InterruptedExceptione1){}
}
}
if(!connectionsSucceeded){//Allattemptsatconnectingtodbexhausted
log.println("
AllattemptsatconnectingtoDatabaseexhausted");
thrownewIOException();
}
}
catch(Exceptione){
thrownewIOException();
}
//Fireupthebackgroundhousekeepingthread
runner=newThread(this);
runner.start();
}//EndConnectionPool()
//文件:DbConnectionDefaultPool.java的第二部分
/**
*Housekeepingthread.RunsinthebackgroundwithlowCPUoverhead.
*Connectionsarecheckedforwarningsandclosureandareperiodically
*restarted.
*Thisthreadisacatchallforcorrupted
*connectionsandpreventsthebuildupofopencursors.(Opencursors
*resultwhentheapplicationfailstocloseaStatement).
*Thismethodactsasfaulttoleranceforbadconnection/statementprogramming.
*/
publicvoidrun(){
booleanforever=true;
Statementstmt=null;
StringcurrCatalog=null;
while(forever){
//Makesurethelogfileistheonethisinstanceopened
//Ifnot,cleanitup!
try{
BufferedReaderin=newBufferedReader(new
FileReader(logFileString+"pid"));
Stringcurr_pid=in.readLine();
if(curr_pid.equals(pid)){
//log.println("Theymatch="+curr_pid);
}
else{
//log.println("Nomatch="+curr_pid);
log.close();
//Closeallconnectionssilently-theyaredefinitelydead.
for(inti=0;i<currConnections;i++){
try{
connPool[i].close();
}
catch(SQLExceptione1){}//ignore
}
//Returningfromtherun()methodkillsthethread
return;
}
in.close();
}
catch(IOExceptione1){
log.println("Cantreadthefileforpidinfo:"+
logFileString+"pid");
}
//GetanyWarningsonconnectionsandprinttoeventfile
for(inti=0;i<currConnections;i++){
try{
currSQLWarning=connPool[i].getWarnings();
if(currSQLWarning!=null){
log.println("Warningsonconnection"+
String.valueOf(i)+""+currSQLWarning);
connPool[i].clearWarnings();
}
}
catch(SQLExceptione){
log.println("CannotaccessWarnings:"+e);
}
}
for(inti=0;i<currConnections;i++){//Doforeachconnection
longage=System.currentTimeMillis()-connCreateDate[i];
synchronized(connStatus){
if(connStatus[i]>0){//Inuse,catchitnexttime!
continue;
}
connStatus[i]=2;//Takeoffline(2indicateshousekeepinglock)
}
try{//TesttheconnectionwithcreateStatementcall
if(age>maxConnMSec){//Forcearesetatthemaxconntime
thrownewSQLException();
}
stmt=connPool[i].createStatement();
connStatus[i]=0;//ConnectionisO.K.
//log.println("Connectionconfirmedforconn="+
//String.valueOf(i));
//SomeDBsreturnanobjectevenifDBisshutdown
if(connPool[i].isClosed()){
thrownewSQLException();
}
//Connectionhasaproblem,restartit
}
catch(SQLExceptione){
try{
log.println(newDate().toString()+
"*****Recyclingconnection"+
String.valueOf(i)+":");
connPool[i].close();
createConn(i);
}
catch(SQLExceptione1){
log.println("Failed:"+e1);
connStatus[i]=0;//Cantopen,tryagainnexttime
}
}
finally{
try{
if(stmt!=null){
stmt.close();
}
}
catch(SQLExceptione1){};
}
}
try{
Thread.sleep(20000);
}//Wait20secondsfornextcycle
catch(InterruptedExceptione){
//Returningfromtherunmethodsetstheinternal
//flagreferencedbyThread.isAlive()tofalse.
//Thisisrequiredbecausewedontusestop()to
//shutdownthisthread.
return;
}
}
}//Endrun
还得说上一点,就java本质而言,是面相对象的,但是你有没有发现,java也不全是,比如说基本类型,int,那他就是整型而不是对象,转换类型是还得借助包装类。 |
|