Singleton JNDI reads configuration files and databases connected to the data source

Singleton pattern profile read from the database

Singleton pattern refers to a class has only one instance, he can only be called by itself, if people want to call, you need to provide such a common access method to obtain instance.

1. Create a .properties file used to store information in a database connection

diver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/kgcnews?characterEncoding=UTF-8
user=root
password=123456

2. Create a class to read configuration files ConfigManager +++

Import a java.io.FileInputStream;
 Import java.io.FileNotFoundException;
 Import java.io.IOException;
 Import a java.io.InputStream;
 Import the java.util.Properties;
 // Lazy mode reads the configuration file 
public  class ConfigManager {
     // . 1 creating an object privatization through the ConfigManager 
    Private  static ConfigManager cm & lt;
     // Create a profile object 
    the Properties Properties; 

    // 2. privatization constructor with no arguments 
    Private   ConfigManager () {
 //         String file = "D: \\ \\ Workspace the Properties \\ \\ src \\ the Login database.properties ";
 //        = new new FileInputStream inputStream (File);
         // "database.properties" as .properties filename 
        String File = "database.properties" ;
         // convert the file into a byte stream ConfigManager.class.getClassLoader () find themselves located class class loader 
        . inputStream = ConfigManager the inputStream class . .getClassLoader () the getResourceAsStream (File); 
        
        
        properties = new new the Properties ();
         the try {
             // write the properties object 
            Properties.load (inputStream); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } 
    } 
    //3. The access point provides a global instance of the object obtained 
    public  static   ConfigManager getCm () {
         // If the object (instance of the class) is not created 
        IF (cm & lt == null ) {
             // synchronized creation of objects by 
            the synchronized (ConfigManager. Class ) { 
                cm & lt = new new ConfigManager (); 
            } 

        } 
        // instance of the class to return 
        return   cm & lt; 
    } 
    // get the value profile by the method getProperty (key) method 
    public String getProRes (String para) {
         return   Properties.getProperty ( para); 
    } 

    public  static void main(String[] args) {
        System.out.println(ConfigManager.getCm().getProRes("driver"));
    }
}

 

Starving mode:

  1. Create a private instance directly pirvate ConfigManager cm = new ConfigManager ();

  2. privatization constructor with no arguments private ConfigManager () {};

      3. Examples of a common method of obtaining privtae static ConfigManager getConf () {return cm;}

The difference between lazy mode and starving mode: first loads, high efficiency mode hungry man. Loaded more than once lazy mode conserves memory resources.

JNDI data source connection

Connection pooling, data source, the relationship between the three and the use of JNDI

Source:
the data source (the DataSource) used to connect to the database, to create a connection (Connection) object.
java.sql.DataSource interface is responsible for establishing a connection to the database
is provided by Tomcat, will save the connection in the connection pool.


Connection Pooling:
connection pool is provided by the container (such as Tomcat) used to manage the connection objects in the pool.
Connection pools and connection objects automatically assigned idle connection recovery.
Connection object connection pool is created by the data source (DataSource).
Connection pool (Connection Pool) used to manage the connection (Connection) object.


JNDI (Java Naming and Directory Interface, Java Naming and Directory Interface):
Use JNDI data source from within the program.


Connection object created by a unified data source is placed in the connection pool management.


Clear the relationship between the three, and then the following configuration:

C3P0 connection pool configured in the Spring configuration file application.xml:

<!-- 配置C3P0连接池: -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

Configuration and method for using a data source data source:

1, the configuration of Tomcat conf / context.xml

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


name = JNDI name of the specified Resource
auth = specify the Resource Management Manager (Container creation and management by the container, Application application created and managed by Web)
of the type specified Resource = java class
maxActive = specify the database connection pool is active connections the maximum number of
maxIdle = specified connection pool is in an idle state the maximum number of database
maxWait = specify the connection pool the connection is idle most of the time, more than this time will prompt abnormal, the value is -1, which means you can wait indefinitely, units in milliseconds (ms)
Do not forget here: also need to add to the database driver jar package, Tomcat installation directory under the lib file folder.

2, using JNDI to get connection object
lookup (java: comp / env / Data Source Name ");
// the Java: CoMP / env / This is the Java syntax requirements, must write.
// Here is the data source name above jdbc / news, this news is the project name.

 

3. Write code to get data source

  public Connection getConnection2 () {
    the try {
     // initialization context 
    the Context CXT = new new the InitialContext ();
     // Get the data source object associated with the logical name 
    DataSource ds = (DataSource) cxt.lookup ( "java: comp / env / jdbc / News " ); 
    Conn = ds.getConnection (); 
   } the catch (a NamingException E) {
     // the TODO Auto-Generated Block the catch 
    e.printStackTrace (); 
   } the catch (SQLException E) {
     // the TODO Auto-Generated the catch Block 
    E .printStackTrace (); 
   } 
   return Conn; 
  }

 

Another point to note: the test connection is successful, the need jsp page output connection, instead of java class Run As, should be configured in Tomcat need to project into the Tomcat Web container to run as a data source. jsp page code is as follows:

Example: 

<%
BaseDao baseDao=new BaseDao();
Connection connection=baseDao.getConnection2();

%>

<%=connection %>

 

 

In the configuration of Tomcat

Configuration: context.xml file within

F:\apache-tomcat-7.0.68-windows-x64\apache-tomcat-7.0.68\conf\context.xml

---------mySQL
<Resource name="jdbc/news"
auth="Container" type="javax.sql.DataSource"
maxActive="100"
maxIdle="30" maxWait="10000" username="root"
password="Admin001"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/news"/>

 

----------Oracle
<Resource name="jdbc/orcl"
auth="Container" type="javax.sql.DataSource"
maxActive="100"
maxIdle="30" maxWait="10000" username="wuyong"
password="Admin001"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"/>

 

Obtaining a connection object using JNDI
Java: CoMP / the env / JDBC / News

This is a fixed writing
java: comp / env /

 

JNDI and JDBC difference:

Java Database Connectivity (JDBC) is a standard Java API, which consists of a set of classes and interfaces, Java application developers use to access the database and execute SQL statements JNDI (Java Name Directory Interface), can not only locate database it is a unique identifier for the current application server manages all resources, including databases, web pages, documents, connection pooling, and so on.

In weblogic encounter when configuring a JDBC data source JNDI this totally strange word, it is checked, simple to understand.
JDBC: jdbc database agents to the middle of java is a protocol may be connected to a database or a method, a database interface, database connectivity through jdbc-odbc methods, Java application developers use to access the database and perform SQL statement
JNDI: java programmers familiar with the language, understand the technology and JDBC MySQL, you can quickly develop the appropriate application. But the encounter

1, the database server name MyDBServer, user name and password may need to change, triggered JDBC URL needs to be modified;

2, the database may switch to other products, such as Oracle or DB2 use, initiator JDBC Driver class name and the package needs to be modified;

3, with the increase in the actual use of the terminal, the connection pool configuration parameters may require adjustments to the original; and so on.

Solution:

Programmers should not need to be concerned about "what specific database back-end? What JDBC driver is? What JDBC URL format? What user name and password to access the database is?" And so these issues, programs written for JDBC programmers should not drivers references, no server name, no user name or password - or even no database connection pool management. But these issues to the J2EE container configuration and management, the programmer only needs to configure and manage these can be referenced.
Thus, there is the practice of using JNDI after JNDI:. First, JNDI configuration parameters within a J2EE container, define a data source, i.e. JDBC reference parameters, the data source to set a name; then, in the program , to access back-end data source database referenced by data source name.

 

Guess you like

Origin www.cnblogs.com/jiayiblog/p/11056685.html