Tag:runtime remove override Dynamic proxy pool source Technology reflect result
jdbcdemo.java:package com.itheima.jdbc;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.sqlexception;import Com.itheima.pool.MyPool; public class Jdbcdemo {public static void main (string[] args) {Connection conn = null; PreparedStatement PS = null; ResultSet rs = null; Mypool pool = new Mypool (), try {conn = pool.getconnection ();p s = conn.preparestatement ("SELECT * from Account"); rs = Ps.ex Ecutequery (); while (Rs.next ()) {String name = rs.getstring (2); String salary = rs.getstring (3); SYSTEM.OUT.PRINTLN (name + ":" + Salary);}} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);} finally {//Close database connection if (rs! = null) {try {rs.close ( );} catch (SQLException e) {rs = null;}} if (PS! = null) {try {ps.close ();} catch (SQLException e) {PS = null;}} /*if (rs! = null) {try {rs.close ();} catch (SQLException e) {rs = null;}} *///You cannot close the database connection object connection, you should return it to the database connection pool POOL.RETURNCONN (conn);}}
Mypool.java:
Package Com.itheima.pool;import Java.io.printwriter;import Java.sql.connection;import Java.sql.DriverManager; Import Java.sql.sqlexception;import Java.sql.sqlfeaturenotsupportedexception;import Java.util.LinkedList;import Java.util.list;import Java.util.logging.logger;import Javax.sql.datasource;public class MyPool implements DataSource {//list collection saves Connection objects in the database connection pool private static list<connection> pool = new linkedlist<connection> ();// Static code block. Used to initialize the list collection. That is, initialize the database connection pool, create 5 connection objects to save in case of using static {try {Class.forName ("Com.mysql.jdbc.Driver"); for (int i = 0; i < 5; i++) { Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "root");p Ool.add (conn);}} catch (ClassNotFoundException e) {e.printstacktrace (); throw new RuntimeException (e);} catch (SQLException e) { E.printstacktrace (); throw new RuntimeException (e);}} @Overridepublic PrintWriter Getlogwriter () throws SQLException {return null;} @Overridepublic void Setlogwriter (PrintWriter out) throwsSQLException {} @Overridepublic void setlogintimeout (int seconds) throws SQLException {} @Overridepublic int Getlogintimeout () throws SQLException {return 0;} @Overridepublic Logger Getparentlogger () throws sqlfeaturenotsupportedexception {return null;} @Overridepublic <T> T Unwrap (class<t> iface) throws SQLException {//TODO auto-generated method Stubreturn nul l;} @Overridepublic boolean iswrapperfor (class<?> iface) throws SQLException {//TODO auto-generated method Stubreturn false;} Overrides the Getconnection () method of the parent class to return a connection object in the database connection pool. Assume that the connection object in the database connection pool is already in use. That is, both are removed and not returned, the creation of 3 Connection objects to save for later use @overridepublic Connection getconnection () throws SQLException {if (pool = = null) { for (int i = 0; i < 3; i++) {Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "Root");p Ool.add (conn);}} Return Pool.remove (0);} Create a new method. Used to return the database connection object connection. Since the DAO layer should not be destroyed after it has run out of database connections, it should be returned to the database connection pool public void Returnconn (Connection conn) {POOL.ADD (conn);} @OverRidepublic Connection getconnection (string Username, string password) throws SQLException {//TODO auto-generated method s Tubreturn null;}}
The above code is a simple use of database connection pooling, but one problem is that when you use database connection pooling technology, you need to change the code in the finally code block in the Jdbcdemo.java file, that is, the Conn object should not pass through the Conn.close in the finally block. Method is closed, but should be returned to the database connection pool.
Here we take the "dynamic Agent" way to solve the problem, that is, the finally code block still calls Conn.close ();
At this point the code changes for the above two Java files are as follows:
package com.itheima.jdbc;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.sqlexception;import Com.itheima.pool.MyPool; public class Jdbcdemo {public static void main (string[] args) {Connection conn = null; PreparedStatement PS = null; ResultSet rs = null; Mypool pool = new Mypool (), try {conn = pool.getconnection ();p s = conn.preparestatement ("SELECT * from Account"); rs = Ps.ex Ecutequery (); while (Rs.next ()) {String name = rs.getstring (2); String salary = rs.getstring (3); SYSTEM.OUT.PRINTLN (name + ":" + Salary);}} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);} finally {//Close database connection if (rs! = null) {try {rs.close ( );} catch (SQLException e) {rs = null;}} if (PS! = null) {try {ps.close ();} catch (SQLException e) {PS = null;}} IF (conn! = null) {try {conn.close ();} catch (SQLException e) {conn = null;}}}}
Package Com.itheima.pool;import Java.io.printwriter;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy;import Java.sql.connection;import Java.sql.DriverManager; Import Java.sql.sqlexception;import Java.sql.sqlfeaturenotsupportedexception;import Java.util.LinkedList;import Java.util.list;import Java.util.logging.logger;import Javax.sql.datasource;public class MyPool implements DataSource {//list collection saves Connection objects in the database connection pool private static list<connection> pool = new linkedlist<connection> ();// A static block of code that initializes the list collection, which initializes the database connection pool, creates 5 connection objects to save for use with static {try {Class.forName ("Com.mysql.jdbc.Driver"); for (int i = 0; I < 5; i++) {Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "root");p Ool.add ( conn);}} catch (ClassNotFoundException e) {e.printstacktrace (); throw new RuntimeException (e);} catch (SQLException e) { E.printstacktrace (); throw new RuntimeException (e);}} @Overridepublic PrintWriter GEtlogwriter () throws SQLException {return null;} @Overridepublic void Setlogwriter (PrintWriter out) throws SQLException {} @Overridepublic void setlogintimeout (int seconds) throws SQLException {} @Overridepublic int getlogintimeout () throws SQLException {return 0;} @Overridepublic Logger Getparentlogger () throws sqlfeaturenotsupportedexception {return null;} @Overridepublic <T> T Unwrap (class<t> iface) throws SQLException {//TODO auto-generated method Stubreturn nul l;} @Overridepublic boolean iswrapperfor (class<?> iface) throws SQLException {//TODO auto-generated method Stubreturn false;} Overrides the Getconnection () method of the parent class. Returns a Connection object in the database connection pool, assuming that the connection object in the database connection pool is already in use. That is, both are removed and not returned, the creation of 3 Connection objects to save for later use @overridepublic Connection getconnection () throws SQLException {if (pool = = null) { for (int i = 0; i < 3; i++) {Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day11", "root", "Root");p Ool.add (conn);}} Final Connection conn = pool.remove (0);//Use dynamic Proxy to changeBuild Close method//newproxyinstance (class loader, all interfaces implemented by Conn object to be modified, anonymous inner class) Connection proxy = (Connection) proxy.newproxyinstance ( Conn.getclass (). getClassLoader (), Conn.getclass (). Getinterfaces (), new Invocationhandler () {@Overridepublic Object Invoke (Object Proxy, method, object[] args) throws Throwable {if ("Close". Equals (Method.getname ())) {//is assumed to be the Close method. We do rewrite returnconn (conn); return null;} else {//Assuming other methods, call return Method.invoke (conn, args) directly;}}); System.out.println ("Get a Connection object, remaining Connection object:" + pool.size ()); return proxy; Creates a new method that returns the database connection object Connection, since the DAO layer should not be destroyed after the database connection is exhausted, but should be returned to the database connection pool public void Returnconn (Connection conn) { POOL.ADD (conn); System.out.println ("Return a Connection object, remaining Connection object:" + pool.size ());} @Overridepublic Connection getconnection (string Username, string password) throws SQLException {//TODO auto-generated Method Stubreturn null;}}
Execution Result:
Get a Connection object, remaining Connection object: 4a:1000.0b:1000.0c:1000.0 Returns a Connection object, remaining connection object: 5
Java Database Connection pooling technology is simple to use