In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to achieve dynamic switching of multiple data sources in mybatis in springboot", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article "how to achieve dynamic switching of multiple data sources in mybatis in springboot".
Introduction of multi-data source configuration
The introduction of mybatis and mysql in springboot is not mentioned here, but what you don't know can be found in the introduction of mysql and mybatis in springboot.
The data source is configured as follows:
Datasource: master: type: com.alibaba.druid.pool.DruidDataSource jdbc-url: jdbc:mysql://127.0.0.1:3306/sbac_master?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true username: root password: 1234 driver-class-name: com.mysql.cj.jdbc.Driver log: type: com.alibaba.druid.pool.DruidDataSource jdbc-url: jdbc:mysql://127.0.0.1:3306/sbac_log?autoReconnect=true& UseUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true username: root password: 1234 driver-class-name: com.mysql.cj.jdbc.Driver
The configuration of mybatis is introduced as follows:
Mybatis: config-location: classpath:mybatis-config.xml mapper-locations: classpath:com/lazycece/sbac/mysql/data/dao/*/mapper/*.xml
What has been used here is the automatic configuration feature of springboot to configure mybatis information, only manually specifying the data source. As shown below, two data sources, master and log, are specified and master is set as the default data source:
@ Configurationpublic class MultiDataSource {public static final String MASTER_DATA_SOURCE = "masterDataSource"; public static final String LOG_DATA_SOURCE = "logDataSource"; @ Bean (name = MultiDataSource.MASTER_DATA_SOURCE) @ ConfigurationProperties (prefix = "datasource.master") public DataSource masterDataSource () {return DataSourceBuilder.create () .build () } @ Bean (name = MultiDataSource.LOG_DATA_SOURCE) @ ConfigurationProperties (prefix = "datasource.log") public DataSource logDataSource () {return DataSourceBuilder.create () .build ();} @ Primary @ Bean (name = "dynamicDataSource") public DynamicDataSource dataSource () {DynamicDataSource dynamicDataSource = new DynamicDataSource (); dynamicDataSource.setDefaultTargetDataSource (masterDataSource ()); Map dataSourceMap = new HashMap (4) DataSourceMap.put (MASTER_DATA_SOURCE, masterDataSource ()); dataSourceMap.put (LOG_DATA_SOURCE, logDataSource ()); dynamicDataSource.setTargetDataSources (dataSourceMap); return dynamicDataSource;}} dynamic data source routing implementation
After introducing the configuration information, it is time to talk about how to achieve multiple data source switching. We implement the dynamic routing of the data source by implementing the determineCurrentLookupKey method of the AbstractRoutingDataSource class, and set the ThreadLocal thread protection variable to store the data source key to ensure that the threads are not affected.
Package com.lazycece.sbac.mysql.multi.config;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;/** * @ author lazycece * / public class DynamicDataSource extends AbstractRoutingDataSource {private static final Logger LOGGER = LoggerFactory.getLogger (DynamicDataSource.class); private static final ThreadLocal DATA_SOURCE_KEY = new ThreadLocal (); static void changeDataSource (String dataSourceKey) {DATA_SOURCE_KEY.set (dataSourceKey) } static void clearDataSource () {DATA_SOURCE_KEY.remove ();} @ Override protected Object determineCurrentLookupKey () {String key = DATA_SOURCE_KEY.get (); LOGGER.info ("current data-source is {}", key); return key;}}
Then, the dynamic switching of the data source is realized by using AOP. The annotations and sections are defined as follows:
@ Documented@Inherited@Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.METHOD, ElementType.TYPE}) public @ interface DataSource {String value ();} @ Component@Aspectpublic class DataSourceConfig {@ Before ("@ annotation (dataSource)") public void beforeSwitchDataSource (DataSource dataSource) {DynamicDataSource.changeDataSource (dataSource.value ());} @ After ("@ annotation (DataSource)") public void afterSwitchDataSource () {DynamicDataSource.clearDataSource ();}} dynamic data source switching
For dynamic data source switching, you only need to use the @ DataSource annotation in the business to indicate the data source you need to use, as shown below (only key codes are posted here):
@ Servicepublic class DynamicDataSourceServiceImpl implements DynamicDataSourceService {@ Resource private UserDao userDao; @ Resource private SystemLogDao systemLogDao; @ Override @ DataSource (value = MultiDataSource.MASTER_DATA_SOURCE) public void addUserInfo (User user) {userDao.insert (user);} @ Override @ DataSource (value = MultiDataSource.MASTER_DATA_SOURCE) public User getUserInfo (String username) {return userDao.findByUsername (username) @ Override @ DataSource (value = MultiDataSource.LOG_DATA_SOURCE) public void addSystemLog (SystemLog systemLog) {systemLogDao.insert (systemLog);} @ Override @ DataSource (value = MultiDataSource.LOG_DATA_SOURCE) public List getSystemLogInfo (Date beginTime, Date endTime) {return systemLogDao.findByCreateTime (beginTime, endTime) }} the above is the content of this article on "how to achieve dynamic switching of multiple data sources in mybatis in springboot". I believe everyone has a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to learn more about related knowledge, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.