BAEL-1314 Guide to AbstractRoutingDatasource (#2989)

* BAEL-1314 initial import.  Guide to AbstractRoutingDatasource.

* BAEL-1314 Guide to Spring AbstractRoutingDatasource

* update test name and rename test classes

* move dsrouting example to spring-boot project.  rename db create script.
This commit is contained in:
chrisoberle
2017-11-09 19:15:03 -05:00
committed by maibin
parent a38e6e295e
commit 3bb538a2f7
8 changed files with 228 additions and 0 deletions
@@ -0,0 +1,29 @@
package org.baeldung.dsrouting;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
* Database access code for datasource routing example.
*/
public class ClientDao {
private static final String SQL_GET_CLIENT_NAME = "select name from client";
private final JdbcTemplate jdbcTemplate;
public ClientDao(DataSource datasource) {
this.jdbcTemplate = new JdbcTemplate(datasource);
}
public String getClientName() {
return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper)
.get(0);
}
private static RowMapper<String> rowMapper = (rs, rowNum) -> {
return rs.getString("name");
};
}
@@ -0,0 +1,14 @@
package org.baeldung.dsrouting;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Returns thread bound client lookup key for current context.
*/
public class ClientDataSourceRouter extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return ClientDatabaseContextHolder.getClientDatabase();
}
}
@@ -0,0 +1,7 @@
package org.baeldung.dsrouting;
public enum ClientDatabase {
ACME_WIDGETS, WIDGETS_ARE_US, WIDGET_DEPOT
}
@@ -0,0 +1,26 @@
package org.baeldung.dsrouting;
import org.springframework.util.Assert;
/**
* Thread shared context to point to the datasource which should be used. This
* enables context switches between different clients.
*/
public class ClientDatabaseContextHolder {
private static final ThreadLocal<ClientDatabase> CONTEXT = new ThreadLocal<>();
public static void set(ClientDatabase clientDatabase) {
Assert.notNull(clientDatabase, "clientDatabase cannot be null");
CONTEXT.set(clientDatabase);
}
public static ClientDatabase getClientDatabase() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}
@@ -0,0 +1,21 @@
package org.baeldung.dsrouting;
/**
* Service layer code for datasource routing example. Here, the service methods are responsible
* for setting and clearing the context.
*/
public class ClientService {
private final ClientDao clientDao;
public ClientService(ClientDao clientDao) {
this.clientDao = clientDao;
}
public String getClientName(ClientDatabase clientDb) {
ClientDatabaseContextHolder.set(clientDb);
String clientName = this.clientDao.getClientName();
ClientDatabaseContextHolder.clear();
return clientName;
}
}