How do I configure c3p0 for a grails 2.X application with multiple datasources?

情到浓时终转凉″ 提交于 2019-12-01 08:24:33
Yves Martin

Here is the corresponding documentation. This blog provides a code example how to delay DataSource creation in Grails... and it is possible to use C3P0 in such a code.

As Grails comes with DBCP by default, I do not find relevant to add code to setup C3P0 pooling (and later replace the default transaction manager...) when it is possible to delegate DataSource and pooling configuration to the underlying container, for instance Tomcat or JBoss. So I recommend that way of doing and here is an example how to setup C3P0 for a Tomcat DataSource, just add its jar in lib directory.

Now, when configuring multiple DataSources, you should take care to the section about the lacking two-phase-commit support in Grails.

If you expect operations done on connections from your two DataSource to be included in a single transaction (commit on both if success, rollback on both if failure), you will have to use a XA transaction manager.

In that case, I recommend you to deploy in JBoss and configure DataSources and pooling in JBoss itself, the JDBC driver must be installed in JBoss libraries.

You will get benefits of the included XA transaction manager. On Grails side, the DataSource is configured to query a JNDI resource-ref entry declared in WEB-INF/web.xml and WEB-INF/jboss-web.xml files of your WAR file.

dataSource {
    jndiName = "java:comp/env/myDataSource"
}

datasource.groovy / External configuration file

   dataSource {
    pooled = true
    dbCreate = "create-drop"
    url = "jdbc:mysql://<ip address>/test1"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "test"
    password = "test123" 
   }

   dataSource_A {
      pooled = true
      dbCreate = "create-drop"
      url = "jdbc:mysql://<ip address>/test2"
      driverClassName = "com.mysql.jdbc.Driver"
      username = "test"
      password = "test123" 
  }

resources.groovy

 dataSource(ComboPooledDataSource) { bean ->
    idleConnectionTestPeriod = 1 * 60 * 60
    testConnectionOnCheckin = true
    bean.destroyMethod = 'close'
    user = grailsApplication.config.dataSource.username
    password = grailsApplication.config.dataSource.password
    driverClass = grailsApplication.config.dataSource.driverClassName
    jdbcUrl = grailsApplication.config.dataSource.url
}


dataSource_A(ComboPooledDataSource) { bean ->

    idleConnectionTestPeriod = 1 * 60 * 60
    testConnectionOnCheckin = true
    bean.destroyMethod = 'close'
    user = grailsApplication.config.dataSource_A.username
    password = grailsApplication.config.dataSource_A.password
    driverClass = grailsApplication.config.dataSource_A.driverClassName
    jdbcUrl = grailsApplication.config.dataSource_A.url

}

c3p0.jar in the project's lib folder.

These are the only changes that are required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!