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

發表于:2007-07-14來源:作者:點擊數: 標簽:
用連接池提高Servlet訪問 數據庫 的效率(2) 101 log("撤銷JDBC驅動程序 " + driver.getClass().getName()+"的注冊"); 102 } 103 catch ( SQL Exception e) { 104 log(e, "無法撤銷下列JDBC驅動程序的注冊: " + driver.getClass().getName()); 105 } 106 }
用連接池提高Servlet訪問數據庫的效率(2)

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 }

(未完待續)

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97