Caucho maker of Resin Server | Application Server (Java EE Certified) and Web Server


 

Resin Documentation

home company blog docs 
app server 
 Resin Server | Application Server (Java EE Certified) and Web Server
 

database configuration


Resin provides a robust and tested connection pool that is used to obtain connections to databases.

Basic Configuration

A basic <database> configuration specifies the following:

  • The JNDI name where the configured DataSource will be stored
  • The database driver's main class
  • The driver-specific url for the database.
  • Any user and password information.
Example: mysql configuration
<web-app xmlns="http://caucho.com/ns/resin">

<database jndi-name='jdbc/test_mysql'>
  <driver type="com.mysql.jdbc.Driver">
    <url>jdbc:mysql://localhost:3306/test</url>
    <user></user>
    <password></password>
  </driver>
</database>

</web-app>

This <database> will configure a javax.sql.DataSource and store it in JNDI at java:comp/env/jdbc/test_mysql. To use the data source, follow the database use pattern in the DataSource tutorial.

Although some deployments will specify driver and connection pool parameters, the default values will be fine for most applications.

Core Concepts

Connection

connection
An established channel of communication between a client and a server. The client and the server may be on separate machines, on the same machine, or even running in the same JVM. Often the connection is established using TCP/IP as the transport of communication.

A database connection is used to allow the Java program, running in a JVM, to communicate with a database server.

Connection Pool

connection pool
A set of connections maintained so that the connections can be reused when there is a future need for the conneciton.

Connection pools are used to reduce the overhead of using a database. Establishing a connection to the database is a costly operation. A connection pool keeps a pool of open connections, each connection can be used for a time as needed, and then released back to the pool. A connection that has been released back to the pool can then be reused.

Connection pooling is especially important in server applications. The overhead of opening a new connection for each new client request is too costly. Instead, the database pool allows for a connection to be opened once and then reused for many requests.

DataSource

DataSource
A JDBC term (and interface name) used for a factory that is used to obtain connections.

Resin provides an implementation of DataSource. Resin's implementation of DataSource is a connection pool.

Driver

driver
An implemetation of a defined interface that hides the details of communication with a device or other resource, such as a database.

A Driver provides an interface and is responsible for the communication with the database. Every different database (i.e Oracle, MySQL) has their own means of enabling communication from the client (in this case Resin and you applications) and the database. The Driver provides a common interface that hides the details of that communication.

Transaction

transaction
A transaction is used to mark a group of operations and provide a guarantee that all of the operations happen, or none of them happen. Transactions protect the integrity of the database.

Transactions are especially important in server applications where many threads of processing may be interacting with the database at the same time.

For a simple example, imagine a set of operations that reads a value, calculates a new value, and then updates the database.

Example: simple set of database operations
read value A=1 
calculate  A=A+1 
update     A=2

read value A=2 
calculate  A=A+1 
update     A=3

Imagine if one thread is performing this operation, and in the middle of this read/calculate/update, another thread performs an update. The data that the first thread obtained from the read and is using for the calculation and update is no longer valid.

Example: 2 Threads with database race condition
 Thread 1                 Thread 2
 --------                 --------
 read value A=1           read value A=1
 calculate  A=A+1         calculate A=A+1
                          update A=2
 update     A=2

Placing the read/calculate/update operations in a transactions guarantees that only one thread can perform those operations at a time, if a second thread comes along and tries to perform the operation, it will have to wait for the first thread to finish before it can begin.

Example: 2 Threads protected with transactions

Thread1                Thread 2
-------                --------
read value A=1         
calculate  A=A+1       (tries to read A, but has to wait for thread 1)
update     A=2
                       read value A=2
                       calculate A=A+1
                       update A=3

Distributed Transaction

distributed transaction
A distributed transaction is a transaction that involves more than one connection.

If the guarantees that transactions apply need to apply to operations that occur on two databases within the same transaction, distributed transactions are needed.

If A and B in the following example are in two different databases, then a distributed transaction is needed:

Example: Simple set of database operations
read value db1.A=1 
read value db2.B=99
calculate  A=A+1 
calculate  B=B-A 
update     db1.A=2
update     db2.B=97

Distributed transactions are rarely needed, and few databases really support them.

Core Configuration

<database>

<database> defines a database (i.e. DataSource) resource.

