1. Brief description
In Java development, many scenarios require access to multiple databases, such as multi-tenant systems or read-write separation architectures. In order to manage these scenarios flexibly and efficiently, Dynamic Data Source Switching (Dynamic-DataSource) technology came into being.
This article introduces how to integrate Dynamic-DataSource in Spring Boot project and implement dynamic switching functions, and finally demonstrate practical applications through examples.
2. What is Dynamic-DataSource?
Dynamic-DataSource is a technology that can dynamically switch data sources according to business needs. Common usage scenarios include:
- Read-write separation: read requests are routed to read-only data sources, and write requests are routed to the main data sources.
- Multi-tenant system: Dynamically select databases based on tenant ID.
- Library and table: Route to the corresponding data source according to the shard key.
Through dynamic data source switching, you can avoid manually managing multiple DataSources and improve development efficiency. Dynamic-DataSource is an implementation of AbstractRoutingDataSource based on Spring. The core idea is:
- Define multiple data sources (such as master and slave).
- Use ThreadLocal to save the currently used data source identity.
- Dynamically select data sources based on context.
3. Integrate Dynamic-DataSource
dynamic-datasource-spring-boot-starter is a springboot-based launcher that integrates multiple data sources quickly.
- Supports data source grouping, suitable for multiple scenarios Pure multi-library Read-write separation One master Multi-slave hybrid mode.
- Supports database sensitive configuration information Encryption (customizable) ENC().
- Supports independent initialization of table structure schema and database database for each database.
- Supports startup without data source and supports lazy loading of data sources (creating connections when needed).
- Provides and simplifies the rapid integration of Druid, HikariCp, BeeCp, Dbcp2.
Provides integration solutions for Mybatis-Plus, Quartz, ShardingJdbc, P6sy, Jndi and other components.
3.1 Maven reference
Before using Dynamic-DataSource, it needs to be added. Here are the Maven dependencies for Dynamic-DataSource:
<!-- mybatis-plus --> <dependency> <groupId></groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <dependency> <groupId></groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>4.3.0</version> </dependency>
3.2 Configuring Multiple Data Sources
Configure multiple data sources in the file:
server: port: 9001 spring: datasource: dynamic: primary: master strict: false datasource: master: url: jdbc:mysql://192.168.25.181:3306/shop_admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: slave_1: url: jdbc:mysql://192.168.25.181:3306/slave_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name:
3.3 Writing dynamic data source switching logic
Dynamic-DataSource Starter provides annotation and AOP support to simplify data source switching logic. Add @DS annotation where you need to dynamically switch data sources:
import ; import ; import ; import ; import ; import ; @Service public class UserService extends ServiceImpl<SysUserMapper, SysUserEntity> { @Resource private SysUserMapper sysUserMapper; @DS("master") public void insertUser(SysUserEntity user) { (user); } @DS("slave_1") public SysUserEntity getUserById(Long id){ return (id); } }
SysUserMapper:
import ; import ; public interface SysUserMapper extends BaseMapper<SysUserEntity> { }
SysUserEntity:
package ; import ; import ; import ; import ; import ; import ; @Data @TableName("sys_user") public class SysUserEntity implements Serializable { private static final long serialVersionUID = 1L; /** * User ID */ @TableId(value = "user_id") private Long userId; /** * username */ @TableField("username") private String username; /** * password */ @TableField("password") private String password; /** * Salt */ @TableField("salt") private String salt; /** * Mail */ @TableField("email") private String email; /** * Phone number */ @TableField("mobile") private String mobile; /** * Status 0: Disable 1: Normal */ @TableField("status") private Integer status; /** * Creator ID */ @TableField("create_user_id") private Long createUserId; /** * Creation time */ @TableField("create_time") private Date createTime; }
Add test cases in Controller control layer:
import ; import ; import ; import ; import ; import ; import ; import ; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/getUserById") public SysUserEntity getUserById(@RequestParam Long id) { return (id); } @GetMapping("/insert") public SysUserEntity insert(@RequestParam Long id) { SysUserEntity sysUserEntity = new SysUserEntity(); ("admin@"); ("123456"); ("adminMaster"); (new Date()); (sysUserEntity); return sysUserEntity; } }
Add mapper mapping path in the startup class:
@SpringBootApplication @MapperScan("") public class ShopEurekaApplication { public static void main(String[] args) { (, args); } }
4. Summary
Dynamic-DataSource provides an efficient and concise multi-data source management method, which is very suitable for complex scenarios such as multi-tenant systems and read and write separation. This article shows how to integrate and use Dynamic-DataSource through configuration and practical cases to help developers quickly implement dynamic data source switching functions.
Through dynamic data source technology, the flexibility and scalability of the system can be significantly improved. Dynamic-DataSource will be a powerful tool if your project involves the management of multiple databases.
The above is the detailed content of the practical guide for Java to implement dynamic data source switching. For more information about Java dynamic data source switching, please pay attention to my other related articles!