Summarizes the proxy pattern and simulates implementing its own database connection pooling tool class based on the database connection pooling principle

Source: Internet
Author: User
Tags connection pooling

Proxy ModeRequirements: Extend (enhance) the functionality of a class already in the system

Requirements: In the case of non-modification of the source code, the existing functions are enhanced

Static proxy

Abstract interface: An object that guarantees an object with enhanced functionality and an existing function, providing the same method externally

Target object: Encapsulates the original functionality

Proxy object: Encapsulates enhancements and legacy functionality (implemented by holding a reference to a target object)

Problem: Code is not flexible enough to generate a lot of redundant work

Dynamic Agent

Implementation APIfor dynamic proxies:

Proxy:

Helper generates proxy objects that provide static methods for generating proxy classes and proxy objects

Invocationhandler:

The handle interface, which intercepts the method that all proxy objects call (the method that all proxy objects call, can be

Invocationhandler intercept to)

Simulating the implementation of database connection pooling

Operation of the database: consider performance issues

Frequent connection and disconnection of data, which itself consumes resources (performance of operational data)

--- pool management for database connection objects (resources are obtained from the pool, and resources are placed again after they are exhausted)

Specific implementations of connection pooling:

1 Create a collection object that encapsulates n Connection Objects

2 definition Get Connected

3 and return the function of the connection

Implementation code:

1  Public classDbpoolutils {2     Private StaticString driver;3     Private StaticString URL;4     Private StaticString username;5     Private StaticString password;6     Private Static intMaxconn;//maximum number of connections to thread pool7     8     //defines a collection that represents the thread pool9     StaticList<connection> list=NewArraylist<connection>();Ten     //initializes the class when it is loaded and creates a Connection object . One     Static{ AProperties properties=NewProperties (); -         Try { -             //Read configuration file information theProperties.load (dbpoolutils.class. getResourceAsStream ("Mysql.properties")); -Driver=properties.getproperty ("Driver"); -Url=properties.getproperty ("url"); -Username=properties.getproperty ("username"); +Password=properties.getproperty ("Password"); -Maxconn=integer.parseint (Properties.getproperty ("Maxconn")); + Class.forName (driver); A             /* at * Create a Connection object - * Because when the user closes the thread connection object to the thread pool, - * All objects and returned objects should be proxy objects.  - * intercept the Close () method to change the original disconnection to connect the thread connection object to the connection pool -              */             -              for(inti = 0; i < Maxconn; i++) { in                 FinalConnection conn=drivermanager.getconnection (URL, username, password); -                 //Create a proxy object toObject connproxy=Proxy.newproxyinstance ( +Dbpoolutils.class. getClassLoader (),//class loader for custom classes -                         NewClass<?>[]{connection.class},//an array of class files for the implemented interface the                         NewInvocationhandler () {//Anonymous inner class implementation Invocationhandler *                              $ @OverridePanax Notoginseng                              PublicObject Invoke ( -Object Proxy,//Proxy Object theMethod method,//proxy object implements the method called in the interface +Object[] Args//The proxy object implements the parameters in the method called in the interface A)throwsThrowable { the                                 //block the Close () method to change the original disconnection to return to the connection pool, that is: Add the current proxy object to the thread pool +String methodname=method.getname (); -                                 if("Close". Equals (MethodName)) { $ List.add ((Connection) proxy); $                                     //wake-on-waiting thread -                                     synchronized(list) { - List.notifyall (); the                                     } -                                 }Wuyi                                 //Release: Call the original object method theObject obj=Method.invoke (conn, args);  -                                 returnobj; Wu                             } -                         }); About                 //Add the created Agent thread object to the thread pool $ List.add ((Connection) connproxy); -             } -}Catch(IOException e) { - e.printstacktrace (); A}Catch(ClassNotFoundException e) { + e.printstacktrace (); the}Catch(SQLException e) { - e.printstacktrace (); $         }         the     } the     /** the * Provide a connection object externally the      * @return -      */ in      Public StaticConnection getconnection () { the         //when there is no connection object in the thread pool, let the thread wait instead of the exception, waiting for the other thread to return and then wake up the         synchronized(list) { About             if(List.size () ==0) { the                 Try { the list.wait (); the}Catch(interruptedexception e) { + e.printstacktrace (); -                 } the             }Bayi         }         the         //remove the first thread from the thread pool every time theConnection Conn=list.remove (0); -System.out.println ("Remaining:" +list.size ()); -         returnConn; the     } the}

Summarizes the proxy pattern and simulates implementing its own database connection pooling tool class based on the database connection pooling principle

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.