<database> Attributes
ATTRIBUTEDESCRIPTIONDEFAULT
backup-driverConfigures a backup database driver. If Resin can't connect to any of the main drivers, it will use one of the. backups
close-dangling-connectionsIf an application does not close a Connection by the end of the request, Resin will close it automatically an issue a warning.true
commit-on-timeouttrue to commit the transaction on timeout, false to rollbackfalse
<connection>Defines initialization attributes for new connections, e.g. setting the transaction-isolation.true
connection-wait-timeWhen max-connections has been reached, how long Resin will wait for a connection to become idle before giving up.10min
driverConfigures the database driver, giving the driver's class name as well as its JDBC URL and any other configuration.required
jndi-nameThe JNDI name to register the connection's DataSource under. The name can be relative to java:comp/env.
max-active-timeThe maximum time Resin will allow a connection to remain open before forcing a close.6h
max-close-statementsThe maximum number of Statements Resin will hold to automatically close when the Connection closes.256
max-connectionsThe maximum number of Connections allowed.128
max-create-connectionsThe maximum number of connection creation allowed at one time.5
max-idle-countThe maximum number of Connections in the idle pool.1024
max-idle-timeThe maximum time a connection will spend in the idle pool before closing.30s
max-overflow-connectionsThe number of extra connection creation if the number of connections exceeds to pool size.0
max-pool-timeThe total time a connection can be used before it is automatically closed instead of returned to the idle pool.24h
nameThe IoC name to save the ConnectionFactory as, used with @Named to inject the resource.
passwordThe JDBC password for the connection.
pingIf true, Resin will ping the database before returning a connection from the pool (if ping-interval is exceeded).false
ping-intervalHow often an idle connection should ping the database to ensure it is still valid.1s
ping-queryA custom query used to ping the database connection.
ping-tableA table used to ping the database connection.
prepared-statement-cache-sizeHow many PreparedStatements to save in the prepared statement cache.0
save-allocation-stack-traceIf true, saves the location of the connection allocation as a stack trace.false
spyEnables spy logging of database statements. The logging occurs with name="com.caucho.sql" and level="fine".false
transaction-timeoutSets the transaction timeout.none
userSets the authentication user.
wrap-statementsIf true, Resin wraps statements and automatically closes them on connection close.true
xaEnables automatic enlistment of Connections with any UserTransaction. Disabling <xa> means the connection are independent of transactions, useful for read-only connections.true
xa-forbid-same-rmWorkaround flag to handle certain database drivers that do not properly implement the XAResource API.false
<database> schema
database = element database {
  backup-driver*
  & close-dangling-connections?
  & commit-on-timeout?
  & connection?
  & connection-wait-time?
  & driver+
  & jndi-name?
  & max-active-time?
  & max-close-statements?
  & max-connections?
  & max-create-connections?
  & max-idle-count?
  & max-idle-time?
  & max-overflow-connections?
  & max-pool-time?
  & name?
  & password?
  & ping?
  & ping-interval?
  & ping-query?
  & ping-table?
  & prepared-statement-cache-size?
  & save-allocation-stack-trace?
  & spy?
  & transaction-timeout?
  & user?
  & wrap-statements?
  & xa?
  & xa-forbid-same-rm?
}

backup-driver = element backup-driver {
  class?
  & url?
  & element * { * }?
}

connection = element connection {
  catalog?
  & read-only?
  & transaction-isolation?
}

driver = element driver {
  class?
  & url?
  & element * { * }?
}

Example: WEB-INF/resin-web.xml database
<web-app xmlns="http://caucho.com/ns/resin">

<database jndi-name='jdbc/test_mysql'>
  <driver class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
    <url>jdbc:mysql://localhost:3306/test</url>
    <user></user>
    <password></password>
  </driver>
</database>

</web-app>

Driver Configuration

driver

child of <database>

Configure a database driver. The driver is a class provided by the database vendor, it is responsible for the communication with the database.

The jar file with the driver in it can be placed in WEB-INF/lib, although it is often best to place your datbase driver's jar file in $RESIN_HOME/lib/local/, which makes the driver available to all of your web applications.

The class that corresponds to <driver> is com.caucho.sql.DriverConfig

ATTRIBUTEDESCRIPTION
typeThe Java class name of the database driver.
urlThe driver specific database url.
userThe username to give the database driver.
passwordThe password to give the database driver.
init-paramSet driver specific properties not known to Resin.

Choosing a driver class for <type>

Database vendors usually provide many different classes that are potential candidates for type. The JDBC api has developed over time. The driver you choose depends on the options the vendor offers, and whether or not you need distributed transactions.

JDBC 2.0 - ConnectionPoolDataSource

JDBC 2.0 defined the interface ConnectionPoolDataSource. A ConnectionPoolDataSource is not a connection pool, but it does provide some extra information that helps Resin to pool the connection more effectively.

A driver that implements ConnectionPoolDataSource is better than a JDBC 1.0 driver that implements Driver.

JDBC 2.0 - XADataSource

JDBC 2.0 defined the interface XADataSource for connections that can participate in distributed transactions. A distributed transaction is needed when transactions involve multiple connections. For example, with two different database backends, if the guarantees that transactions apply need to apply to operations that occur on both databases within the same transaction, distributed transactions are needed.

