仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1074|回复: 19
打印 上一主题 下一主题

[学习教程] JAVA网页设计一个毗连池的例子 (一)

[复制链接]
爱飞 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:37:44 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

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,那他就是整型而不是对象,转换类型是还得借助包装类。
兰色精灵 该用户已被删除
沙发
发表于 2015-1-21 11:33:27 | 只看该作者
Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台
莫相离 该用户已被删除
板凳
发表于 2015-1-28 09:32:00 | 只看该作者
是一种使网页(Web Page)产生生动活泼画面的语言
透明 该用户已被删除
地板
发表于 2015-2-5 10:53:54 | 只看该作者
所以现在应用最广泛又最好学的就是J2EE了。 J2EE又包括许多组件,如Jsp,Servlet,JavaBean,EJB,JDBC,JavaMail等。要学习起来可不是一两天的事。那么又该如何学习J2EE呢?当然Java语法得先看一看的,I/O包,Util包,Lang包你都熟悉了吗?然后再从JSP学起。
深爱那片海 该用户已被删除
5#
发表于 2015-2-11 09:16:06 | 只看该作者
还好,SUN提供了Javabean可以把你的JSP中的 Java代码封装起来,便于调用也便于重用。
第二个灵魂 该用户已被删除
6#
发表于 2015-2-24 19:21:20 | 只看该作者
一直感觉JAVA很大,很杂,找不到学习方向,前两天在网上找到了这篇文章,感觉不错,给没有方向的我指了一个方向,先不管对不对,做下来再说。
灵魂腐蚀 该用户已被删除
7#
发表于 2015-3-7 12:59:46 | 只看该作者
接着就是EJB了,EJB就是Enterprise JavaBean, 看名字好象它是Javabean,可是它和Javabean还是有区别的。它是一个体系结构,你可以搭建更安全、更稳定的企业应用。它的大量代码已由中间件(也就是我们常听到的 Weblogic,Websphere这些J2EE服务器)完成了,所以我们要做的程序代码量很少,大部分工作都在设计和配置中间件上。
变相怪杰 该用户已被删除
8#
发表于 2015-3-8 15:34:24 | 只看该作者
学Java必读的两个开源程序就是Jive和Pet Store.。 Jive是国外一个非常著名的BBS程序,完全开放源码。论坛的设计采用了很多先进的技术,如Cache、用户认证、Filter、XML等,而且论坛完全屏蔽了对数据库的访问,可以很轻易的在不同数据库中移植。论坛还有方便的安装和管理程序,这是我们平时编程时容易忽略的一部份(中国程序员一般只注重编程的技术含量,却完全不考虑用户的感受,这就是我们与国外软件的差距所在)。
乐观 该用户已被删除
9#
发表于 2015-3-16 03:29:14 | 只看该作者
Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。
爱飞 该用户已被删除
10#
 楼主| 发表于 2015-3-16 13:07:30 | 只看该作者
应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展
简单生活 该用户已被删除
11#
发表于 2015-3-22 23:08:03 | 只看该作者
我大二,Java也只学了一年,觉得还是看thinking in java好,有能力的话看英文原版(中文版翻的不怎么好),还能提高英文文档阅读能力。
不帅 该用户已被删除
12#
发表于 2015-3-24 21:38:23 | 只看该作者
有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想)
只想知道 该用户已被删除
13#
发表于 2015-4-6 19:10:14 | 只看该作者
设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧
再现理想 该用户已被删除
14#
发表于 2015-4-13 11:20:36 | 只看该作者
Java是一种计算机编程语言,拥有跨平台、面向对java
愤怒的大鸟 该用户已被删除
15#
发表于 2015-4-28 02:20:28 | 只看该作者
是一种使网页(Web Page)产生生动活泼画面的语言
若相依 该用户已被删除
16#
发表于 2015-4-28 10:17:18 | 只看该作者
如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。
冷月葬花魂 该用户已被删除
17#
发表于 2015-5-4 10:14:30 | 只看该作者
是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能
飘灵儿 该用户已被删除
18#
发表于 2015-5-4 15:30:11 | 只看该作者
你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。
活着的死人 该用户已被删除
19#
发表于 2015-5-6 08:09:26 | 只看该作者
应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展
分手快乐 该用户已被删除
20#
发表于 2015-6-16 20:56:20 | 只看该作者
是一种使网页(Web Page)产生生动活泼画面的语言
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-5-15 03:24

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表