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 > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the knowledge of "how to use Dynamic Datasource to configure multiple data sources in SpringBoot". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Functional features:
Support data source grouping, suitable for multiple scenarios pure multi-database read and write separation of one master and multi-slave mixed mode.
Support no data source startup, support the configuration of lazy startup data source (3.3.2 +).
Support database sensitive configuration information encryption ENC ().
Support for each database to initialize the table structure schema and database database independently.
Support custom annotations and inherit DS (3.2.0 +).
Provides rapid integration of Druid,Mybatis-Plus,P6sy,Jndi.
Simplify Druid and HikariCp configuration and provide global parameter configuration. Configure once, global universal.
Provides a custom data source scheme.
Provides a solution for dynamically adding and removing data sources after the start of the project.
Provides a pure read-write separation scheme in Mybatis environment.
Provides a scenario for parsing data sources using spel dynamic parameters. Built-in spel,session,header to support customization.
Supports multi-tier data source nesting switching. (ServiceA > > ServiceB > ServiceC).
Provides solutions, considerations and examples for the integration of third-party libraries such as shiro,sharding-jdbc,quartz.
Provide a distributed transaction scheme based on seata. Attachment: native spring transactions are not supported.
Provides a local multi-data source transaction solution. Attachment: native spring transactions (3.3.1 +) are not supported.
The main purpose of this article is to achieve the separation of reading and writing, one-master and multi-slave environment.
The primary database recommends that only INSERT, UPDATE, and DELETE operations be performed.
It is recommended that only SELECT operations be performed from the database.
First, prepare the database
Main library: PiaoDB
From library 1:PiaoDB2
From library 2:PiaoDB3
2. Import POM files
Introduce dynamic-datasource-spring-boot-starter.
Com.baomidou dynamic-datasource-spring-boot-starter 3.3.2
Edit the configuration file
We have configured one master library and two slave libraries.
The "header" of all underlined _ split data sources in the configuration file is the name of the group, and data sources with the same group name are placed under a group.
The default data source name is master, which we can modify through spring.datasource.dynamic.primary.
Spring: datasource: dynamic: primary: master # sets the default data source or data source group. The default is master strict: false # sets strict mode, and the default false does not start. After startup, an exception is thrown when the specified data source is not matched, or the default data source is used if it is not started. Datasource: master: url: jdbc:mysql://localhost:3306/PiaoDB?serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.jdbc.Driver # 3.2.0 supports SPI but omits this configuration slave_1: url: jdbc:mysql://localhost:3306/PiaoDB2?serverTimezone=Asia/Shanghai username: root password : root driver-class-name: com.mysql.jdbc.Driver slave_2: url: jdbc:mysql://localhost:3306/PiaoDB3?serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.jdbc.Driver
Because we are using Ali database connection pool Druid, we need to exclude the fast configuration class of native Druid.
Other third-party integration addresses: integrated Druid
@ SpringBootApplication (exclude = DruidDataSourceAutoConfigure.class) public class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}}
Some versions of springBoot may not be excluded. You can exclude them in the following ways.
Spring: autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
In addition to configuring one master and multiple slaves, we can also configure.
# Multi-master, multi-slave, pure multi-database (remember to set primary) mixed configuration spring: datasource: dynamic: Dynamic: dynamic: datasource: master_1: mysql: master: master_2: Oracle: slave_1: slave_1: sqlserver: slave_2: slave_2: postgresql: oracle_1: slave_ 3: h3: oracle_2:
Fourth, write code
Use @ DS to switch data sources. @ DS can be annotated on methods and classes. If it exists at the same time, the method annotation takes precedence over the class comment. It is strongly recommended to comment on the service implementation or mapper interface methods.
@ DS ("xxx") specifies the use of xxx as a data source, and xxx can be either a group name or a specific library name. If it is a group name, the load balancing algorithm is used when switching. If the specified group name or library does not exist, the default data source (main library) is automatically used.
If there is no @ DS, the default data source (main library) is used
If @ DS is set but no group or library is specified, select a slave library according to the DynamicDataSourceStrategy policy. Default load balancing policy.
1. Write Controller
RestController@RequiredArgsConstructor@RequestMapping ("/ demo") public class DemoController {private final DemoService demoService; @ GetMapping ("/ add") public String add () {return demoService.add (null) + ";} @ GetMapping (" / selectGoodsInfo ") public List selectGoodsInfo () {return demoService.selectGoodsInfo ();} @ GetMapping (" / selectMasterGoodsInfo ") public List selectMasterGoodsInfo () {return demoService.selectMasterGoodsInfo ();}}
2. Write Service
Public interface DemoService {boolean add (GoodsInfo param); List selectGoodsInfo (); List selectMasterGoodsInfo ();} @ Service@RequiredArgsConstructorpublic class DemoServiceImpl implements DemoService {private final DemoMapper demoMapper; @ DS ("master") @ Override public boolean add (GoodsInfo param) {param = new GoodsInfo (); param.setGname ("RMB 1200 second kills Huawei Pad"); param.setGnum (100); return demoMapper.insertGoodsInfo (param) @ DS ("slave") @ Override public List selectGoodsInfo () {return demoMapper.selectGoodsInfo ();} @ DS ("master") @ Override public List selectMasterGoodsInfo () {return demoMapper.selectGoodsInfo ();}}
3. Write Mapper
@ Mapperpublic interface DemoMapper {boolean insertGoodsInfo (GoodsInfo param); List selectGoodsInfo ();} select * from t_goods_info insert into t_goods_info (gname, gnum, gcreatetime) values (# {gname}, # {gnum}, now ())
5. Verification results
1. Request to add an API (add data to the main database): 127.0.0.1:8086/demo/add
2. Request query main database data API: 127.0.0.1:8086/demo/selectMasterGoodsInfo
3. Request slave database data API (load balancer):
First request:
Second request:
This is the end of "how to configure multiple data sources using Dynamic Datasource in SpringBoot". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.