[Java EE] database connection pool and dynamic proxy

Source: Internet
Author: User
Tags stub

Implementing the Javax.sql.DataSource interface

Implementing the Connection getconnection () method

Defines a static member property LinkedList type as a connection pool, initializes 5 database connections in a static code block, adds to the connection pool, and getconnection method, remove a connection from the connection pool when you get the connection.

ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;Importjava.sql.Connection;ImportJava.sql.ResultSet;Importjava.sql.Statement; Public classJdbctest { Public Static voidMain (string[] args)throwsException {//How to use reflectionClass.forName ("Com.mysql.jdbc.Driver"); //to get the database connection, when the guide packet, attention to guide java.sql, interface-oriented programmingMypool pool=NewMypool (); Connection Conn=pool.getconnection (); //get The transmitter objectStatement statement=conn.createstatement (); //get result Set objectResultSet resultset=statement.executequery ("SELECT * from User"); //Traverse         while(Resultset.next ()) {String username=resultset.getstring ("username");        SYSTEM.OUT.PRINTLN (username); }        //Close ResourceResultset.close ();        Statement.close ();            POOL.RESETCONN (conn); }}

My connection Pool

ImportJava.io.PrintWriter;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.SQLException;Importjava.sql.SQLFeatureNotSupportedException;Importjava.util.LinkedList;Importjava.util.List;ImportJava.util.logging.Logger;ImportJavax.sql.DataSource;/*** Handwritten connection pool * *@authorTaoshihan **/ Public classMypoolImplementsDataSource {//Connection Pool     Public StaticList<connection> pool =NewLinkedlist<connection>(); //Initialize    Static {        Try{class.forname ("Com.mysql.jdbc.Driver");  for(inti = 0; I < 5; i++) {Connection conn=Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/java", "root", "root");            POOL.ADD (conn); }        } Catch(Exception e) {}}/*** Get Connections*/@Override PublicConnection getconnection ()throwsSQLException {//If there is no connection in the pool        if(pool.size () = = 0) {             for(inti = 0; I < 5; i++) {Connection conn=Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/java", "root", "root");            POOL.ADD (conn); }        }        //Advanced First OutConnection Conn=pool.remove (0); System.out.println ("Get a connection, the pool is still remaining" +pool.size ()); returnConn; }    /*** Reset Connection*/     Public voidResetconn (Connection conn) {Try {            if(conn!=NULL&&!conn.isclosed ())                {POOL.ADD (conn); System.out.println ("Also back a connection, the pool is still remaining" +pool.size ()); }        } Catch(Exception e) {e.printstacktrace (); }} @Override PublicConnection getconnection (string Username, string password)throwsSQLException {return NULL; } @Override PublicPrintWriter Getlogwriter ()throwsSQLException {//TODO auto-generated Method Stub        return NULL; } @Override Public voidSetlogwriter (PrintWriter out)throwsSQLException {//TODO auto-generated Method Stub} @Override Public voidsetLoginTimeout (intSecondsthrowsSQLException {//TODO auto-generated Method Stub} @Override Public intGetlogintimeout ()throwsSQLException {//TODO auto-generated Method Stub        return0; } @Override PublicLogger Getparentlogger ()throwssqlfeaturenotsupportedexception {//TODO auto-generated Method Stub        return NULL; } @Override Public<T> T Unwrap (class<t> iface)throwsSQLException {//TODO auto-generated Method Stub        return NULL; } @Override Public BooleanIswrapperfor (class<?> iface)throwsSQLException {//TODO auto-generated Method Stub        return false; }}

Using inheritance, decoration, dynamic agents to transform methods in a class

The disadvantage of inheritance: At this point we have got the Connection object, so we cannot transform this object through inheritance

The test implementation of the decoration:

ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;Importjava.sql.Connection;ImportJava.sql.ResultSet;Importjava.sql.Statement; Public classJdbctest { Public Static voidMain (string[] args)throwsException {//Test Decorating ModeAnimal dog=NewBigDog (NewDog ());        Dog.eat ();    Dog.sound (); }}/*** Decoration Mode test *@authorTaoshihan **/Interfaceanimal{ Public voideat ();  Public voidSound ();}classDogImplementsanimal{@Override Public voideat () {System.out.println (Eat); } @Override Public voidSound () {System.out.println (Wang); }}//at this point I want to modify the sound method in the dog classclassBigDogImplementsanimal{PrivateDog Dog;  PublicBigDog (dog dog) { This. dog=Dog; }    /*** This method to tune the original*/@Override Public voideat () {dog.eat (); }    /*** This method is decorated*/@Override Public voidSound () {System.out.println (Shout); }    }

Dynamic Agent:

                //Test agent Mode        FinalDog dog=NewDog (); Animal Proxy= (Animal) proxy.newproxyinstance (Dog.class. getClassLoader (), Dog.class. Getinterfaces (),NewInvocationhandler () {@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {if("Sound". Equals (Method.getname ())) {System.out.println (Shout); return NULL; }Else{                    returnMethod.invoke (dog, args);        }            }        });        Proxy.eat (); Proxy.sound ();

[Java EE] database connection pool and dynamic proxy

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.