|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
诸如RMI,EJB等一些技术并不是你说的那么复杂,而是它们把一些复杂的工具封装成不复杂的工具了,理解这些工具是需要些时间。我问你,.net里有这些工具吗?要简单多少?。publicclassOracleConnectionManager{
privateDBConnectionManagerconnMgr;
privatefinalStringpoolName="Oracle";
privateConnectionconn;
publicOracleConnectionManager(){
StringuserID="system";
Stringpassword="manager";
StringJDBCDriver="oracle.jdbc.driver.OracleDriver";
StringJDBCDriverType="jdbc:oracle:thin";
StringDBHost="127.0.0.1";
StringPort="1521";
StringSID="sid";
Stringurl=JDBCDriverType+":@"+DBHost+":"+Port+":"+SID;
connMgr=DBConnectionManager.getInstance();
if(DBConnectionManager.clients==1){
connMgr.init(poolName,JDBCDriver,url,userID,password);
connMgr.init("egongOracle",JDBCDriver,JDBCDriverType+":@110.7.6.22:1521:egong","abcusername","abcpasswd");
}
}
publicConnectiongetConnection(){
return(conn=connMgr.getConnection(poolName));
}
publicConnectiongetConnection(StringnewOracle){
return(conn=connMgr.getConnection(newOracle));
}
publicvoidfreeConnection(){
connMgr.freeConnection(poolName,conn);
}
publicvoidfreeConnection(StringnewOracle){
connMgr.freeConnection(newOracle,conn);
}
}
publicclassDBConnectionManager{
staticprivateDBConnectionManagerinstance=null;//Thesingleinstance
staticpublicintclients=0;
privateVectordrivers=newVector();
privatePrintWriterlog;
privateHashtablepools=newHashtable();
privatefinalintMAX_CONN=1000;
/**
*Returnsthesingleinstance,creatingoneifitsthe
*firsttimethismethodiscalled.
*
*@returnDBConnectionManagerThesingleinstance.
*/
staticsynchronizedpublicDBConnectionManagergetInstance(){
if(instance==null){
instance=newDBConnectionManager();
}
clients++;
returninstance;
}
/**
*AprivateconstructorsincethisisaSingleton
*/
privateDBConnectionManager(){
//init();
}
/**
*Returnsaconnectiontothenamedpool.
*
*@paramnameThepoolnameasdefinedinthepropertiesfile
*@paramconTheConnection
*/
publicvoidfreeConnection(Stringname,Connectioncon){
DBConnectionPoolpool=(DBConnectionPool)pools.get(name);
if(pool!=null){
pool.freeConnection(con);
}
}
/**
*Returnsanopenconnection.Ifnooneisavailable,andthemax
*numberofconnectionshasnotbeenreached,anewconnectionis
*created.
*
*@paramnameThepoolnameasdefinedinthepropertiesfile
*@returnConnectionTheconnectionornull
*/
publicConnectiongetConnection(Stringname){
DBConnectionPoolpool=(DBConnectionPool)pools.get(name);
if(pool!=null){
returnpool.getConnection();
}
returnnull;
}
/**
*Returnsanopenconnection.Ifnooneisavailable,andthemax
*numberofconnectionshasnotbeenreached,anewconnectionis
*created.Ifthemaxnumberhasbeenreached,waitsuntilone
*isavailableorthespecifiedtimehaselapsed.
*
*@paramnameThepoolnameasdefinedinthepropertiesfile
*@paramtimeThenumberofmillisecondstowait
*@returnConnectionTheconnectionornull
*/
publicConnectiongetConnection(Stringname,longtime){
DBConnectionPoolpool=(DBConnectionPool)pools.get(name);
if(pool!=null){
returnpool.getConnection(time);
}
returnnull;
}
/**
*Closesallopenconnectionsandderegistersalldrivers.
*/
publicsynchronizedvoidrelease(){
//Waituntilcalledbythelastclient
if(--clients!=0){
return;
}
EnumerationallPools=pools.elements();
while(allPools.hasMoreElements()){
DBConnectionPoolpool=(DBConnectionPool)allPools.nextElement();
pool.release();
}
EnumerationallDrivers=drivers.elements();
while(allDrivers.hasMoreElements()){
Driverdriver=(Driver)allDrivers.nextElement();
try{
DriverManager.deregisterDriver(driver);
log("DeregisteredJDBCdriver"+driver.getClass().getName());
}
catch(SQLExceptione){
log(e,"CantderegisterJDBCdriver:"+driver.getClass().getName());
}
}
log.close();
}
/**
*CreatesinstancesofDBConnectionPoolbasedontheproperties.
*ADBConnectionPoolcanbedefinedwiththefollowingproperties:
*<PRE>
*<poolname>.urlTheJDBCURLforthedatabase
*<poolname>.userAdatabaseuser(optional)
*<poolname>.passwordAdatabaseuserpassword(ifuserspecified)
*<poolname>.maxconnThemaximalnumberofconnections(optional)
*</PRE>
*
*@parampropsTheconnectionpoolproperties
*/
privatevoidcreatePools(StringpoolName,Stringurl,Stringuser,Stringpassword,intmax){
/*
EnumerationpropNames=props.propertyNames();
while(propNames.hasMoreElements()){
Stringname=(String)propNames.nextElement();
if(name.endsWith(".url")){
StringpoolName=name.substring(0,name.lastIndexOf("."));
Stringurl=props.getProperty(poolName+".url");
if(url==null){
log("NoURLspecifiedfor"+poolName);
continue;
}
Stringuser=props.getProperty(poolName+".user");
Stringpassword=props.getProperty(poolName+".password");
Stringmaxconn=props.getProperty(poolName+".maxconn","0");
intmax;
try{
max=Integer.valueOf(maxconn).intValue();
}
catch(NumberFormatExceptione){
log("Invalidmaxconnvalue"+maxconn+"for"+poolName);
max=0;
}
DBConnectionPoolpool=
newDBConnectionPool(poolName,url,user,password,max);
pools.put(poolName,pool);
log("Initializedpool"+poolName);
}
}
*/
DBConnectionPoolpool=
newDBConnectionPool(poolName,url,user,password,max);
pools.put(poolName,pool);
log("Initializedpool"+poolName);
}
publicvoidinit(StringpoolName,Stringdriver,Stringurl,Stringuser,Stringpasswd){
init(poolName,driver,url,user,passwd,MAX_CONN);
}
/**
*Loadspropertiesandinitializestheinstancewithitsvalues.
*/
publicvoidinit(StringpoolName,Stringdriver,Stringurl,Stringuser,Stringpasswd,intmaxconn){
/*
InputStreamis=getClass().getResourceAsStream("/db.properties");
PropertiesdbProps=newProperties();
try{
dbProps.load(is);
}
catch(Exceptione){
System.err.println("Cantreadthepropertiesfile."+
"Makesuredb.propertiesisintheCLASSPATH");
return;
}
StringlogFile=dbProps.getProperty("logfile","DBConnectionManager.log");
StringlogFile="."+File.separator+"logs"+File.separator+"dbpool";
try{
log=newPrintWriter(newFileWriter(logFile,true),true);
}
catch(IOExceptione){
System.err.println("Cantopenthelogfile:"+logFile);
log=newPrintWriter(System.err);
}
*/
log=newPrintWriter(System.err);
loadDrivers(driver);
createPools(poolName,url,user,passwd,maxconn);
}
/**
*LoadsandregistersallJDBCdrivers.Thisisdonebythe
*DBConnectionManager,asopposedtotheDBConnectionPool,
*sincemanypoolsmaysharethesamedriver.
*
*@parampropsTheconnectionpoolproperties
*/
privatevoidloadDrivers(StringdriverClassName){
/*
StringdriverClasses=props.getProperty("drivers");
StringTokenizerst=newStringTokenizer(driverClasses);
while(st.hasMoreElements()){
StringdriverClassName=st.nextToken().trim();
try{
Driverdriver=(Driver)
Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
drivers.addElement(driver);
log("RegisteredJDBCdriver"+driverClassName);
}
catch(Exceptione){
log("CantregisterJDBCdriver:"+
driverClassName+",Exception:"+e);
}
}
*/
try{
Driverdriver=(Driver)
Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
drivers.addElement(driver);
log("RegisteredJDBCdriver"+driverClassName);
}
catch(Exceptione){
log("CantregisterJDBCdriver:"+
driverClassName+",Exception:"+e);
}
}
/**
*Writesamessagetothelogfile.
*/
privatevoidlog(Stringmsg){
log.println(newDate()+":"+msg);
}
/**
*WritesamessagewithanExceptiontothelogfile.
*/
privatevoidlog(Throwablee,Stringmsg){
log.println(newDate()+":"+msg);
e.printStackTrace(log);
}
/**
*Thisinnerclassrepresentsaconnectionpool.Itcreatesnew
*connectionsondemand,uptoamaxnumberifspecified.
*Italsomakessureaconnectionisstillopenbeforeitis
*returnedtoaclient.
*/
classDBConnectionPool{
privateintcheckedOut;
privateVectorfreeConnections=newVector();
privateintmaxConn;
privateStringname;
privateStringpassword;
privateStringURL;
privateStringuser;
/**
*Createsnewconnectionpool.
*
*@paramnameThepoolname
*@paramURLTheJDBCURLforthedatabase
*@paramuserThedatabaseuser,ornull
*@parampasswordThedatabaseuserpassword,ornull
*@parammaxConnThemaximalnumberofconnections,or0
*fornolimit
*/
publicDBConnectionPool(Stringname,StringURL,Stringuser,Stringpassword,
intmaxConn){
this.name=name;
this.URL=URL;
this.user=user;
this.password=password;
this.maxConn=maxConn;
}
/**
*Checksinaconnectiontothepool.NotifyotherThreadsthat
*maybewaitingforaconnection.
*
*@paramconTheconnectiontocheckin
*/
publicsynchronizedvoidfreeConnection(Connectioncon){
//PuttheconnectionattheendoftheVector
freeConnections.addElement(con);
checkedOut--;
notifyAll();
}
/**
*Checksoutaconnectionfromthepool.Ifnofreeconnection
*isavailable,anewconnectioniscreatedunlessthemax
*numberofconnectionshasbeenreached.Ifafreeconnection
*hasbeenclosedbythedatabase,itsremovedfromthepool
*andthismethodiscalledagainrecursively.
*/
publicsynchronizedConnectiongetConnection(){
Connectioncon=null;
if(freeConnections.size()>0){
//PickthefirstConnectionintheVector
//togetround-robinusage
con=(Connection)freeConnections.firstElement();
freeConnections.removeElementAt(0);
try{
if(con.isClosed()){
log("Removedbadconnectionfrom"+name);
//Tryagainrecursively
con=getConnection();
}
}
catch(SQLExceptione){
log("Removedbadconnectionfrom"+name);
//Tryagainrecursively
con=getConnection();
}
}
elseif(maxConn==0||checkedOut<maxConn){
con=newConnection();
}
if(con!=null){
checkedOut++;
}
returncon;
}
/**
*Checksoutaconnectionfromthepool.Ifnofreeconnection
*isavailable,anewconnectioniscreatedunlessthemax
*numberofconnectionshasbeenreached.Ifafreeconnection
*hasbeenclosedbythedatabase,itsremovedfromthepool
*andthismethodiscalledagainrecursively.
*<P>
*Ifnoconnectionisavailableandthemaxnumberhasbeen
*reached,thismethodwaitsthespecifiedtimeforonetobe
*checkedin.
*
*@paramtimeoutThetimeoutvalueinmilliseconds
*/
publicsynchronizedConnectiongetConnection(longtimeout){
longstartTime=newDate().getTime();
Connectioncon;
while((con=getConnection())==null){
try{
wait(timeout);
}
catch(InterruptedExceptione){}
if((newDate().getTime()-startTime)>=timeout){
//Timeouthasexpired
returnnull;
}
}
returncon;
}
/**
*Closesallavailableconnections.
*/
publicsynchronizedvoidrelease(){
EnumerationallConnections=freeConnections.elements();
while(allConnections.hasMoreElements()){
Connectioncon=(Connection)allConnections.nextElement();
try{
con.close();
log("Closedconnectionforpool"+name);
}
catch(SQLExceptione){
log(e,"Cantcloseconnectionforpool"+name);
}
}
freeConnections.removeAllElements();
}
/**
*Createsanewconnection,usingauseridandpassword
*ifspecified.
*/
privateConnectionnewConnection(){
Connectioncon=null;
try{
if(user==null){
con=DriverManager.getConnection(URL);
}
else{
con=DriverManager.getConnection(URL,user,password);
}
log("Createdanewconnectioninpool"+name);
}
catch(SQLExceptione){
log(e,"Cantcreateanewconnectionfor"+URL);
returnnull;
}
returncon;
}
}
}
你通过从书的数量和开发周期及运行速度来证明:net和ruby要比java简单。 |
|