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

Example Analysis of springboot configuration Multi-data Source Framework

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shows you the springboot configuration multiple data source framework (dynamic-datasource-spring-boot-starter), the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.

Introduction to the framework

Dynamic-datasource-spring-boot-starter is a springboot-based initiator for fast integration of multiple data sources.

Frame description

This framework only does the core thing of switching data sources, and does not limit your specific operations. Switching data sources can do any CRUD.

The header of all underlined _ split data sources in the configuration file is the name of the group, and the data sources with the same group name will be placed under a group.

The switching data source can be a group name or a specific data source name. When switching the group name, the load balancing algorithm is used to switch.

The default data source name is master, which you can modify through spring.datasource.dynamic.primary

Comments on methods take precedence over comments on classes

DS supports inheriting DS on abstract classes, but does not support DS on inheritance interfaces.

Data preparation for integration with springboot

Springboot version: 2.0.6.RELEASE

Mysql version: 5.7

Create a database test1,test2 respectively. The database tables are all goods, and the data are different.

CREATE TABLE `goods` (`goodsId` bigint (11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `goodsName` varchar) NOT NULL DEFAULT' 'COMMENT' name', `goods` varchar''COMMENT' title', `price` decimal (15Power2) NOT NULL DEFAULT '0.00' COMMENT' price', `stock`int (11) NOT NULL DEFAULT'0' COMMENT 'stock', PRIMARY KEY (`goodsId`) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT=' Commodity Table'

The test1 database data is as follows

The test2 database data is as follows

Introduce dependency

As for other dependencies, I will not repeat them.

Com.baomidou dynamic-datasource-spring-boot-starter 3.3.2springboot profile

For details of the configuration file, please refer to the official documentation.

Server.port=8080# sets test1 primary data source spring.datasource.dynamic.primary=master#test1 main data source configures spring.datasource.dynamic.datasource.master.url=jdbc:mysql://127.0.0.1:3306/test1?characterEncoding=utf8&useSSL=false&autoReconnect=true&serverTimezone=UTCspring.datasource.dynamic.datasource.master.username=rootspring.datasource.dynamic.datasource.master.password=123456spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.jdbc.Driverspring.datasource.dynamic.datasource.master.type=com.alibaba.druid.pool.DruidDataSource # druid connection Pool configuration spring.datasource.dynamic.datasource.master.druid.initial-size=5spring.datasource.dynamic.datasource.master.druid.max-active=20spring.datasource.dynamic.datasource.master.druid.min-idle=5spring.datasource.dynamic.datasource.master.druid.max-wait=60000#test2 configure spring.datasource.dynamic.datasource.slave.url=jdbc:mysql://127.0.0.1:3306/test2?characterEncoding=utf8&useSSL=false&autoReconnect=true&serverTimezone=UTCspring.datasource.dynamic.datasource.slave.username=rootspring.datasource from the data source. Dynamic.datasource.slave.password=123456spring.datasource.dynamic.datasource.slave.driver-class-name=com.mysql.jdbc.Driverspring.datasource.dynamic.datasource.slave.type=com.alibaba.druid.pool.DruidDataSource#druid connection pool configuration spring.datasource.dynamic.datasource.slave.druid.initial-size=5spring.datasource.dynamic.datasource.slave.druid.max-active=20spring.datasource.dynamic.datasource.slave.druid.min-idle=5spring.datasource.dynamic.datasource.slave.druid.max-wait=60000#mybatis configuration mybatis.mapper-locations=classpath:org / example/mapper/*.xmlmybatis.configuration.cache-enabled=true# enable hump naming mybatis.configuration.map-underscore-to-camel-case=true# print SQLmybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

Startup class

The DruidDataSourceAutoConfigure class needs to be excluded, otherwise the startup will report that the configured url will not be found.

@ SpringBootApplication (exclude = DruidDataSourceAutoConfigure.class) @ Slf4jpublic class App {public static void main (String [] args) {SpringApplication.run (App.class, args); log.info ("- springboot running-");}}

Entity class

@ Data@ApiModelpublic class Goods implements Serializable {@ ApiModelProperty (value = "id") private Long goodsid; @ ApiModelProperty (value = "Commodity name") @ NotBlank (message = "Commodity name cannot be empty") private String goodsname; @ ApiModelProperty (value = "Commodity description") @ NotBlank (message = "Commodity description cannot be empty") private String subject @ ApiModelProperty (value = "Commodity prices") @ NotNull (message = "Commodity prices cannot be empty") private BigDecimal price; @ ApiModelProperty (value = "Commodity inventory", example = "0") @ NotNull (message = "Commodity inventory cannot be empty") private Integer stock;}

Service layer

As for the dao layer, the mybatis-generator plug-in is used to automatically generate

@ Servicepublic class GoodServiceImpl implements GoodService {@ Autowired private GoodsMapper goodsMapper; @ Override public Goods selectOneGoods (Long goodsid) {return goodsMapper.selectByPrimaryKey (goodsid);} @ Override public int addGoods (Goods goods) {return goodsMapper.insertSelective (goods);}}

Controller layer

@ Controller@RequestMapping (path = "/ goods") @ Api (tags = "Commodity Management related Interface") @ Slf4jpublic class GoodsController {@ Autowired private GoodService goodService @ GetMapping (path = "/ selectOne") @ ResponseBody @ ApiOperation (value = "query Commodity Interface") @ ApiImplicitParam (name = "id", value = "Commodity id", required = true) public ResultMap selectOne (@ RequestParam (name = "id", defaultValue = "3") Long goodsid) {Goods goods = goodService.selectOneGoods (goodsid); log.info ("queried Commodity data:" + goods.toString ()) If (StringUtils.isEmpty (goods)) {return new ResultMap () .fail () .message ("query failed, no data you want");} return new ResultMap () .success () .message ("query success") .data (goods) } @ PostMapping (path = "/ addGoods") @ ResponseBody @ ApiOperation (value = "Interface for adding goods") public ResultMap addGoods (@ Valid Goods goods, @ NotNull BindingResult bindingResult) {if (bindingResult.hasErrors ()) {String defaultMessage = Objects.requireNonNull (bindingResult.getFieldError ()). GetDefaultMessage (); return new ResultMap (). Fail (). Message (defaultMessage);} int I = goodService.addGoods (goods) If (I > 0) {return new ResultMap () .success () .message ("added successfully");} return new ResultMap () .fail () .message ("add failed");}}

There is no annotation @ DS on the test service layer method.

Test the first interface using postman

Test the second interface using postman

The tests of the above two interfaces show that they all operate the master data source test1 by default, which proves that the master data source test1 configured in our configuration file is correctly configured and has taken effect.

Add @ DS to the service layer method and test it again.

@ Servicepublic class GoodServiceImpl implements GoodService {@ Autowired private GoodsMapper goodsMapper; @ DS (value = "slave") / / switch the data source and specify the database name @ Override public Goods selectOneGoods (Long goodsid) {return goodsMapper.selectByPrimaryKey (goodsid);} @ Override public int addGoods (Goods goods) {return goodsMapper.insertSelective (goods);}}

Test the first interface using postman

At this point, the @ DS annotation has taken effect, and the dynamic switching of the data source has occurred.

Test the second interface using postman

Since there is no @ DS annotation on the interface, no data source switching occurs, and the test1 default data source is still operated.

@ DS Annotation

The annotation result does not have @ DS default data source @ DS ("dsName") dsName can be a group name or a specific library name

@ DS can be annotated on a method or class, and there is a proximity principle that comments on methods take precedence over comments on classes.

@ DS officially recommends using methods in the service layer

The above is a sample analysis of the springboot configuration multiple data Source Framework (dynamic-datasource-spring-boot-starter). Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to 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.

Share To

Development

Wechat

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

12
Report