In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how springboot integrates the configuration of multiple data sources. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
Brief introduction
This paper mainly introduces two integration methods, namely, springboot+mybatis integration using subcontracting, and springboot+druid+mybatisplus integration using annotations.
I. Table structure
Create two new local databases named db1 and db2, and create a new user table with the following table structure:
SQL Code:
CREATE TABLE `user` (`id` int (11) NOT NULL AUTO_INCREMENT COMMENT 'key', `name` varchar (25) NOT NULL COMMENT 'name', `age`int (2) DEFAULT NULL COMMENT 'age', `sex`tinyint (1) NOT NULL DEFAULT'0' COMMENT 'gender: 0-male, 1-female', `addr` varchar (100) DEFAULT NULL COMMENT 'address', PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 II, multi-source integration 1. Springboot+mybatis uses subcontracting integration to mainly rely on packets
Spring-boot-starter-web
Mybatis-spring-boot-starter
Mysql-connector-java
Lombok
The pom.xml file is as follows:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.9.RELEASE com.example multipledatasource 0.0.1-SNAPSHOT multipledatasource Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web Org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0 mysql mysql-connector-java runtime org.projectlombok lombok true org.springframework.boot spring-boot- Starter-test test org.springframework.boot spring-boot-maven-plugin 1.2 application.yml profile server: port: 8080 # Startup Port spring: datasource: db1: # data Source 1 jdbc-url: jdbc:mysql://localhost:3306/db1? CharacterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver db2: # data Source 2 jdbc-url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
Matters needing attention
The parameters change when configuring datasource for each version of springboot, for example, the url attribute is used when configuring database url in the lower version, and the jdbc-url attribute is used in the higher version, please pay attention to the distinction.
1.3 establish a configuration file to connect to the data source
First profile
@ Configuration@MapperScan (basePackages = "com.example.multipledatasource.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory") public class DataSourceConfig1 {@ Primary / / indicates that this data source is the default data source, and this annotation must be added Because if it is not added, spring will not be able to distinguish which primary data source (default data source) @ Bean ("db1DataSource") @ ConfigurationProperties (prefix = "spring.datasource.db1") / / read the configuration parameter mapping in application.yml into an object public DataSource getDb1DataSource () {return DataSourceBuilder.create () .build () } @ Primary @ Bean ("db1SqlSessionFactory") public SqlSessionFactory db1SqlSessionFactory (@ Qualifier ("db1DataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dataSource) / / the xml file location of mapper must be configured, or an error will be reported: no statement (this error may also be caused by the inconsistent path between namespace and the project in mapper xml) bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath*:mapping/db1/*.xml")); return bean.getObject () } @ Primary @ Bean ("db1SqlSessionTemplate") public SqlSessionTemplate db1SqlSessionTemplate (@ Qualifier ("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate (sqlSessionFactory);}}
Second profile
@ Configuration@MapperScan (basePackages = "com.example.multipledatasource.mapper.db2", sqlSessionFactoryRef = "db2SqlSessionFactory") public class DataSourceConfig2 {@ Bean ("db2DataSource") @ ConfigurationProperties (prefix = "spring.datasource.db2") public DataSource getDb1DataSource () {return DataSourceBuilder.create (). Build ();} @ Bean ("db2SqlSessionFactory") public SqlSessionFactory db1SqlSessionFactory (@ Qualifier ("db2DataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dataSource) Bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath*:mapping/db2/*.xml")); return bean.getObject ();} @ Bean ("db2SqlSessionTemplate") public SqlSessionTemplate db1SqlSessionTemplate (@ Qualifier ("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate (sqlSessionFactory);}} 1.4 concrete implementation
The project structure is as follows:
Matters needing attention
Inject different dao layers into the service layer according to different services
If it is master-slave replication-read-write separation: for example, db1 is responsible for adding, deleting and correcting, and db2 is responsible for query. However, it should be noted that the database responsible for adding, deleting and modifying must be the main database (master).
2. Springboot+druid+mybatisplus uses annotations to integrate 2.1 mainly dependent packages
Spring-boot-starter-web
Mybatis-plus-boot-starter
Dynamic-datasource-spring-boot-starter # configuring dynamic data sources
Database connection Pool for druid-spring-boot-starter # Ali
Mysql-connector-java
Lombok
The pom.xml file is as follows:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.9.RELEASE com.example mutipledatasource2 0.0.1-SNAPSHOT mutipledatasource2 Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web com.baomidou mybatis-plus- Boot-starter 3.2.0 com.baomidou dynamic-datasource-spring-boot-starter 2.5.6 mysql mysql-connector-java runtime com.alibaba druid-spring-boot-starter 1.1.20 Org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin Local1 local1 true local2 local2 2.2 application.yml configuration file server: port: 8080spring: datasource: dynamic: primary: db1 # configure the default database datasource: Db1: # data Source 1 configuration url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver db2: # data Source 2 configuration url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 Username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver durid: initial-size: 1 max-active: 20 min-idle: 1 max-wait: 60000 autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # remove druid configuration
DruidDataSourceAutoConfigure will inject a DataSourceWrapper, which will look for url, username, password, etc., under the native spring.datasource. Configurations such as dynamic data source URL are under dynamic, so they need to be excluded, otherwise an error will be reported. There are two ways to exclude, one is the above profile exclusion, and the other can be excluded from the project startup class:
@ SpringBootApplication (exclude = DruidDataSourceAutoConfigure.class) public class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}} 2.3 add annotations @ DS to use non-default data sources
@ DS can be annotated on both methods and classes, and method annotations take precedence over class annotations.
Note on service implementation or mapper interface methods, do not comment on both service and mapper.
@ DS ("db2") public interface UserMapper extends BaseMapper {} @ Service@DS ("db2") public class ModelServiceImpl extends ServiceImpl implements IModelService {} @ Select ("SELECT * FROM user") @ DS ("db2") List selectAll (). I hope the above content can be helpful and learn more about how springboot integrates the configuration of multiple data sources. If you think the article is good, you can share it for more people to see.
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.