Javaweb Backend < 10 > Data pool c3p0 DPCB JNDI

Source: Internet
Author: User

First, database connection Pooling principle: (understanding)
The principle of simulating database connection pooling public class Connectionpooldemo {private static list<connection> pool = new arraylist<connection& gt; (); static{try {for (int i=0;i<10;i++) {Connection conn = jdbcutil.getconnection ();//New connection created POOL.ADD (conn);}} catch (Exception e) {e.printstacktrace ();}} Remove a link from the pool public synchronized static Connection getconnection () {if (Pool.size () >0) {Connection conn = pool.remove (0 ); return conn;} Else{throw New RuntimeException ("Server is really Busy");}} Return the link back to the pool public static void release (Connection conn) {POOL.ADD (conn);}}

Ii. writing a data source (DataSource) (important)

Write a class implementation Javax.sql.DataSource

public class MyDataSource1 implements DataSource {private static list< Connection> pool = collections.synchronizedlist (new arraylist<connection> ()); static{try {for (int i=0;i< 10;i++) {Connection conn = jdbcutil.getconnection ();//Create a new connection POOL.ADD (conn);}} catch (Exception e) {e.printstacktrace ();}} Get the link from the pool > Com.mysql.jdbc.Connectionpublic Connection getconnection () throws SQLException {if (pool.size () >0) { Connection conn = pool.remove (0); MyConnection1 mconn = new MyConnection1 (conn,pool); return mconn;} Else{throw New RuntimeException ("Server really Busy");}} 
Public PrintWriter Getlogwriter () throws SQLException {return null;} public void Setlogwriter (PrintWriter out) throws SQLException {}public void setlogintimeout (int seconds) throws Sqlexcept ion {}public int getlogintimeout () throws SQLException {return 0;} Public <T> T Unwrap (class<t> iface) throws SQLException {return null;} public boolean iswrapperfor (Class<?> iface) throws SQLException {return false;} Public Connection getconnection (string Username, string password) throws SQLException {return null;}}
Three, the difficulty of programming: (Design mode)

Difficulty: When you implement an instance of the Javax.sql.DataSource class, the user calls the Connection.close () method, closes the link, and loses the meaning of the connection pool.

Clear a question: the user obtains connection the realization is: The database drives to the connection interface implementation. Therefore, the call to the Close method is database-driven and it closes the link. (This is not what we want, we want to swap the link back into the pool).

Solution: Overwrite the original Close method that drives it. There are several coding options for functional changes to some/some methods of a known class:

A, inheritance: it won't work here.

What is the implementation of the drive to write sub-class (many)

Database-driven implementation classes for connection interfaces are not allowed to be inherited

Information about the original object was lost. Penny Wise lost the watermelon.

b, decoration (packaging) design mode: (Basic IO)

Keep the original information of the wrapped object, and you can rewrite some/some methods.

Formula:

1. Write a class that implements the same interface as the wrapper class (the database-driven implementation of connection). (Enables the same behavior for this class and the drive implementation of the database)

2. Define a variable that references the instance of the wrapped class.

3. Define the constructor method and pass in the instance of the wrapped class.

4, for the method to rewrite, write your own code can.

5. For methods that do not require rewriting, call the corresponding method of the original object.

The current packaging is: COM.MYSQL.JDBC.CONNECTION//1, write a class that implements the same interface as the wrapper class (the database-driven implementation of Connection). (Make this class and the database drive implementation have the same behavior) public class MyConnection implements Connection {//2, define a variable, reference the instance of the wrapped class private Connection conn;// Refer to the specific database driver private list<connection> POOL;//3, define the constructor method, and pass in the instance of the wrapped class. Public myconnection (Connection conn,list<connection> Pool) {//Dependency Injection this.conn = Conn;this.pool = Pool;} Return the link back to the pool//4, write your own code for the method you want to rewrite. public void Close () throws SQLException {POOL.ADD (conn);} Public Statement createstatement () throws SQLException {return conn.createstatement (); 5. For methods that do not require rewriting, call the corresponding method of the original object. Public <T> T Unwrap (class<t> iface) throws SQLException {return conn.unwrap (iface);}
C, default adapter: (for later preparation)
The default adapter/* itself is also a wrapper class, but does not overwrite any method 1, writing a class that implements the same interface as the wrapped class (the database-driven implementation of connection). (Make this class and the database drive implementation have the same behavior) 2, define a variable, reference the instance of the wrapped class. 3. Define the constructor method and pass in the instance of the wrapped class. 4, all call the corresponding method of the original object */public class Connectionadapter implements Connection {private Connection Conn;public Connectionadapter (Connection conn) {this.conn = conn;} Public <T> T Unwrap (class<t> iface) throws SQLException {return conn.unwrap (iface);} public boolean iswrapperfor (Class<?> iface) throws SQLException {return conn.iswrapperfor (iface);}

/* This is also packaging: packaging Connectionadapter. The wrapper class is the wrapper of the wrapper class, and it's his child class. 1, write a class, inheritance is already a wrapper class class. 2. Define a variable that references the instance of the wrapped class. 3. Define the constructor method and pass in the instance of the wrapped class. 4, overwrite the need to rewrite the method */public class MyConnection1 extends Connectionadapter {private Connection conn;private list<connection > Pool;public MyConnection1 (Connection conn,list<connection> pool) {super (conn); this.conn = Conn;this.pool = Pool;} public void Close () throws SQLException {POOL.ADD (conn);}}

D, dynamic Agent: (Very important aop--aspect-oriented programming core technology)

L interface-based dynamic agent: Proxy

If a class does not implement any interfaces, this type of proxy cannot be used.

Package Com.itheima.proxy;public interface Human {void sing (float money), void dance (float money);}

Package Com.itheima.proxy;public class Springbrother implements Human {public void sing (float money) {System.out.println ("Get the Money:" +money+ "Sing");} public void Dance (float) {System.out.println ("Get Money:" +money+ "open Jump");}}

Package Com.itheima.proxy;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy;public class Client1 {public static void main (string[] args) {final Human sb = new Springbrother () ;//Agent: How to dynamically generate Agent/*classloader loader: Dynamic agent, must have byte code class. To run in memory, there must be a class loader. Fixed: Same as being used by the agent class<?>[] interfaces: The interface to be implemented by the proxy class has the same behavior as the proxy object. Fixed: And being used by the agent is the same as Invocationhandler H: how to Proxy. He is an interface.         The policy design pattern. *///generates the proxy class, gets his instance Human Proxyman = (Human) proxy.newproxyinstance (Sb.getclass (). getClassLoader (), Sb.getclass ().  Getinterfaces (), new Invocationhandler () {///anonymous inner class, complete the specific proxy policy//call any method of the proxy class, it goes through this method. Intercept/* Object proxy: A reference to the proxy object. Method: Currently executing methods object[] args: The parameter return value used by the current method: The return value of the currently called Method */public object Invoke (Object proxy, method, object [] args) throws Throwable {//Judging the appearance fee if ("Sing". Equals (Method.getname ())) {//sing float money = (float) args[0];if (money> 10000) {Method.invoke (SB, MONEY/2);}} if ("Dance". Equals (Method.getname ())) {//sing float money = (float) ARGs[0];if (money>20000) {Method.invoke (SB, MONEY/2);}} return null;}}); Proxyman.sing (20000);p roxyman.dance (100000);}}

• Subclass-based dynamic proxy: CGLIB

Prerequisite: The requirements of the agent class

1. Cannot be final

2. Must be public

Package Com.itheima.cglib;public class springbrother{public void Sing (float money) {System.out.println ("Get Paid:" +money+ " Sing "); public void Dance (float) {System.out.println ("Get Money:" +money+ "open Jump");}}

Package Com.itheima.cglib;import Java.lang.reflect.method;import Net.sf.cglib.proxy.callback;import Net.sf.cglib.proxy.enhancer;import Net.sf.cglib.proxy.methodinterceptor;import Net.sf.cglib.proxy.MethodProxy; public class Client1 {public static void main (string[] args) {final Springbrother sb = new Springbrother ();//Agent producing SB:/*CLA SS Type: The parent type of the proxy class callback CB: Callback, how to proxy */springbrother proxy = (springbrother) enhancer.create (springbrother.class,new Methodinterceptor () {public object Intercept (object proxy, method, object[] Args,methodproxy Arg3) throws Throwable {//Judging the appearance fee if ("Sing". Equals (Method.getname ())) {//sing float money = (float) args[0];if (money>10000) { Method.invoke (SB, MONEY/2);}} if ("Dance". Equals (Method.getname ())) {//sing float money = (float) args[0];if (money>20000) {Method.invoke (SB, MONEY/2 );}} return null;}}); System.out.println (proxy instanceof Springbrother);p roxy.dance (100000);p roxy.sing (50000);}}

For example, an ordinary javabean may not implement any interface. The proxy class is a subclass of the proxy class.

Iv. use of Open source data sources: (very important, very simple)

1, DBCP:

Developed by the Apache organization. Dbcp:database Connection Pool, an implementation of the data source.

A, copy jar package

B. Write the configuration file

Dbcpconfig.properties

#连接设置driverClassName =com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/testusername=rootpassword=sorry#< !--Initialize connection-->initialsize=10# maximum number of connections maxactive=50#<!--maximum idle connection-->maxidle=20#<!--minimum idle connection-->minidle=5# <!--timeout wait time in milliseconds 6000 milliseconds/1000 equals 60 seconds-->maxwait=60000#jdbc the Connection property property that accompanies the driver when the connection is established must be in the format: [property name =property;] #注意: "User" and The "password" two attributes are explicitly passed, so there is no need to include them here. connectionproperties=useunicode=true;characterencoding=utf8# Specifies the auto-commit (Auto-commit) state of the connection created by the connection pool. Defaultautocommit=true#driver default Specifies the read-only (read-only) state of the connection created by the connection pool. #如果没有设置该值, the "setreadonly" method will not be called. (Some drivers do not support read-only mode, such as Informix) defaultreadonly= #driver default Specifies the transaction level (transactionisolation) of the connection created by the connection pool. #可用值为下列之一: (Details visible Javadoc. ) none,read_uncommitted, read_committed, Repeatable_read, Serializabledefaulttransactionisolation=repeatable_read

C, use can

public class Dbcputil {private static DataSource datasource;static{try {InputStream in = DBCPUtil.class.getClassLoader () . getResourceAsStream ("dbcpconfig.properties"); Properties props = new properties ();p rops.load (in);d Atasource = Basicdatasourcefactory.createdatasource (props);} catch (Exception e) {throw new Exceptionininitializererror (e);}} public static DataSource Getdatasource () {return DataSource;} public static Connection getconnection () {try {return datasource.getconnection ();} catch (SQLException e) {throw new Runti Meexception (e);}}

2, C3P0:

An open source data source implementation.

C3p0-config.xml

<?xml version= "1.0" encoding= "UTF-8"? ><c3p0-config><default-config><property name= " Driverclass ">com.mysql.jdbc.driver</property><property name=" Jdbcurl ">jdbc:mysql:///test</ Property><property name= "user" >root</property><property name= "password" >sorry</property ><property name= "initialpoolsize" >10</property><property name= "MaxIdleTime" >30</property ><property name= "maxpoolsize" >100</property><property name= "Minpoolsize" >10</property ><property name= "maxstatements" >200</property></default-config> <named-config name= "Day15 "><property name=" initialpoolsize ">10</property><property name=" MaxIdleTime ">30</ Property><property name= "maxpoolsize" >100</property><property name= "MinPoolSize" >10</ Property><property name= "Maxstatements" >200</property></named-config></c3p0-config>

public class C3p0util {private static Combopooleddatasource DataSource = new Combopooleddatasource ();p ublic static Dataso Urce Getdatasource () {return dataSource;} public static Connection getconnection () {try {return datasource.getconnection ();} catch (SQLException e) {throw new Runti Meexception (e);}}

3, closer to actual development: Jndi Management Data source

Jndi:java naming and Directory Interface. belongs to one of the Java EE Technologies and aims to mimic the registry in the window System.

A. Registering the Jndi data source in the server

1, copy the database drive to the Tomcat\lib directory

2. Create a configuration file named Context.xml in the Meta-inf directory of the Web application

<?xml version= "1.0" encoding= "UTF-8"? ><context><resource name= "Jdbc/test" auth= "Container" type= " Javax.sql.DataSource "               maxactive=" maxidle= "5" maxwait= "10000"               username= "root" password= "Sorry" Driverclassname= "Com.mysql.jdbc.Driver"               url= "Jdbc:mysql://localhost:3306/test"/></context>

3. Get the resources in the Jndi container

public class Jndidsutil {public static Connection getconnection () throws Exception {Context Initcontext = new Initialconte XT ();D atasource ds = (DataSource) initcontext.lookup ("Java:/comp/env/jdbc/test"); Connection conn = Ds.getconnection (); return conn;}}

V. Prepare your own JDBC framework (for Learning Dbutil framework, Spring JdbcTemplate)

1, database meta-information acquisition (for writing framework and preparation)

Meta information: Some of the database's definition information. For example, what database is used, such as the definition information of the table.

  databasemetadata    preparedstatement     Resultsetmetadata getcolumncount

Get the database meta-Information get public class Demo {//The database itself information gets @testpublic void Test1 () throws Exception{connection conn = Dbcputil.getconnection ();D atabasemetadata DMD = Conn.getmetadata (); String name = Dmd.getdatabaseproductname ();//can know what to say dialect System.out.println (name); int isolation = Dmd.getdefaulttransactionisolation (); SYSTEM.OUT.PRINTLN (isolation);} Parameter metadata information: PreparedStatement @testpublic void Test2 () throws Exception{connection conn = Dbcputil.getconnection (); PreparedStatement stmt = conn.preparestatement ("??????????"); Parametermetadata PMD = Stmt.getparametermetadata (); int count = Pmd.getparametercount (); System.out.println (count);//The number of placeholders in the statistics statement}//result set metadata information: @Testpublic void Test3 () throws Exception{connection conn = Dbcputil.getconnection (); PreparedStatement stmt = conn.preparestatement ("SELECT * from Account"); ResultSet rs = Stmt.executequery (); ResultSetMetaData RSMD = Rs.getmetadata (); int count = Rsmd.getcolumncount ();//There are several columns of System.out.println (count); for (int i= 0;i<count;i++) {String fieldName = Rsmd.getcolUmnname (i+1); int type = Rsmd.getcolumntype (i+1); System.out.println (fieldname+ ":" +type);}}}

2. Writing the JDBC Framework: (Policy design mode)

/** * Framework Core class * @author wzhting * */public class Dbassist {private DataSource datasource;public dbassist (DataSource Datasou RCE) {this.datasource = DataSource;} Write: Add, delete, modify//params parameters to correspond to placeholders in SQL public void Update (String sql,object...params) {Connection conn = null; PreparedStatement stmt = null; ResultSet rs = Null;try{conn = Datasource.getconnection (); stmt = conn.preparestatement (sql);//Set parameters// Get the parameters in sql Parametermetadata PMD = stmt.getparametermetadata (), int count = Pmd.getparametercount (), if (count>0) {if ( Params==null) {throw new RuntimeException ("value must pass in Parameter");} if (count!=params.length) {throw new RuntimeException ("The number of parameters does not match");} for (int i=0;i<count;i++) {stmt.setobject (i+1, params[i]);}} Stmt.executeupdate ();} catch (Exception e) {throw new RuntimeException (e);} Finally{release (RS, stmt, conn);}} READ: Querying public Object query (String sql,resultsethandler rsh,object...params) {Connection conn = null; PreparedStatement stmt = null; ResultSet rs = Null;try{conn = Datasource.getconnection (); stmt = Conn.preparestAtement (SQL);//Set parameters//Get parameters in sql Parametermetadata PMD = stmt.getparametermetadata (); int count = Pmd.getparametercount ( if (count>0) {if (params==null) {throw new RuntimeException ("value must pass in Parameter");} if (count!=params.length) {throw new RuntimeException ("The number of parameters does not match");} for (int i=0;i<count;i++) {stmt.setobject (i+1, params[i]);}} rs = Stmt.executequery ();//There is a result set that you want to encapsulate into the object. Policy design mode return Rsh.handle (RS);} catch (Exception e) {throw new RuntimeException (e);} Finally{release (RS, stmt, conn);}} private void Release (ResultSet rs,statement stmt,connection conn) {if (rs!=null) {try {rs.close ();} catch (SQLException e) {E.printstacktrace ();} rs = null;} if (stmt!=null) {try {stmt.close ();} catch (SQLException e) {e.printstacktrace ();} stmt = null;} if (conn!=null) {try {conn.close ();} catch (SQLException e) {e.printstacktrace ();} conn = null;}}}

Public interface Resultsethandler {/** * encapsulates the data in the result into the specified object * @param rs * @return The object that encapsulates the data */object handle (ResultSet RS);}

/** * Fits only one query result * encapsulated into JavaBean * Meet Convention: Database field name and JavaBean field name are consistent * @author wzhting * */public class Beanhanlder implements Resultsethandler {Private class clazz;//target type public beanhanlder (Class clazz) {this.clazz = Clazz;} public object Handle (ResultSet Rs) {try {if (Rs.next ()) {//has Record object bean = Clazz.newinstance ();//target object//How many columns are there, and what are the column names and values? ResultSetMetaData RSMD = Rs.getmetadata (); int count = Rsmd.getcolumncount ();//column number for (int i=0;i<count;i++) {String FieldName = Rsmd.getcolumnname (i+1);//Get the database field name and get the Javaban field name Object fieldvalue = Rs.getobject (fieldName);//field value// Fields are reflected by field F = Clazz.getdeclaredfield (FieldName); f.setaccessible (true); F.set (bean, fieldvalue);} return bean;} return null;} catch (Exception e) {throw new RuntimeException (e);}}}

/** * encapsulated into JavaBean * Meet Convention: Database field name and JavaBean field name are consistent * @author wzhting * */public class Beanlisthanlder implements Resultsetha Ndler {Private class clazz;//target type public beanlisthanlder (Class clazz) {this.clazz = Clazz;} public object Handle (ResultSet Rs) {try {list List = new ArrayList (), while (Rs.next ()) {//have record Object bean = clazz.newinstance ()///target object//How many columns are there, and what are the column names and values? ResultSetMetaData RSMD = Rs.getmetadata (); int count = Rsmd.getcolumncount ();//column number for (int i=0;i<count;i++) {String FieldName = Rsmd.getcolumnname (i+1);//Get the database field name and get the Javaban field name Object fieldvalue = Rs.getobject (fieldName);//field value// Fields are reflected by field F = Clazz.getdeclaredfield (FieldName); f.setaccessible (true); F.set (bean, fieldvalue);} List.add (bean);} return list;} catch (Exception e) {throw new RuntimeException (e);}}}

Javaweb Backend < 10 > Data pool c3p0 DPCB JNDI

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.