Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize dynamic switching of data sources by Springboot

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to realize Springboot dynamic switching data source". In daily operation, I believe that many people have doubts about how to realize Springboot dynamic switching data source. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to realize Springboot dynamic switching data source". Next, please follow the editor to study!

Preface

Switching between multiple data sources can be achieved with only one sentence of code in the springboot project:

/ / switch sqlserver data source: DataSourceContextHolder.setDataBaseType (DataSourceEnum.SQLSERVER_DATASOURCE);. / / switch mysql data source DataSourceContextHolder.setDataBaseType (DataSourceEnum.MYSQL_DATASOURCE). Specific implementation:

This example is based on the springboot2.5+ version.

1. Configure the data source:

Configure connection information for multiple data sources in the configuration file, distinguished by different prefixes:

# sqlserver data source 1: prefix: spring.datasource.sqlserverspring.datasource.sqlserver.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriverspring.datasource.sqlserver.jdbc-url=jdbc:sqlserver://localhost:1433 DatabaseName=testspring.datasource.sqlserver.username=saspring.datasource.sqlserver.password=sa# mysql data source 1: prefix: spring.datasource.mysqlspring.datasource.mysql.driver-class-name=com.mysql.jdbc.Driverspring.datasource.mysql.jdbc-url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=truespring.datasource.mysql.username=rootspring.datasource.mysql.password=root# sqlLite data source 1: prefix: spring.datasource.sqlitespring.datasource.sqlite.driver-class-name=org.sqlite.JDBCspring.datasource.sqlite. Jdbc-url=jdbc:sqlite:D://sqllite//test.dbspring.datasource.sqlite.username=spring.datasource.sqlite.password=# sqlserver data source 2: prefix: spring.datasource.sqlserver2spring.datasource.sqlserver2.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriverspring.datasource.sqlserver2.jdbc-url=jdbc:sqlserver://localhost DatabaseName=test1spring.datasource.sqlserver2.username=saspring.datasource.sqlserver2.password=sa# configuration database connection pool information spring.datasource.hikari.maximum-pool-size=32spring.datasource.hikari.minimum-idle=16

two。 Create a new enumeration class DataSourceEnum, and set several enumeration classes corresponding to several data sources.

Public enum DataSourceEnum {MYSQL_DATASOURCE, SQLSERVER_DATASOURCE, SQLSERVER2_DATASOURCE, SQLLITE_DATASOURCE}

3. Create a new database switching tool class DataSourceContextHolder, which stores the current data source enumeration class through variables of ThreadLocal type, while ensuring thread safety.

