国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

用連接池提高Servlet訪問數據庫的效率 (-)

2024-07-21 02:14:17
字體:
來源:轉載
供稿:網友
java servlet作為首選的服務器端數據處理技術,正在迅速取代cgi腳本。servlet超越cgi的優勢之一在于,不僅多個請求
可以共享公用資源,而且還可以在不同用戶請求之間保留持續數據。本文介紹一種充分發揮該特色的實用技術,即數據庫連
接池。


一、實現連接池的意義

動態web站點往往用數據庫存儲的信息生成web頁面,每一個頁面請求導致一次數據庫訪問。連接
數據庫不僅要開銷一定的通訊和內存資源,還必須完成用戶驗證、安全上下文配置這類任務,因而往往成為最為耗時的操
作。當然,實際的連接時間開銷千變萬化,但1到2秒延遲并非不常見。如果某個基于數據庫的web應用只需建立一次初始連
接,不同頁面請求能夠共享同一連接,就能獲得顯著的性能改善。
servlet是一個java類。servlet引擎(它可能是web服務軟件的一部分,也可能是一個獨立的附加模塊)在系統啟動或servlet
第一次被請求時將該類裝入java虛擬機并創建它的一個實例。不同用戶請求由同一servlet實例的多個獨立線程處理。那些要
求在不同請求之間持續有效的數據既可以用servlet的實例變量來保存,也可以保存在獨立的輔助對象中。
用jdbc訪問數據庫首先要創建與數據庫之間的連接,獲得一個連接對象(connection),由連接對象提供執行sql語句的方法。
本文介紹的數據庫連接池包括一個管理類dbconnectionmanager,負責提供與多個連接池對象(dbconnectionpool類)之間
的接口。每一個連接池對象管理一組jdbc連接對象,每一個連接對象可以被任意數量的servlet共享。
類dbconnectionpool提供以下功能:

1) 從連接池獲?。ɑ騽摻ǎ┛捎眠B接。
2) 把連接返回給連接池。
3) 在系統關閉時釋放所有資源,關閉所有連接。

此外, dbconnectionpool類還能夠處理無效連接(原來登記為可用的連接,由于某種原因不再可用,如超時,通訊問題)
,并能夠限制連接池中的連接總數不超過某個預定值。
管理類dbconnectionmanager用于管理多個連接池對象,它提供以下功能:

1) 裝載和注冊jdbc驅動程序。
2) 根據在屬性文件中定義的屬性創建連接池對象。
3) 實現連接池名字與其實例之間的映射。
4) 跟蹤客戶程序對連接池的引用,保證在最后一個客戶程序結束時安全地關閉所有連接池。

本文余下部分將詳細說明這兩個類,最后給出一個示例演示servlet使用連接池的一般過程。


二、具體實現

dbconnectionmanager.java程序清單如下:

001 import java.io.*;
002 import java.sql.*;
003 import java.util.*;
004 import java.util.date;
005
006 /**
007 * 管理類dbconnectionmanager支持對一個或多個由屬性文件定義的數據庫連接
008 * 池的訪問.客戶程序可以調用getinstance()方法訪問本類的唯一實例.
009 */
010 public class dbconnectionmanager {
011 static private dbconnectionmanager instance; // 唯一實例
012 static private int clients;
013
014 private vector drivers = new vector();
015 private printwriter log;
016 private hashtable pools = new hashtable();
017
018 /**
019 * 返回唯一實例.如果是第一次調用此方法,則創建實例
020 *
021 * @return dbconnectionmanager 唯一實例
022 */
023 static synchronized public dbconnectionmanager getinstance() {
024 if (instance == null) {
025 instance = new dbconnectionmanager();
026 }
027 clients++;
028 return instance;
029 }
030
031 /**
032 * 建構函數私有以防止其它對象創建本類實例
033 */
034 private dbconnectionmanager() {
035 init();
036 }
037
038 /**
039 * 將連接對象返回給由名字指定的連接池
040 *
041 * @param name 在屬性文件中定義的連接池名字
042 * @param con 連接對象
043 */
044 public void freeconnection(string name, connection con) {
045 dbconnectionpool pool = (dbconnectionpool) pools.get(name);
046 if (pool != null) {
047 pool.freeconnection(con);
048 }
049 }
050
051 /**
052 * 獲得一個可用的(空閑的)連接.如果沒有可用連接,且已有連接數小于最大連接數
053 * 限制,則創建并返回新連接
054 *
055 * @param name 在屬性文件中定義的連接池名字
056 * @return connection 可用連接或null
057 */
058 public connection getconnection(string name) {
059 dbconnectionpool pool = (dbconnectionpool) pools.get(name);
060 if (pool != null) {
061 return pool.getconnection();
062 }
063 return null;
064 }
065
066 /**
067 * 獲得一個可用連接.若沒有可用連接,且已有連接數小于最大連接數限制,
068 * 則創建并返回新連接.否則,在指定的時間內等待其它線程釋放連接.
069 *
070 * @param name 連接池名字
071 * @param time 以毫秒計的等待時間
072 * @return connection 可用連接或null
073 */
074 public connection getconnection(string name, long time) {
075 dbconnectionpool pool = (dbconnectionpool) pools.get(name);
076 if (pool != null) {
077 return pool.getconnection(time);
078 }
079 return null;
080 }
081
082 /**
083 * 關閉所有連接,撤銷驅動程序的注冊
084 */
085 public synchronized void release() {
086 // 等待直到最后一個客戶程序調用
087 if (--clients != 0) {
088 return;
089 }
090
091 enumeration allpools = pools.elements();
092 while (allpools.hasmoreelements()) {
093 dbconnectionpool pool = (dbconnectionpool) allpools.nextelement();
094 pool.release();
095 }
096 enumeration alldrivers = drivers.elements();
097 while (alldrivers.hasmoreelements()) {
098 driver driver = (driver) alldrivers.nextelement();
099 try {
100 drivermanager.deregisterdriver(driver);
101 log("撤銷jdbc驅動程序 " + driver.getclass().getname()+"的注冊");
102 }
103 catch (sqlexception e) {
104 log(e, "無法撤銷下列jdbc驅動程序的注冊: " + driver.getclass().getname());
105 }
106 }
107 }
108
109 /**
110 * 根據指定屬性創建連接池實例.
111 *
112 * @param props 連接池屬性
113 */
114 private void createpools(properties props) {
115 enumeration propnames = props.propertynames();
116 while (propnames.hasmoreelements()) {
117 string name = (string) propnames.nextelement();
118 if (name.endswith(".url")) {
119 string poolname = name.substring(0, name.lastindexof("."));
120 string url = props.getproperty(poolname + ".url");
121 if (url == null) {
122 log("沒有為連接池" + poolname + "指定url");
123 continue;
124 }
125 string user = props.getproperty(poolname + ".user");
126 string password = props.getproperty(poolname + ".password");
127 string maxconn = props.getproperty(poolname + ".maxconn", "0");
128 int max;
129 try {
130 max = integer.valueof(maxconn).intvalue();
131 }
132 catch (numberformatexception e) {
133 log("錯誤的最大連接數限制: " + maxconn + " .連接池: " + poolname);
134 max = 0;
135 }
136 dbconnectionpool pool =
137 new dbconnectionpool(poolname, url, user, password, max);
138 pools.put(poolname, pool);
139 log("成功創建連接池" + poolname);
140 }
141 }
142 }
143
144 /**
145 * 讀取屬性完成初始化
146 */
147 private void init() {
148 inputstream is = getclass().getresourceasstream("/db.properties");
149 properties dbprops = new properties();
150 try {
151 dbprops.load(is);
152 }
153 catch (exception e) {
154 system.err.println("不能讀取屬性文件. " +
155 "請確保db.properties在classpath指定的路徑中");
156 return;
157 }
158 string logfile = dbprops.getproperty("logfile", "dbconnectionmanager.log");
159 try {
160 log = new printwriter(new filewriter(logfile, true), true);
161 }
162 catch (ioexception e) {
163 system.err.println("無法打開日志文件: " + logfile);
164 log = new printwriter(system.err);
165 }
166 loaddrivers(dbprops);
167 createpools(dbprops);
168 }
169
170 /**
171 * 裝載和注冊所有jdbc驅動程序
172 *
173 * @param props 屬性
174 */
175 private void loaddrivers(properties props) {
176 string driverclasses = props.getproperty("drivers");
177 stringtokenizer st = new stringtokenizer(driverclasses);
178 while (st.hasmoreelements()) {
179 string driverclassname = st.nexttoken().trim();
180 try {
181 driver driver = (driver)
182 class.forname(driverclassname).newinstance();
183 drivermanager.registerdriver(driver);
184 drivers.addelement(driver);
185 log("成功注冊jdbc驅動程序" + driverclassname);
186 }
187 catch (exception e) {
188 log("無法注冊jdbc驅動程序: " +
189 driverclassname + ", 錯誤: " + e);
190 }
191 }
192 }
193
194 /**
195 * 將文本信息寫入日志文件
196 */
197 private void log(string msg) {
198 log.println(new date() + ": " + msg);
199 }
200
201 /**
202 * 將文本信息與異常寫入日志文件
203 */
204 private void log(throwable e, string msg) {
205 log.println(new date() + ": " + msg);
206 e.printstacktrace(log);
207 }
208
209 /**
210 * 此內部類定義了一個連接池.它能夠根據要求創建新連接,直到預定的最
211 * 大連接數為止.在返回連接給客戶程序之前,它能夠驗證連接的有效性.
212 */
213 class dbconnectionpool {
214 private int checkedout;
215 private vector freeconnections = new vector();
216 private int maxconn;
217 private string name;
218 private string password;
219 private string url;
220 private string user;
221
222 /**
223 * 創建新的連接池
224 *
225 * @param name 連接池名字
226 * @param url 數據庫的jdbc url
227 * @param user 數據庫帳號,或 null
228 * @param password 密碼,或 null
229 * @param maxconn 此連接池允許建立的最大連接數
230 */
231 public dbconnectionpool(string name, string url, string user, string password,
232 int maxconn) {
233 this.name = name;
234 this.url = url;
235 this.user = user;
236 this.password = password;
237 this.maxconn = maxconn;
238 }
239
240 /**
241 * 將不再使用的連接返回給連接池
242 *
243 * @param con 客戶程序釋放的連接
244 */
245 public synchronized void freeconnection(connection con) {
246 // 將指定連接加入到向量末尾
247 freeconnections.addelement(con);
248 checkedout--;
249 notifyall();
250 }
251
252 /**
253 * 從連接池獲得一個可用連接.如沒有空閑的連接且當前連接數小于最大連接
254 * 數限制,則創建新連接.如原來登記為可用的連接不再有效,則從向量刪除之,
255 * 然后遞歸調用自己以嘗試新的可用連接.
256 */
257 public synchronized connection getconnection() {
258 connection con = null;
259 if (freeconnections.size() > 0) {
260 // 獲取向量中第一個可用連接
261 con = (connection) freeconnections.firstelement();
262 freeconnections.removeelementat(0);
263 try {
264 if (con.isclosed()) {
265 log("從連接池" + name+"刪除一個無效連接");
266 // 遞歸調用自己,嘗試再次獲取可用連接
267 con = getconnection();
268 }
269 }
270 catch (sqlexception e) {
271 log("從連接池" + name+"刪除一個無效連接");
272 // 遞歸調用自己,嘗試再次獲取可用連接
273 con = getconnection();
274 }
275 }
276 else if (maxconn == 0 || checkedout < maxconn) {
277 con = newconnection();
278 }
279 if (con != null) {
280 checkedout++;
281 }
282 return con;
283 }
284
285 /**
286 * 從連接池獲取可用連接.可以指定客戶程序能夠等待的最長時間
287 * 參見前一個getconnection()方法.
288 *
289 * @param timeout 以毫秒計的等待時間限制
290 */
291 public synchronized connection getconnection(long timeout) {
292 long starttime = new date().gettime();
293 connection con;
294 while ((con = getconnection()) == null) {
295 try {
296 wait(timeout);
297 }
298 catch (interruptedexception e) {}
299 if ((new date().gettime() - starttime) >= timeout) {
300 // wait()返回的原因是超時
301 return null;
302 }
303 }
304 return con;
305 }
306
307 /**
308 * 關閉所有連接
309 */
310 public synchronized void release() {
311 enumeration allconnections = freeconnections.elements();
312 while (allconnections.hasmoreelements()) {
313 connection con = (connection) allconnections.nextelement();
314 try {
315 con.close();
316 log("關閉連接池" + name+"中的一個連接");
317 }
318 catch (sqlexception e) {
319 log(e, "無法關閉連接池" + name+"中的連接");
320 }
321 }
322 freeconnections.removeallelements();
323 }
324
325 /**
326 * 創建新的連接
327 */
328 private connection newconnection() {
329 connection con = null;
330 try {
331 if (user == null) {
332 con = drivermanager.getconnection(url);
333 }
334 else {
335 con = drivermanager.getconnection(url, user, password);
336 }
337 log("連接池" + name+"創建一個新的連接");
338 }
339 catch (sqlexception e) {
340 log(e, "無法創建下列url的連接: " + url);
341 return null;
342 }
343 return con;
344 }
345 }
346 }


菜鳥學堂:
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 晋州市| 合水县| 靖西县| 新宾| 齐齐哈尔市| 杭州市| 丁青县| 轮台县| 崇信县| 芒康县| 嘉禾县| 静海县| 凤山县| 云和县| 信宜市| 乐陵市| 高密市| 南陵县| 门头沟区| 黄龙县| 吉安市| 望江县| 攀枝花市| 临泉县| 宁都县| 驻马店市| 泾阳县| 杨浦区| 金沙县| 共和县| 永胜县| 金堂县| 射洪县| 永济市| 仪征市| 内江市| 广汉市| 博爱县| 乐业县| 闽清县| 忻城县|