dawdler-db-core
Module Introduction
Database module. It provides data source management, read-write splitting, horizontal sharding routing and the transaction aspect (TransactionAspect). The transaction kernel (transaction manager / connection context / @DBTransaction annotation) has been split out into dawdler-tx-core.
1. Adding the dependency in pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-db-core</artifactId>
2. The DBTransaction annotation
For the @DBTransaction annotation and the definition of transaction propagation / isolation level / timeout / read-only, see dawdler-tx-core. This module's TransactionAspect resolves the data source for the service package and drives the transaction manager.
Both read and write connections are materialized lazily: starting a transaction does not check out a write connection; a connection is taken from the pool only on the first write-connection acquisition. For the number of connections occupied under each mode and the note that "reads inside a transaction go to the read data source and cannot see uncommitted writes", see dawdler-tx-core's "Connection occupancy model".
Note: participating propagation behaviors such as REQUIRED/NESTED are only guaranteed to join the same physical transaction within the same MappingDecision and the same shard (subfix). TransactionAspect resolves the MappingDecision from the package name of the service implementation class and the shard subfix from the @SubDatabase expression on the method. If either differs from the outer transaction frame, the inner frame is routed to another physical data source, starts an independent physical transaction through its own transaction manager and commits independently — the outer rollback cannot undo the inner committed writes, and there is no distributed transaction protection in this case. Common triggers:
- The inner and outer service implementation classes are in different packages and map to different
datasource-expressionvalues (cross-database); - The outer method does not declare @SubDatabase while the inner one does, or the inner and outer @SubDatabase expressions resolve to different subfix values (cross-shard, e.g. the outer routes to shard
_0by userId=1001 while the inner routes to shard_2by orderId=2002); - The outer method is readOnly / has no transaction frame, in which case an inner participating propagation naturally starts a new transaction.
This is consistent with Spring's behavior in multi-DataSource scenarios (a single-resource transaction manager likewise cannot span DataSources), but dawdler's routing that switches databases by package name / shard key is implicit, so developers can easily cross the boundary without realizing it. Cross-database / cross-shard writes should either be split into independent service methods that commit explicitly and orchestrate compensation themselves, or use the distributed transaction module dawdler-distributed-transaction. If the inner and outer layers really must share a transaction, ensure the inner and outer services are in the same package (or map to the same antpath) and that the shard expressions resolve to the same subfix.
3. Data source configuration
Data sources can be configured in local properties files or in the unified configuration center (local configuration files are preferred; multi-environment configuration is supported, see Multi-environment configuration).
Example (the configuration file resides on the project classpath):
userDataSource_read.properties
type: com.zaxxer.hikari.HikariDataSource
jdbcUrl: jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=utf8&useSSL=false
driverClassName: com.mysql.cj.jdbc.Driver
username: root
password:
maximumPoolSize: 20
minimumPoolSize: 2
Parameter description:
type The database connection pool class; the remaining properties are connection pool properties, whose meaning depends on the pool implementation.
4. Data source rule configuration
dawdler supports read-write splitting configuration, configured through the datasource-expression node.
<datasource-expressions>
<datasource-expression id="userDataSource"
latent-expression="write=[userDataSource_write],read=[userDataSource_read|userDataSource_read1]" />
<!--Data source expression configuration: id is the identifier, latent_expression is the read/write configuration, where write is the write connection and read the read connection. Multiple read connections can be configured separated by | and are called in round-robin order. In the example userDataSource_write, userDataSource_read and userDataSource_read1 are the ids of the data source configurations. Note that the configuration of this project is looked up first. -->
</datasource-expressions>
5. Binding services to data sources
Use decision nodes to specify which configured data source the services in a package use.
<decisions>
<decision mapping="com.anywide.demo.user.service.impl" latent-expression-id="userDataSource" />
<!-- mapping is the specified package; all service implementation classes under it use the rule configured by latent-expression-id. This takes precedence over antpath matching rules -->
<!-- antpath patterns are also supported -->
<decision mapping="com.anywide.demo.**.service.impl" latent-expression-id="userDataSource" />
<!-- mapping supports antpath; all service implementation classes under the matched packages use the rule configured by latent-expression-id, with lower priority than a directly specified non-antpath mapping -->
</decisions>
6. Horizontal sharding configuration
dawdler supports horizontal sharding, configured through the SubDatabase annotation.
Note: you must configure the data sources corresponding to the sharding rules, otherwise the corresponding databases will not be found, e.g. userDataSource_write_0, userDataSource_write_1, userDataSource_write_2 and userDataSource_read_0, userDataSource_read_1, userDataSource_read_2. If read-write splitting is not used, only userDataSource_0, userDataSource_1 and userDataSource_2 need to be configured.
Note: when sharding is combined with multiple write databases (e.g. latent-expression configured with write=[write0|write1]), the shard suffix (subfix) determines which physical shard is written, and multiple write databases in the same shard share write traffic in round-robin order (round-robin granularity is the transaction; the write connection does not switch within a single transaction), never crossing shards. Therefore multiple write databases are only valid when they are mutually consistent mirror clusters of the primary database of the same shard (e.g. write0_0/write1_0 contain the same data and write0_1/write1_1 contain the same data); otherwise the data of one shard is scattered across several physical databases.
Note: when sharding is combined with multiple read databases (e.g. latent-expression configured with read=[read0|read1]), the shard suffix (subfix) determines which physical shard is read, and multiple read databases in the same shard share read traffic in round-robin order, never crossing shards. Therefore when multiple read databases are combined with sharding, every read database must be a mirror read cluster covering all shards (e.g. read0_0/read0_1/read1_0/read1_1 must all exist) and the replicas of the same shard must be consistent (mutual replicas of the same primary); otherwise reads for one shard may hit the read database of another shard and return empty or dirty data.
/**
* @author jackson.song
* @version V1.0
* Sharding annotation, applied to service methods
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Inherited
public @interface SubDatabase {
String expression();
String configPath();
Class<? extends SubRule> subRuleType();
}
Parameter description:
expression: specifies the name of the sharding parameter. For example, if the shard field is id, the parameter name is id. Object parameters are also supported, e.g. if the shard field is the object user, the parameter name is user.id.
configPath: specifies the path of the sharding rule configuration file. The file is in yml format (the unified configuration center is supported).
subRuleType: specifies the implementation class of the sharding rule; the class must implement the SubRule interface.
dawdler provides the sharding rule implementations ConsistentHashSubRule and RemainderSubRule. You can extend it for other needs.
ConsistentHashSubRule: a sharding rule based on consistent hashing. It requires the number of virtual nodes and the node list. Each physical node is expanded into numberOfReplicas virtual nodes on the hash ring, default 160 (the Ketama convention); too few virtual nodes cause load skew and more key migration than expected when nodes are added or removed.
Example:
numberOfReplicas: 160
nodes:
- 0
- 1
- 2
RemainderSubRule: a sharding rule based on the modulo operation. It requires the divisor.
Example:
divisor: 3
The following demonstrates sharding by user id with a modulo 3.
userById.yml
divisor: 3
@Service
public class UserServiceImpl implements UserService {
@Repository
private UserMapper userMapper;
@Override
@DBTransaction(mode=MODE.readOnly)
@SubDatabase(expression = "id",configPath = "userById",subRuleType = RemainderSubRule.class)
public BaseResult<User> selectByPrimaryKey(Integer id) {
User user = userMapper.selectByPrimaryKey(id);
return new BaseResult<>(user);
}
@Override
@DBTransaction(mode=MODE.readOnly)
@SubDatabase(expression = "user.id",configPath = "userById",subRuleType = RemainderSubRule.class)
public BaseResult<User> selectByPrimaryKey(User user) {
User result = userMapper.selectByPrimaryKey(user);
return new BaseResult<>(result);
}
}