Detailed Tomcat 6 JNDI data source

Database connection pool should be no stranger to this concept, that is, the connection pool database connection pool in Java, which is a kind of ideological connection multiplexing using multiple connections to avoid waste of resources mechanism.

The most common is the DBCP connection pool and C30P, and use the default in the tomcat DBCP connection pool is used by default in Hibernate is C3P0. Their most obvious difference for the user is that, by default, does not provide a release idle DBCP connection, you need to manually open.

The following describes the data Tomcat connection pool configuration and use.

 

Introduction

  Benpian rely on a concept --JNDI, you can refer back to the blog: the JNDI resources explain .

  For the JNDI, can be simply understood as a resource pool in Tomcat, by some unique names correspond to a particular resource, similar to a map, can be obtained simply by the name of the resource.

  So this blog entry JNDI data source is the data source to configure a resource acquired in the application via the database name, operation. This eliminates the need to connect to the database each time step.

Connection pooling principle

  The concept of connection pooling, should not a stranger. Part of the contents can refer to: several mainstream connection pool

  A brief description here under, if the application uses a separate connection pool, connection pool may just create run-time applications. The tomcat configuration data source can be initialized tomcat connection pool when the container starts, stops when tomcat release resources, deployed applications, according to a statement JNDI, shared use of the resources in the application.

  So a connection pool applications (ie, a different business applications using the connection pool, such as registering new users with the purchase of goods), a connection pool can expand to a multi-application, but also the use of specific business needs.

 

  Further, Tomcat DBCP connection pool to use the default, which is located in the jar package CATALINA_HOME / lib, Tomcat-dbcp.jar .

  Note that, dbcp by default not to release free connections. For example, when we coding, get a business connection to perform the operation, but no release. At this point, DBCP connection pool will not be put back into the idle queue. If no new connections will be allocated to other connections. When the number of connections is too large, it will cause obstruction connection.

  May be automatically recovered via some configuration attributes, the first set removeAbandoned = "true" open recovered and then set removeAbandonedTimeout = "300" set time connections, this time is exceeded will automatically retracted.

  Specific content can refer to: DBCP documentation

Mysql Case

  The following steps:

  1 placed mysql driven: to be here to download

  2 Create a database insert data

  3 Configure JNDI resources (context.xml and web.xml)

  4 Create JSP validation results

  

  Placing a drive

  Lib placed in the drive mysql tomcat root directory.

  2 Create a database table and add data

  Refer to the following SQL script:

/*
SQLyog v4.05
Host - 4.1.11-nt : Database - test
*********************************************************************
Server version : 4.1.11-nt
*/


create database if not exists `test`;

USE `test`;

/*Table structure for table `test`.`stu` */

drop table if exists `test`.`stu`;

CREATE TABLE `stu` (
  `id` int(11) NOT NULL default '0',
  `name` char(1) default NULL,
  `age` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

/*Data for the table `test`.`stu` */

insert into `test`.`stu` values (0,'x',26),(1,'z',27),(2,'w',25);

  3 Configure JNDI resources

  First, add <resource> in the context.xml

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="root" password="123456" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/test"/>

  Where username is your user name, password is the password.

  maxActive specifies the maximum number of connections, maxIdle specify the maximum number of idle connections (ie not connected, how much to save the connection), maxWait specify the maximum number of waiting connections.

  Then configure the resource name specified in web.xml (not required)

<resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

  4 Create JSP page output

  The following code creates and releases the connection:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    import="javax.naming.*,java.sql.*,javax.sql.*"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>Results</h2>
    <%
    Context initContext = new InitialContext();
    Context envContext  = (Context)initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");
    Connection conn = ds.getConnection();
    String sql = "select * from stu";
    PreparedStatement st = conn.prepareStatement(sql);
    ResultSet rs = st.executeQuery();
    while(rs.next()){
        out.println("name:"+rs.getString(2)+" age:"+rs.getInt(3)+"<br>");
    }
    if(rs!=null){
        try{
            rs.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        rs = null;
    }
    if(st!=null){
        try{
            st.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    if(conn!=null){
        try{
            conn.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    %>
</body>
</html>

  The final results of the implementation:

Other configurations

  Other configurations, such as Oracle and PostgreSQL just different JNDI name, and create database-driven needs:

  For example, in the oracle, context.xml configured as follows:

<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/>

  In PostgreSQL configured as follows:

<Resource name="jdbc/postgres" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://127.0.0.1:5432/mydb"
          username="myuser" password="mypasswd" maxActive="20" maxIdle="10"
maxWait="-1"/>

  Use are similar.

reference

[1] Several mainstream connection pool: http://developer.51cto.com/art/201006/207768.htm

[2] DBCP official document: http://commons.apache.org/proper/commons-dbcp/configuration.html

【3】Tomcat JNDI Database:http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html

Reproduced in: https: //my.oschina.net/u/204616/blog/545068

Guess you like

Origin blog.csdn.net/weixin_33671935/article/details/91989344