Saturday 28 January 2017

DataSource - Connection Cook

Datasource:  Datasource is connection cook which provides us the connection through the Connection pool. It's up to us to order n number of connections.

Why DataSource:
Without Datasource, we left with a driver manager. we face following problem with driver manager:
  • Take care of open & close the connection.
  • Can not create a connection pool
  • Hard to balance connection load.
Datasource provides us n number of connection, Connections are a reserve in the pool, so whenever someone required, it takes from the pool. When it close the connection is returned to the pool. We can externalize the properties of a Datasource. It help us If we want to keep different configuration depending upon a server. The Database vendor provides the implementation for Datasource. i.e Mysql, Oracle database provides the classes required build a Datasource. 

The most know DataSource in apache DBCP.

Below is the Spring configuration in for DBCP.

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/databaseName" />
<property name="username" value="databaseUserName" />
<property name="password" value="databasePassword" />
<property name="defaultAutoCommit" value="true" />
</bean>

Below is the maven dependency for DBCP:

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>

Play Framework internally use Hikaricp DataSource: 

Hikaricp is faster than DBCP: Below is the performance statistics from HikariCp GitHub page:




Below is the Spring Configuration of Hikaricp for Mysql:
  
<bean id="HikariCpConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="dataSourceClassName"                     value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"/>
    
 <property name="dataSourceProperties">
      <props>
        <prop key="serverName"> localhost </prop>
        <prop key="port">3306</prop>
        <prop key="databaseName">databasename</prop>
        <prop key="user">databaseUserName</prop>
        <prop key="password">databaseUserPasswod</prop>
      </props>
    </property>
  </bean>

Below is the maven dependency required for HikariCp:

    <dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP</artifactId>
      <version>2.5.1</version>
    </dependency>

You Can choose latest from search.maven.org.





No comments:

Post a Comment