Javaweb07-html Notes (iii)

Source: Internet
Author: User
Tags connection pooling html notes

1.1 Case Two: tool classes for using connection pooling to transform JDBC: 1.1.1 Requirements:
Traditional JDBC operations are not particularly good at destroying connected objects. It takes time to create and destroy connections every time. A program that can use connection pooling optimization.

    • At the beginning of the program, you can create several connections to put the connection into the connection pool. When users use a connection, they can get it from the connection pool. After you run out of time, you can return the connection to the connection pool.
      1.1.2 Analysis: 1.1.2.1 Technical Analysis:
      "Custom connection Pooling" (learn)
    • Sun provides an interface to a pool of connections. (Javax.sql.DataSource).
    • Define a connection pool: implement this interface.
    • Use the list collection to hold multiple connected objects.
      "Code for custom Connection pool"
public class MyDataSource implements DataSource{// 创建一个List集合用于存放多个连接对象.private List<Connection> list = new ArrayList<Connection>();// 在程序开始的时候,初始化几个连接,将连接存放到list中.public MyDataSource() {// 初始化3个连接:for(int i=1;i<=3;i++){Connection conn = JDBCUtils.getConnection();list.add(conn);}}@Override// 获得连接的方法:public Connection getConnection() throws SQLException {if(list.size() <= 0){for(int i=1;i<=3;i++){Connection conn = JDBCUtils.getConnection();list.add(conn);}}Connection conn = list.remove(0);return conn;}// 归还连接的方法:public void addBack(Connection conn){list.add(conn);}...}

"Custom connection pool issues and how to resolve"
? Problem?
1. If you are using a custom connection pool, you will need to remember the APIs in the custom connection pool extra.
2. Can I use an interface-oriented programming method?
? Solve:
Do not provide additional API methods, you can solve the above two problems!!!
Can you also call the Close method of connection. Can enhance the connection Close method, the original destruction into return!!!
? How to enhance the Close method of connection:

    • There are several ways to enhance a method in a Java class???
      • One way: the way inheritance is. Inheritance can only be used when
        • can control the construction of this class.
      • Two ways: Decorator mode. Both the
        • wrapper object and the wrapped object implement the same interface.
        • The
        • wrapper object needs to get a reference to the wrapped object.
          * * * * * Disadvantages: If the interface method is more, enhance one of the methods. Other functions of the method require the original call.
      • Three ways: Dynamic proxy mode.
        • an Enhanced object implementation interface is available.
          Cases of inheritance and decorators
/** * 继承的方式增强一个类中某个方法: */class Man{public void run(){System.out.println("跑....");}}class SuperMan extends Man{public void run(){// super.run();System.out.println("飞....");}}/** * 使用装饰者的方式完成类的方法的增强 */interface Waiter{public void server();}class Waiteress implements Waiter{@Overridepublic void server() {System.out.println("服务...");}}class WaiteressWrapper implements Waiter{    private Waiter waiter;public WaiteressWrapper(Waiter waiter) {        this.waiter = waiter;}@Overridepublic void server() {System.out.println("微笑...");// this.waiter.server();}}【使用装饰者模式增强Connection的close方法】public class MyConnection implements Connection{private Connection conn;

Private list<connection> List;

Public myconnection (Connection conn,list<connection> List) {
This.conn = conn;
This.list = list;
}

@Override
public void Close () throws SQLException {
LIST.ADD (conn);
}
...
}

Getconnection method for connection pooling:br/> @Override

Public Connection getconnection () throws SQLException {
if (list.size () <= 0) {
for (int i=1;i<=3;i++) {
Connection conn = Jdbcutils.getconnection ();
LIST.ADD (conn);
}
}
Connection conn = list.remove (0);
MyConnection myconn = new MyConnection (conn, list);
return myconn;
}
"Common open Source database connection pool":
? DBCP:
DBCP (database connection pool), DB connection pool. is a Java Connection pool project on Apache and a connection pool component used by Tomcat. Use of DBCP alone requires 2 packages: Commons-dbcp.jar, Commons-pool.jar because establishing a database connection is a very time-consuming and resource-intensive behavior, the connection pool is pre-established with the database to make some connections, put in memory, the application needs to establish a database connection directly to the connection pool to apply for a line, run out and then put back.
? C3P0:
C3P0 is an open source JDBC connection pool that implements the data source and Jndi bindings, and supports the standard extensions of the JDBC3 specification and JDBC2. The open source projects that currently use it are hibernate,spring and so on.
? Tomcat built-in connection pool:
"Use of the DBCP connection pool"
First step: Introduce the jar package of the DBCP connection pool.
Step two: Write the DBCP code:

    • To set parameters manually:
    • Configuration file Setup parameters:
      "Use of the DBCP connection pool"
@Test/** * Manual mode: */public void Demo1 () {Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Basicdatasource DataSource = new Basicdatasource ();d atasource.setdriverclassname ("Com.mysql.jdbc.Driver"); Datasource.seturl ("jdbc:mysql:///web_07");d atasource.setusername ("root");d Atasource.setpassword ("123"); try{// Get CONNECTED: conn = Datasource.getconnection ();//write Sql:string sql = "SELECT * from category";//precompiled sql:stmt = Conn.preparestateme NT (SQL);//Execute Sql:rs = Stmt.executequery (); while (Rs.next ()) {System.out.println (Rs.getint ("CID") + "+rs.getstring (" CNAME "));}} catch (Exception e) {e.printstacktrace ();} Finally{jdbcutils.release (RS,STMT, conn);}} @Test/** * configuration file: */public void Demo2 () {Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Properties Properties = new properties (); Try{properties.load (New FileInputStream ("Src/dbcpconfig.properties"));D Atasource DataSource = Basicdatasourcefactory.createdatasource (properties);//Get connection: conn = Datasource.getconnection ();//write Sql:string sql = "SELECT * from category",//pre-compile sql:stmt = conn.preparestatement (sql);//Execute SQL:RS = Stmt.executeque Ry (); while (Rs.next ()) {System.out.println (Rs.getint ("CID") + "" +rs.getstring ("CNAME");}} catch (Exception e) {e.printstacktrace ();} Finally{jdbcutils.release (RS,STMT, conn);}}

Javaweb07-html Notes (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.