Public class DataSourceContextHolder {/ * ensure thread safety through ThreadLocal * / private static final ThreadLocal contextHolder = new ThreadLocal (); / * set data source variable * @ param dataSourceEnum data source variable * / public static void setDataBaseType (DataSourceEnum dataSourceEnum) {System.out.println ("modify data source to:" + dataSourceEnum); contextHolder.set (dataSourceEnum) } / * get data source variable * @ return data source variable * / public static DataSourceEnum getDataBaseType () {DataSourceEnum dataSourceEnum = contextHolder.get () = = null? DataSourceEnum.MYSQL_DATASOURCE: contextHolder.get (); System.out.println ("current data source type is:" + dataSourceEnum); return dataSourceEnum;} / * clear data type * / public static void clearDataBaseType () {contextHolder.remove ();}

4. The new DynamicDataSource class inherits the AbstractRoutingDataSource class and implements the determineCurrentLookupKey method, which is the method that specifies the current default data source.

Public class DynamicDataSource extends AbstractRoutingDataSource {@ Override protected Object determineCurrentLookupKey () {return DataSourceContextHolder.getDataBaseType ();}}

This class doesn't seem to have much content, but inheriting the AbstractRoutingDataSource class is the key to dynamically switching data sources.

5. The new DataSourceConfig class is used to create instances of bean, including DataSource instances of each data source, DynamicDataSource instances, and JdbcTemplate instances of SqlSessionFactory or Spring related to Mybatis.

@ Configurationpublic class DataSourceConfig {@ Bean (name = "sqlserverDataSource") @ ConfigurationProperties (prefix = "spring.datasource.sqlserver") public DataSource getDateSource1 () {return DataSourceBuilder.create () .build ();} @ Bean (name = "sqlserver2DataSource") @ ConfigurationProperties (prefix = "spring.datasource.sqlserver2") public DataSource getDateSource11 () {return DataSourceBuilder.create () .build () } @ Bean (name = "mysqlDataSource") @ ConfigurationProperties (prefix = "spring.datasource.mysql") public DataSource getDateSource2 () {return DataSourceBuilder.create () .build ();} @ Bean (name = "sqlLiteDataSource") @ ConfigurationProperties (prefix = "spring.datasource.sqlite") public DataSource getDateSource3 () {return DataSourceBuilder.create () .build () } @ Bean (name = "dynamicDataSource") public DynamicDataSource DataSource (@ Qualifier ("sqlserverDataSource") DataSource sqlserverDataSource, @ Qualifier ("sqlserver2DataSource") DataSource sqlserver2DataSource, @ Qualifier ("mysqlDataSource") DataSource mysqlDataSource @ Qualifier ("sqlLiteDataSource") DataSource sqlLiteDataSource) {/ / configure multiple data sources Map targetDataSource = new HashMap () TargetDataSource.put (DataSourceEnum.SQLSERVER_DATASOURCE, sqlserverDataSource); targetDataSource.put (DataSourceEnum.MYSQL_DATASOURCE, mysqlDataSource); targetDataSource.put (DataSourceEnum.SQLLITE_DATASOURCE, sqlLiteDataSource); targetDataSource.put (DataSourceEnum.SQLSERVER2_DATASOURCE, sqlserver2DataSource); DynamicDataSource dataSource = new DynamicDataSource (); / / multiple data source dataSource.setTargetDataSources (targetDataSource); / / default data source dataSource.setDefaultTargetDataSource (sqlserverDataSource); return dataSource } @ Bean (name = "SqlSessionFactory") public SqlSessionFactory test1SqlSessionFactory (@ Qualifier ("dynamicDataSource") DataSource dynamicDataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dynamicDataSource); return bean.getObject ();} @ Bean (name = "JdbcTemplate") public JdbcTemplate test1JdbcTemplate (@ Qualifier ("dynamicDataSource") DataSource dynamicDataSource) {return new JdbcTemplate (dynamicDataSource);}}

This gives all the bean we need to switch database locks to the spring container, directly through DataSourceContextHolder.setDataBaseType (DataSourceEnum dataSourceEnum); this method specifies the enumeration class corresponding to the data source.

Principle analysis:

In fact, when we create a new database connection, we also obtain the connection through DataSource, and the AbstractRoutingDataSource here also obtains the connection through the getConnection method in DataSource.

Two Map are maintained in this class to store database connection information:

@ Nullableprivate Map targetDataSources; @ Nullableprivate Object defaultTargetDataSource;private boolean lenientFallback = true;private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup (); @ Nullableprivate Map resolvedDataSources;@Nullableprivate DataSource resolvedDefaultDataSource

The above attributes are described below:

The first targetDataSources is a Map object. When we create a DynamicDataSource instance in step 5 above, we put the DataSource class of multiple data sources into this Map. Here Key is the enumerated class, and values is the DataSource class.

The second defaultTargetDataSource is the default data source, which is the only overridden method in DynamicDataSource to assign values to this object.

The third lenientFallback is an identity, which is whether to use the default data source when the data source does not exist. The default is true. If it is set to false, if the specified data source cannot be found, it will return null.

The fourth dataSourceLookup is used to parse the specified data source object as a DataSource instance. The default is the JndiDataSourceLookup instance, which is inherited from the DataSourceLookup interface.

The fifth resolvedDataSources is also a Map object, which is the DataSource object that holds the parsed data source.

The sixth resolvedDefaultDataSource is the default parsed DataSource data source object where the getConnection method takes the DataSource instance and gets the connection from this variable.

At this point, the study on "how to dynamically switch data sources in Springboot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report