How to set up connection pooling in an OSGi bundle?
After many years of developing web applications for the Websphere platform, I have recently been looking at OSGi especially in connection with the RAP (RichAjayPlatform) project.
In the past, I have been able to access connection pools defined in the EAR using JNDI lookups.
How do you create connection pools and access them in an OSGi environment? I have created a DB2 bundle containing the jdbc drivers but I'm not sure how to create the pool. Previously, this was a configuration in the EAR and Websphere handle开发者_如何转开发d it.
Are there any examples, tutorials out there?
There is nothing "built in" to OSGi to do connection pooling of course, but it is very simple to implement.
First, your client code should access the database via a service, probably of type javax.sql.DataSource
(I recommend using Declarative Services to inject this into your component).
Then you need a bundle that will create a connection pool using a specific driver and register the DataSource
service(s). I would also build this using Declarative Services, wrapping the Apache Commons DBCP library.
You'll have to register the connection pool manager as an OSGi service. If you add in the Apache Aries JNDI bundle, all of your services will also be exposed via JNDI. Some connection pool managers don't play well in OSGi because of classloader issues but having the driver embedded in the same bundle that configures the connection pool can often get around those.
I've only set this up using JPA + JNDI but the steps I would take with creating and exporting a connection pool would be something like this:
- Manually create a connection pool (c3p0, dbcp, etc) in the bundle activator.
- Register the connection pool as a service with the bundle context.
- In the services that need a connection, get a reference to the connection pool (I use declarative services) and get a connection from the pool.
精彩评论