问题描述
我想知道 Spring 是否提供对数据源自动故障转移的任何支持?例如,如果主数据源关闭,则连接到辅助数据源.非常感谢任何有效配置数据源自动故障转移的建议.
I would like to know if Spring offers any support for Auto Fail over of Data Sources? For example, if the primary data source is down, connect to secondary. Any suggestions to effectively configure auto fail over of Data sources is greatly appreciated.
谢谢.
推荐答案
DB 的主/DR 设置应该在 DB 级别进行管理.在代码中切换它是不对的.但是要回答您的问题可以在 Spring 中连接到 2 个数据源".是的,如果你使用 Spring-boot,你会更容易.
The Primary/DR setup for DB should be managed at DB level. Its not right to switch that in code. But to answer your question "can connect to 2 Data sources in Spring". Yes you can easier if you are using Spring-boot.
spring 的一些细节 文档.
Few details from spring documentation.
如果您使用 JDBC 或 JPA 的默认自动配置,则将其中一个标记为 @Primary(然后任何 @Autowired 注入都会选择该配置).
Mark one of them as @Primary if you are using the default auto-configuration for JDBC or JPA (then that one will be picked up by any @Autowired injections).
@Bean
@Primary
@ConfigurationProperties(prefix="datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
这篇关于Spring 多数据源配置 - 自动故障转移机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!