Distributed transactions are rarely needed, and few databases really support them. Some vendors will provide XADataSource drivers even though the database does not really support distributed transactions. Often, XADataSource drivers are slower than their ConnectionPoolDataSource counterparts.

XADataSource should only be used if distributed transactions are really needed, and can probably be safely ignored for most applications.

JDBC 1.0 - Driver

Driver is the original JDBC interface, and is the least desirable kind of driver to use. Resin can still pool database connections using these drivers, but it will not be as efficient as the newer drivers.

Set driver properties with init-param

init-param is used to set properties for java.sql.Driver database drivers. More modern drivers like ConnectionPoolDataSource will not use init-param, but will use IoC-style tags directly.

For example, MySQL drivers accept the useUnicode parameter, if true the driver will use Unicode character encodings when handling strings.

Example: mysql configuration
<database>
  <jndi-name>jdbc/mysql</jndi-name>
  <driver>
    <type>com.mysql.jdbc.Driver</type>
    <url>jdbc:mysql://localhost:3306/dbname</url>
    <user>username</user>
    <password>password</password>

    <init-param useUnicode="true"/>
  </driver>
  ...
</database>
Example: mysql ConnectionPoolDataSource
<database>
  <jndi-name>jdbc/mysql</jndi-name>
  <driver>
    <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
    <url>jdbc:mysql://localhost:3306/dbname</url>
    <user>username</user>
    <password>password</password>

    <useUnicode/>
  </driver>
  ...
</database>

Pooling Configuration

Pooling configuration controls the behaviour of Resin's pooling of database connections. For most applications and databases the only needed change is to increase the max-connections value to meet high demand. Other pooling parameters have defaults that are based on our years of experience with many different databases in many different applications. Changes from the defaults should only be done in response to specific problems, and with a good understanding of how pooling works.

Reliability Configuration

ping

Resin's database pool can test if the pooled database connection is still alive by configuring a ping query. This is typically only necessary if the pooling parameters are changed from their default values.

If the pool is configured with a long max-idle-time the database connection may become stale if the database is restarted, or if the database is configured with a shorter connection timeout value than the configuration of the Resin pool. Normally when a database connection is returned to the pool it will wait there until the next request or the idle-time expires. If the database goes down in the meantime or closes the connection, the connection will become stale. The ping configuration can test the database connection.

When pinging, Resin's DBPool will test a table specified with the ping-table parameter before returning the connection to the application. If the ping fails, the connection is assumed to be no good and a different connection from the pool is returned. For a ping-table of BROOMS, Resin will use the query select 1 from BROOMS where 1=0

Example: <ping> configuration
  <database jndi-name="...">
    <driver type="...">
      ...
    </driver>

    <ping>true</ping>
    <ping-table>BROOMS</ping-table>
  </database>

You can test the ping using the following steps:

  1. Configure the database with ping-table and ping.
  2. Execute some servlet that queries the database.
  3. Restart the database server.
  4. Execute another servlet that queries the database.

<driver> list

If there is a pool of database servers available that can be used for database operations, Resin can be configured with a list of <driver> tags. Resin uses a round robin algorithm to cycle through the list of drivers when obtaining connections. If a particular <driver> fails to provide a connection, Resin continues the attempt to obtain a connection. If all of the configured drivers fail to provide a connection the exception is propogated to the caller.

Example: A <driver> list
<database jndi-name="jdbc/hogwarts">
  <driver>
    <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
    <url>jdbc:mysql://192.168.0.110:3306/hogwarts</url>
    ...
  </driver>

  <driver>
    <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
    <url>jdbc:mysql://192.168.0.111:3306/hogwarts</url>
    ...
  </driver>
  ...
</database>

<backup-driver> list

Drivers in a driver list can be marked as backups. The drivers configured with <backup-driver> are used only if all of the drivers configured with <driver> have failed.

Each time a new connection is needed Resin goes through the process of first attempting to use one of the <driver> configured drivers to get a connection, and if that fails then the <backup-driver> are used. A new connection is needed from the driver if the pool of connections that is maintained by Resin does not contain an idle connection. The Pooling configuration and the usage pattern of the application determine how often a connection is obtained from a driver. The pooling configuration typically allows a single real connection to be reused by the application many times.

The lifetime of a connection obtained from a <backup-driver> is determined by the Pooling configuration, thus even if the main <driver> becomes available again a connection previously obtained from a <backup-driver> will continue to be used until it expires from the pool.

