2

I've got the following problem. There are 2 datasources for 2 dbs: current(A) and stand by(B). If A doesn't respond, I will try to connect B.

This is how I acheave that.

  • Interceptor checks if connection is bad
  • Interceptor will swap datasource URL, if something goes wrong

Datasources are Spring beans. So I change Spring bean properties on fly. Is that ok? Look at the code:

@Autowired
@Qualifier("dataSourceMain")
private oracle.jdbc.pool.OracleDataSource dsMain;

@Autowired
@Qualifier("dataSourceStandBy")
private oracle.jdbc.pool.OracleDataSource dsStandBy;

public void swapURL() {
    try {
        String dsMainURL = dsMain.getURL();
        dsMain.setURL(dsStandBy.getURL());
        dsStandBy.setURL(dsMainURL);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

As I can see, my code works, but I don't know if it's good approach or not.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Tony
  • 3,605
  • 14
  • 52
  • 84
  • 2
    IMHO you shouldn't need this hack as this should be something provided by the JDBC driver and/or connection pool used. – M. Deinum Jun 15 '15 at 08:45
  • 1
    It the datasource is a pool swapping the URL will only work for newly created connections. The already available connection still point to the old URL until all of them are abandoned. You are using oracle so I suggest setting up proper failover and use Spring Data JDBC to setup this failover situation instead of rolling your own. – M. Deinum Jun 15 '15 at 08:51
  • Agreed - the MySQL jdbc driver for example allows you to add in a list of database URLs which are accessed in a round robin way when attempting to get a connection. I'm not sure whether Oracle provides this on its jdbc driver though. – PaulNUK Jun 15 '15 at 08:52

2 Answers2

2

Can you check if this solves your problem? Seems like a similiar question

dynamically change Spring data source

Which seems to be done in a more elegant way

Community
  • 1
  • 1
Massimo
  • 692
  • 2
  • 11
  • 29
  • If the URL is the only thing you have to switch, yeah, it seems it's ok. I'm guessing your user, passwords and configurations are the same for both the data sources, of course. – Massimo Jun 15 '15 at 08:46
2

If your data sources are pooled, then they will have a pool of connections waiting to be used or re-used. Depending on your strategy for pooling, your code could have no effect as you aren't telling the data source to evict existing pooled connections that are using the old URLs.

On a general point I suggest you use AbstractRoutingDataSource to safely swap datasources. See here

How to make safe frequent DataSource switches for AbstractRoutingDataSource?

Community
  • 1
  • 1
PaulNUK
  • 4,774
  • 2
  • 30
  • 58