TomEE/OpenEJB and failover of datasources


Defining a DataSource in TomEE is quite easy, the most common way to do so is to define a Resource block in tomee.xml:

<Resource id="jdbc/ds" type="DataSource">
   JdbcUrl = jdbc:mysql://datasourcehost:3306/tomee
   ...
</Resource>

When you have multiple hosts you often use datasourcehost (in the previous sample) as a service host (or IP) to delegate then to real hosts. But sometimes it is not possible or too complicated. For such needs TomEE now provides a basic failover feature.

The idea is to reuse dynamic datasource feature of tomee to handle it.

First define your datasources as usual:

<Resource id="jdbc/main" type="DataSource">
   JdbcUrl = jdbc:mysql://main:3306/ds
   ...
</Resource>
<Resource id="jdbc/fallback" type="DataSource">
   JdbcUrl = jdbc:mysql://fallback:3306/ds
   ...
</Resource>

Then define a router which will select between datasources the one to use:

<Resource id="failover-router" class-name="org.apache.openejb.resource.jdbc.router.FailOverRouter">
   datasourceNames = jdbc/main,jdbc/fallback
</Resource>

And finally define the routed datasource which will use the router to switch between main/fallback datasources:

<Resource id="jdbc/ds" type="DataSource" provider="RoutedDataSource">
   router = failover-router
</Resource>

Now all is in place to get failover between main and fallback datasources.

You can go a bit further adding the strategy parameter to the router. It can take as values (ATM):

  • default: the first is used while possible and others datasources are just backup, this is typically the failover case
  • random: any datasource of the list is used
  • reverse: between two call to a method the list is reversed
  • round-robin[%N]: round robin between datasources, you can specify how many step you browse between two calls using N (default is 1)

Finally you use the routed datasource (jdbc/ds) as your datasource (either directly through @Resource(name = “jdbc/ds”) or through jpa).

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s