Example: A <backup-driver> list
<database jndi-name="jdbc/hogwarts">
  <driver>
    <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
    <url>jdbc:mysql://192.168.0.110:3306/hogwarts</url>
    ...
  </driver>

  <driver>
    <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
    <url>jdbc:mysql://192.168.0.111:3306/hogwarts</url>
    ...
  </driver>

  <backup-driver>
    <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
    <url>jdbc:mysql://192.168.0.112:3306/hogwarts</url>
    ...
  </backup-driver>

  <backup-driver>
    <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type>
    <url>jdbc:mysql://192.168.0.113:3306/hogwarts</url>
    ...
  </backup-driver>
  ...
</database>

Obtaining and using a database connection

Getting the DataSource

The DataSource is a factory that is used to obtain a connection. The DataSource is obtained using the <jndi-name> specified when configuring the database resource.

Ideally, the JNDI lookup of DataSource is done only once, the DataSource obtained from the lookup can be stored in a member variable or other appropriate place. The stored DataSource can then be used each time a connection is needed. If it is not stored, there will be an impact on performance from having to do the lookup each time you want to get a connection.

Example: Obtaining a DataSource
import javax.sql.*;
import javax.webbeans.*;

public class .... {
  @Named("jdbc/test") DataSource _pool;

  ...
}

Getting a Connection

A connection is obtained from the DataSource. The connection is used as needed, and then released with a call to close() so that Resin knows it is available for a subsequent request.

It is very important that the close() is always called, even if there as an exception. Without the close(), Resin's database pool can loose connections. If you fail to close() a connection, Resin does not know that it is available for reuse, and cannot allocate it for another request. Eventually, Resin may run out of connections.

Warning Always put a close() in a finally block, to guarantee that it is called.

The following example shows the use of a finally block that contains the close(). Because the close() is in a finally block, it will happen even if the code using the connection throws an exception.

Example: Getting a connection from the DataSource
package javax.webbeans.*;
package javax.sql.*;

public class MyBean()
{
  @In DataSource _pool;

  public void doStuff()
  {
    Connection conn = null;
    try {
      conn = _pool.getConnection();

      Statement stmt = conn.createStatement();

      ResultSet rs = stmt.executeQuery(" ... ");

      ...

      rs.close();
      stmt.close();
    } catch (SQLException e) {
      throw new ServletException(e);
    } finally {
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException e) {
      }
    }
  }
}

Getting the underlying driver connection

The connection obtained by pool.getConnection() is an instance of com.caucho.sql.UserConnection.

UserConnection is a wrapper around the real driver connection, it allows Resin to intercept the close() call and manage the underlying driver connection.

In rare circumstances it is necessary to obtain the real connection returned by the driver. Typically this is a requirement for situations where the driver provides a specialized API that is not available with the standard JDBC API.

Example: Getting the underlying driver connection
Connection driverConn = ((com.caucho.sql.UserConnection) connection).getConnection();

// never do this: driverConn.close()

Protecting the database password

Resin provides facilities that allow you to plugin your own custom code that returns a password to Resin. However any solution is vulnerable, unless you require a person to type in a password every time Resin starts (or restarts). Typically the security of the machine hosting Resin, and proper permissions on the readability of the resin.xml file, are sufficient to protect your database password.

The solution shown below is not really secure because you can disassemble the Password code to get the decryption key, but it may be marginally better than plaintext.

Example: password encryption
<driver type="..."> 
  <password xmlns:hogwarts="urn:java:com.hogwarts">
    <hogwarts:Password value="mX9aN9M=="/>
  </password>
  ...

You will need to provide com.hogwarts.Password:

Example: Password class
package com.hogwarts;

public class Password { 
  private String _value; 
 
  public void setValue(String value) 
  { 
    _value = value; 
  } 
 
  public Object replaceObject() 
  { 
    return decrypt(_value); 
  } 

  private String decrypt(String encrypted)
  {
    ... custom code ...
  }
} 

This solution is completely general, you can use <mypkg:MyClass/> anywhere in the configuration files where a string value is allowed.

Resin does not provide the equivalent of com.hogwarts.Password because it's not really secure. Providing that kind of solution would lead some to believe it was a secure solution.

Hibernate

Resin comes with JPA 2.0 interfaces that are not compatible with Hibernate and JPA 2.1+. To override Resin's classes, add the Hibernate jar to the directory that you can specify in <jvm-classpath>.

<resin xmlns="http://caucho.com/ns/resin">
  <cluster id="web-tier">
    <server-default>
      <jvm-classpath>/tmp/test-classpath</jvm-classpath>
    </server-default>

    <server id="app-a" address="192.168.2.10"/>

    ...
  </cluster>
</resin>

An alternative is to reverse the normal classloading order by adding <servlet-hack> to your resin-web.xml, which gives webapp classes priority over Resin's classpath classes.


Copyright © 1998-2015 Caucho Technology, Inc. All rights reserved. Resin ® is a registered trademark. Quercustm, and Hessiantm are trademarks of Caucho Technology.