可以在此处找到示例:https://github.com/afedulov/routing-data-source。
Spring 提供了一个 DataSource 的变体,称为 AbstractRoutingDatasource。它可以用来代替标准的 DataSource 实现,并启用一种机制来确定在运行时为每个操作使用哪个具体的 DataSource。您需要做的就是扩展它并提供抽象determineCurrentLookupKey 方法的实现。这是实现您的自定义逻辑以确定具体数据源的地方。返回的对象用作查找键。它通常是一个 String 或 en Enum,在 Spring 配置中用作限定符(后面会详细说明)。
package website.fedulov.routing.RoutingDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class RoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
}
您可能想知道 DbContextHolder 对象是什么以及它如何知道要返回哪个 DataSource 标识符?请记住,只要 TransactionsManager 请求连接,就会调用 determineCurrentLookupKey 方法。重要的是要记住每个事务都与一个单独的线程“关联”。更准确地说,TransactionsManager 将 Connection 绑定到当前线程。因此,为了将不同的事务分派到不同的目标数据源,我们必须确保每个线程都能可靠地识别要使用哪个数据源。这使得使用 ThreadLocal 变量将特定的 DataSource 绑定到 Thread 并因此绑定到 Transaction 变得很自然。它是这样完成的:
public enum DbType {
MASTER,
REPLICA1,
}
public class DbContextHolder {
private static final ThreadLocal<DbType> contextHolder = new ThreadLocal<DbType>();
public static void setDbType(DbType dbType) {
if(dbType == null){
throw new NullPointerException();
}
contextHolder.set(dbType);
}
public static DbType getDbType() {
return (DbType) contextHolder.get();
}
public static void clearDbType() {
contextHolder.remove();
}
}
如您所见,您还可以使用枚举作为键,Spring 将根据名称正确解析它。关联的 DataSource 配置和键可能如下所示:
....
<bean id="dataSource" class="website.fedulov.routing.RoutingDataSource">
<property name="targetDataSources">
<map key-type="com.sabienzia.routing.DbType">
<entry key="MASTER" value-ref="dataSourceMaster"/>
<entry key="REPLICA1" value-ref="dataSourceReplica"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceMaster"/>
</bean>
<bean id="dataSourceMaster" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="${db.master.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<bean id="dataSourceReplica" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="${db.replica.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
此时你可能会发现自己在做这样的事情:
@Service
public class BookService {
private final BookRepository bookRepository;
private final Mapper mapper;
@Inject
public BookService(BookRepository bookRepository, Mapper mapper) {
this.bookRepository = bookRepository;
this.mapper = mapper;
}
@Transactional(readOnly = true)
public Page<BookDTO> getBooks(Pageable p) {
DbContextHolder.setDbType(DbType.REPLICA1); // <----- set ThreadLocal DataSource lookup key
// all connection from here will go to REPLICA1
Page<Book> booksPage = callActionRepo.findAll(p);
List<BookDTO> pContent = CollectionMapper.map(mapper, callActionsPage.getContent(), BookDTO.class);
DbContextHolder.clearDbType(); // <----- clear ThreadLocal setting
return new PageImpl<BookDTO>(pContent, p, callActionsPage.getTotalElements());
}
...//other methods
现在我们可以控制将使用哪个 DataSource 并根据需要转发请求。看起来不错!
...或者是吗?首先,那些对神奇 DbContextHolder 的静态方法调用真的很突出。它们看起来不属于业务逻辑。他们没有。它们不仅没有传达目的,而且看起来很脆弱且容易出错(忘记清理 dbType 怎么样)。如果在 setDbType 和 cleanDbType 之间抛出异常怎么办?我们不能忽视它。我们需要绝对确定我们重置了 dbType,否则返回到 ThreadPool 的线程可能处于“损坏”状态,试图在下一次调用中写入副本。所以我们需要这个:
@Transactional(readOnly = true)
public Page<BookDTO> getBooks(Pageable p) {
try{
DbContextHolder.setDbType(DbType.REPLICA1); // <----- set ThreadLocal DataSource lookup key
// all connection from here will go to REPLICA1
Page<Book> booksPage = callActionRepo.findAll(p);
List<BookDTO> pContent = CollectionMapper.map(mapper, callActionsPage.getContent(), BookDTO.class);
DbContextHolder.clearDbType(); // <----- clear ThreadLocal setting
} catch (Exception e){
throw new RuntimeException(e);
} finally {
DbContextHolder.clearDbType(); // <----- make sure ThreadLocal setting is cleared
}
return new PageImpl<BookDTO>(pContent, p, callActionsPage.getTotalElements());
}
哎呀>_<!这绝对不像我想放入每个只读方法中的东西。我们能做得更好吗?当然!这种“在方法的开头做某事,然后在结尾做某事”的模式应该敲响了警钟。救援方面!
不幸的是,这篇文章已经太长了,无法涵盖自定义方面的主题。您可以使用此link 跟进使用方面的详细信息。