Database connection pool, dynamic agent __ Database

Source: Internet
Author: User
Tags connection pooling throwable

in the Web project, Java Access database is a multi-user operation, the need to connect the database frequently, one method is to a request to an operating object, this method of thinking simple, but there are huge hidden dangers, if the traffic is particularly large, database connection objects too much, may lead to crash. A good way to do this is to use a database connection for unified management, including a limited number of database connection objects and reuse after use.

when it comes to management, according to the programmer's habit, get connected object to finish the operation, usually close the connection object, this will create a problem, the next time another user gets the collection after the closed object, because the object has been closed, and then other operations, will produce an exception. So we're going to modify the function of the close () function.

train of thought: To modify function function, basically is to use cover method, a way is to use decoration mode, that is, inheritance plus combination, but this way has a disadvantage, if the interface to implement has a lot of functions, the code is very large, so generally not used. Another way is to use proxy mode. I want to describe in detail below

The agent uses a key API class, proxy, in addition to an instance object of an interface and interface.
Proxy.newproxyinstance (loader, interfaces, h);
First parameter: Class loader in the same space as the proxy object
Second parameter: To implement an array of interfaces
Third parameter: A handle object that implements the function

Here is an example of a renter renting through an intermediary to demonstrate:

Interface

Public interface Irenter {public
    abstract void rent (int n);
}

Interface Implementation Class

public class Renter implements irenter{

    @Override the public
    void rent (int n) {
        System.out.println ("Give you the +n+ room, Please pay 500 Yuan ");
    }

Key classes

public class Client {
    private static irenter rent = new renter ();
    public static void Main (string[] args) {

         Object obj =proxy.newproxyinstance (
                    Client.class.getClassLoader (),//
                    New Class[]{irenter.class}, 
                new Invocationhandler () {

                        @Override public
                        object Invoke (object Proxy, method method, object[] args
                                throws Throwable {
                            System.out.println ("I proxy ...");
                            return Method.invoke (rent, args);
                        }
                    });

         Irenter o = (irenter) obj;
         O.rent (3);
    }
}

According to the principle. Do a proxy tool class:

public class Proxyutil implements invocationhandler{
    private Object srcobj;

    Public Proxyutil (Object srcobj) {
        super ();
        This.srcobj = srcobj;
    }

    public static object GetProxy (object srcobj) {
        Object obj = Proxy.newproxyinstance (
                ProxyUtil.class.getClassLoader (), 
                Srcobj.getclass (), Getinterfaces (),
                new Proxyutil (srcobj)
                );
        return obj;
    }

    @Override Public
    object Invoke (Object proxy, Method method, object[] args)
            throws Throwable {

        return Method.invoke (srcobj, args);
    }

code implementation for database connection pooling:

public class Connsutil {private static List<connection>pool = new Arraylist<connection> ();
    private static int num = 3;
        static{Properties P = new properties ();
            try {p.load (ConnsUtil.class.getClassLoader (). getResourceAsStream ("jdbc.properties"));
            String Driver = p.getproperty ("Driver");
            String url = p.getproperty ("url");
            String user = P.getproperty ("username");
            String Password = p.getproperty ("password");
            Class.forName (driver);
                for (int i=0;i<num;i++) {final Connection conn = drivermanager.getconnection (URL, user, password);  
                        Connection con = (Connection) proxy.newproxyinstance (ConnsUtil.class.getClassLoader (),

                            New Class[]{connection.class}, new Invocationhandler () { @Override public Object Invoke (objecT proxy, method method, object[] args throws Throwable {
                                    if (Method.getname (). Equalsignorecase ("close")) {Pool.add ((Connection) proxy);
                                return null;
                            Return Method.invoke (conn, args);
                }
                        }
                    );
            Pool.add (con);
        } catch (Exception e) {e.printstacktrace ();
                } public static synchronized Connection getconnection () {if (Pool.size () <=0) {try {
                Thread.Sleep (100);
            return getconnection ();
            catch (Interruptedexception e) {e.printstacktrace ();
    } return Pool.remove (0);
 }
}

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.