I. The role of dynamic agents
Using dynamic proxies, you can intercept the execution of a method of an object and execute a custom method that is essentially reflective
Pros: Flexible
Cons: Because it's essentially reflective, the execution speed is relatively slow
Second, database connection pool design idea
1. Why use a database connection pool: The process of creating connection objects is time-consuming and should be managed to ensure that connection can be reused, connection.
2. Design Requirements:
(1) The connection pool is capable of maintaining multiple connections, and it is necessary to ensure that each thread acquires a different connection object.
(2) Provide a method to reclaim the connection.
3. The most basic implementation
PackageDay15_2;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.SQLException;Importjava.util.ArrayList;/*** Create a database connection pool using the most basic method *@authorKdyzm **/ Public classJDBCPool1 {Private StaticArraylist<connection>pool=NewArraylist<connection>(); Static { Try{class.forname ("Com.mysql.jdbc.Driver"); String URL= "Jdbc:mysq://localhost:3306?useunicode=true&characterencoding=utf-8"; for(inti=0;i<5;i++) {Connection conn=drivermanager.getconnection (URL, "root", "5a6f38"); POOL.ADD (conn); } } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); } } PublicConnection Getconn () {synchronized(Pool) {Connection conn=pool.remove (0); System.out.println ("also" +pool.size () + "connections"); returnConn; } } Public Static voidBack (Connection conn) {System.out.println ("Also connected:" +conn); POOL.ADD (conn); }}
4. The programmer writes code always calls the Close method habitually, if the Close method is actually called, then the connection will be freed and no longer recycled, so you should use a method to intercept the execution of the Close method and replace it with a custom action. This task can be accomplished using a proxy.
code example:
ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;ImportJava.net.URL;ImportJava.net.URLDecoder;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.util.LinkedList;Importjava.util.Properties; Public classConnutils {Private StaticLinkedlist<connection> pool =NewLinkedlist<connection>(); Static{ Try { //declaring the resource class-Properties prop =NewProperties (); //get the path to this fileURL url = connutils.class. getClassLoader (). GetResource ("Jdbc.properties"); String Path=Url.getpath (); //to prevent a Chinese or a blank spacePath = Urldecoder.decode (path, "UTf-8"); File File=NewFile (path); //load jdbc.properties This fileProp.load (Newfileinputstream (file)); //Get informationString Driver = prop.getproperty ("Driver"); Class.forName (driver); String Jdbcurl= Prop.getproperty ("url"); String nm= Prop.getproperty ("name"); String pwd= Prop.getproperty ("pwd"); //create three native connections and proxy themString poolsize = Prop.getproperty ("Poolsize"); intSize =Integer.parseint (poolsize); for(inti=0;i<size;i++){ FinalConnection con =drivermanager.getconnection (JDBCURL,NM,PWD); //dynamic proxy for conObject proxyedobj =proxy.newproxyinstance (connutils.class. getClassLoader (),NewClass[]{connection.class}, NewInvocationhandler () { Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//is the Close method if(Method.getname (). Equals ("Close")){ synchronized(Pool) {Pool.addlast ((Connection) proxy); Pool.notify (); } return NULL;//If Close is called, the method of the proxy class is not called. } returnMethod.invoke (con, args); } }); //put the proxy object in the poolPool.add ((Connection) proxyedobj); } } Catch(Exception e) {e.printstacktrace (); } } Public StaticConnection Getconn () {synchronized(pool) {if(Pool.size () ==0{//If there is no connection in the connection pool, wait in the waiting poolTry{pool.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } returnGetconn (); }Else{//If there is a connection in the connection pool, the connection is assigned. Connection Con=Pool.removefirst (); System.err.println ("A few more:" +pool.size ()); returncon; } } }}
5. The core class of the dynamic agent.
(1) proxy class: Provides a dynamic method for creating dynamic proxy classes and instances, or a superclass of all dynamic proxy classes created by these methods.
(2) Invocationhandler interface: The interface that is implemented by the calling handler of the proxy instance.
6. Tasks of the Agent
(1) Create a subclass of an interface in memory.
(2) Intercept all methods executed on the agent.
Third, contact management small exercise.
Source code: HTTPS://GITHUB.COM/KDYZM/DAY15
Java EE Learning Day 15th, "Customizing the use of dynamic proxies for database connection pooling"