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 SpringBoot Multi-data Source switching

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

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to achieve SpringBoot multi-data source switching". Friends who are interested may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to achieve SpringBoot multiple data source switching".

Configuration file (YML) spring: datasource: default-db-key: voidme multi-db:-voidme: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: root url: jdbc:mysql://192.168.42.153:3306/voidme?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useSSL=false-xcdef: driver-class-name: com.mysql. Cj.jdbc.Driver username: root password: root url: jdbc:mysql://192.168.42.153:3306/xcdef?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useSSL=falsemybatis: # 1.classpath: will only look for files in your classes path. # 2. Classpathkeeper: search not only in the classes path, but also in the jar file (classes path). Mapper-locations: classpath*:/mapper/**/*Mapper.xml # mapper mapping file location type-aliases-package: com.**.entity # location of entity class configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # for console printing sql statement map-underscore-to-camel-case: true # enable entity class attribute core code that maps underlined table fields to hump format

DynamicDataSource

This class is used to get the (core) of the data source

Package com.dynamicdatadource.dynamic;import org.springframework.beans.factory.annotation.Value;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource {@ Value ("${spring.datasource.default-db-key}") private String defaultDbKey; @ Override protected Object determineCurrentLookupKey () {String currentDb = DynamicDataSourceService.currentDb (); if (currentDb = = null) {return defaultDbKey;} return currentDb;}} DynamicDataSourceService

This class is a data source switching tool, and we have done thread isolation, so we don't have to worry about the confusion of multi-threaded data sources.

Package com.dynamicdatadource.dynamic;import com.application.ApplicationContextProvider;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.jdbc.DataSourceBuilder;import javax.sql.DataSource;import java.util.HashMap;import java.util.Map;public class DynamicDataSourceService {private static final Logger log = LoggerFactory.getLogger (DynamicDataSourceService.class); private static final Map dataSources = new HashMap (); private static final ThreadLocal dbKeys = ThreadLocal.withInitial (()-> null) / * dynamically add a data source * * @ param name data source key * @ param dataSource data source object * / public static void addDataSource (String name, DataSource dataSource) {DynamicDataSource dynamicDataSource = ApplicationContextProvider.getApplicationContext () .getBean (DynamicDataSource.class); dataSources.put (name, dataSource); dynamicDataSource.setTargetDataSources (dataSources); dynamicDataSource.afterPropertiesSet () Log.info ("added data source: {}", name) } / * * @ param name data source key * @ param driverClassName driver * @ param url database connection address * @ param username database account * @ param password database password * / public static void addDataSource (String name,String driverClassName,String url,String username,String password) {DataSourceBuilder builder = DataSourceBuilder.create (); builder.driverClassName (driverClassName) Builder.username (username); builder.password (password); builder.url (url); addDataSource (name,builder.build ()); log.info ("added data sources: {}", name);} / * switch data sources * / public static void switchDb (String dbKey) {dbKeys.set (dbKey) } / * reset data source (switch to default data source) * / public static void resetDb () {dbKeys.remove ();} / * get the key * / public static String currentDb () {return dbKeys.get ();}} DynamicDataSourceConfig of the current data source

Configure the data source into springboot and initialize the Mybaitis configuration

Package com.dynamicdatadource.dynamic;import lombok.Data;import org.apache.ibatis.logging.Log;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import java.io.IOException;import java.util.HashMap;import java.util.Map @ Configuration@ConfigurationProperties (prefix = "mybatis") @ Datapublic class DynamicDataSourceConfig {private String mapperLocations; private String typeAliasesPackage; @ Datapublic class MybatisConfiguration {private String logImpl; private boolean mapUnderscoreToCamelCase;} private MybatisConfiguration configuration=new MybatisConfiguration (); / * * dynamic data source * / @ Bean public DynamicDataSource dynamicDataSource () {DynamicDataSource dataSource = new DynamicDataSource (); Map targetDataSources = new HashMap (); dataSource.setTargetDataSources (targetDataSources) Return dataSource;} / * session factory Mybaitis * / @ Bean public SqlSessionFactoryBean sqlSessionFactoryBean () throws IOException, ClassNotFoundException {org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration (); configuration.setMapUnderscoreToCamelCase (this.configuration.isMapUnderscoreToCamelCase ()); / / open hump naming configuration.setLogImpl ((Class)

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