java – 在Spring Boot中使用两个数据源
发布时间:2020-12-14 05:58:28 所属栏目:Java 来源:网络整理
导读:我在我的项目中使用 Spring Boot 1.3.3和一个数据库,现在我想使用两个具有相同模式但连接不同的数据库. 我想使用相同的存储库,实体并找到方法告诉spring我想要使用哪个数据源,具体取决于具体情况. 解决方法 如果有人有这个问题,我找到了解决方案: 首先,您的
我在我的项目中使用
Spring Boot 1.3.3和一个数据库,现在我想使用两个具有相同模式但连接不同的数据库.
我想使用相同的存储库,实体并找到方法告诉spring我想要使用哪个数据源,具体取决于具体情况. 解决方法
如果有人有这个问题,我找到了解决方案:
首先,您的application.properties应如下所示: datasource: primary: url: jdbc:mysql://localhost:3306/primary_db username: your_username password: your_password driver-class-name: com.mysql.jdbc.Driver secondary: url: jdbc:mysql://localhost:3306/secondary_db username: your_username password: your_password driver-class-name: com.mysql.jdbc.Driver 之后,您必须使用数据库创建枚举: public enum Database { PRIMARY,SECONDARY } 然后,您创建一个ThreadLocal: public class DatabaseThreadContext { private static final ThreadLocal<Database> current = new ThreadLocal<>(); public static void setCurrentDatabase(Database database) { current.set(database); } public static Object getCurrentDatabase() { return current.get(); } } 这就是魔术,你必须使用在2007年春季2中实现的AbstractRoutingDataSource: public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DatabaseThreadContext.getCurrentDatabase(); } } 最后在Spring Boot App中注入一个配置: @Configuration public class DatabaseRouter { @Bean @ConfigurationProperties(prefix="datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix="datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public DataSource dataSource() { Map<Object,Object> targetDatasources = new HashMap<Object,Object>(){{ put(Database.SECONDARY,secondaryDataSource()); put(Database.PRIMARY,primaryDataSource()); }}; RoutingDataSource routingDataSource = new RoutingDataSource(); routingDataSource.setDefaultTargetDataSource(primaryDataSource()); routingDataSource.setTargetDataSources(targetDatasources); routingDataSource.afterPropertiesSet(); return routingDataSource; } } 在每个请求中,如果要在数据库之间进行更改,只需使用此函数:DatabaseThreadContext.setCurrentDatabase(Database.PRIMARY);. 此外,您可以同时拥有两个以上的数据库. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |