当前位置:网站首页>Shardingsphere source code analysis
Shardingsphere source code analysis
2022-07-05 23:55:00 【Listen to the wind 0220】
Watch this article and browse it :https://blog.csdn.net/qq_36851469/article/details/125449241
1、SpringBootConfiguration
@Configuration
@ComponentScan("org.apache.shardingsphere.spring.boot.converter")
// EnableConfigurationProperties Are used to load configuration information
@EnableConfigurationProperties({
SpringBootShardingRuleConfigurationProperties.class,
SpringBootMasterSlaveRuleConfigurationProperties.class, SpringBootEncryptRuleConfigurationProperties.class,
SpringBootPropertiesConfigurationProperties.class, SpringBootShadowRuleConfigurationProperties.class})
@ConditionalOnProperty(prefix = "spring.shardingsphere", name = "enabled", havingValue = "true", matchIfMissing = true)
// shardingsphere initialization DataSource Prior to the DataSourceAutoConfiguration, meanwhile MybatisAutoConfiguration Initialization lags behind DataSourceAutoConfiguration
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@RequiredArgsConstructor
public class SpringBootConfiguration implements EnvironmentAware {
@Bean
@Conditional(ShardingRuleCondition.class)
public DataSource shardingDataSource() throws SQLException {
return ShardingDataSourceFactory.createDataSource(dataSourceMap, new
ShardingRuleConfigurationYamlSwapper().swap(shardingRule), props.getProps());
}
}
public final class ShardingDataSourceFactory {
public static DataSource createDataSource(
final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig, final
Properties props) throws SQLException {
return new ShardingDataSource(dataSourceMap, new ShardingRule(shardingRuleConfig, dataSourceMap.keySet()),
props);
}
}
// ShardingRule Partition strategy information of database and table
public ShardingDataSource(final Map<String, DataSource> dataSourceMap, final ShardingRule shardingRule, final
Properties props) throws SQLException {
// among dataSourceMap In the end by the abstract class AbstractDataSourceAdapter hold
super(dataSourceMap);
checkDataSourceType(dataSourceMap);
runtimeContext = new ShardingRuntimeContext(dataSourceMap, shardingRule, props, getDatabaseType());
}
2、EnvironmentAware
Purpose to load configuration file information .
@Override
public final void setEnvironment(final Environment environment) {
String prefix = "spring.shardingsphere.datasource.";
// obtain prefix + name To configure 「spring.shardingsphere.datasource.name」 All library names
for (String each : getDataSourceNames(environment, prefix)) {
// dataSourceMap Maintain all configured in the configuration file DataSource
dataSourceMap.put(each, getDataSource(environment, prefix, each));
}
}
private DataSource getDataSource(final Environment environment, final String prefix, final String dataSourceName)
throws ReflectiveOperationException, NamingException {
Map<String, Object> dataSourceProps = PropertyUtil.handle(environment, prefix + dataSourceName.trim(), Map.class);
// configurable type Property initializes the corresponding type DataSource 「HikariDataSource」
DataSource result = DataSourceUtil.getDataSource(dataSourceProps.get("type").toString(), dataSourceProps);
...
return result;
}
public static DataSource getDataSource(final String dataSourceClassName, final Map<String, Object>
dataSourceProperties) throws ReflectiveOperationException {
// configurable driver-class-name Instantiation DataSource
DataSource result = (DataSource) Class.forName(dataSourceClassName).newInstance();
// Set up DataSource The attributes of include : user name 、 password 、jdbcUrl etc.
for (Entry<String, Object> entry : dataSourceProperties.entrySet()) {
callSetterMethod(result, getSetterMethodName(entry.getKey()), null == entry.getValue() ? null :
entry.getValue().toString());
}
return result;
}
3、ShardingConnection
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
//ShardingConnection: Before passing Mybatis Source analysis shows that , Finally through SpringManagedTransaction Held ShardingDataSource Get the connection ShardingConnection
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt);
return stmt;
}
public class ShardingDataSource extends AbstractDataSourceAdapter {
@Override
public final ShardingConnection getConnection() {
// getDataSourceMap() obtain abstract class AbstractDataSourceAdapter Held DataSourceMap
return new ShardingConnection(getDataSourceMap(), runtimeContext, TransactionTypeHolder.get());
}
}
public ShardingConnection(final Map<String, DataSource> dataSourceMap, final ShardingRuntimeContext runtimeContext,
final TransactionType transactionType) {
// Hold all of the current app dataSourceMap
this.dataSourceMap = dataSourceMap;
this.runtimeContext = runtimeContext;
this.transactionType = transactionType;
shardingTransactionManager =
runtimeContext.getShardingTransactionManagerEngine().getTransactionManager(transactionType);
}
4、ShardingPreparedStatement
// What is returned is ShardingPreparedStatement
public class PreparedStatementHandler extends BaseStatementHandler {
protected Statement instantiateStatement(Connection connection) throws SQLException {
String sql = boundSql.getSql();
if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
String[] keyColumnNames = mappedStatement.getKeyColumns();
if (keyColumnNames == null) {
return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
return connection.prepareStatement(sql, keyColumnNames);
}
} else if (mappedStatement.getResultSetType() == ResultSetType.DEFAULT) {
return connection.prepareStatement(sql);
} else {
return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(),
ResultSet.CONCUR_READ_ONLY);
}
}
}
@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
// ShardingPreparedStatement
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();
return resultSetHandler.handleResultSets(ps);
}
public boolean execute() throws SQLException {
// Start execution here Sub database sub table plug-in The logic of
prepare();
// #5 initialization StatementExecuteUnit, Namely PreparedStatement Final execution SQL Minimum unit of . It's initialization AbstractStatementExecutor attribute #inputGroups
initPreparedStatementExecutor();
// Actually execute through callback SQL
return preparedStatementExecutor.execute();
}
public final class SQLExecuteCallbackFactory {
public static SQLExecuteCallback<Boolean> getPreparedSQLExecuteCallback(final DatabaseType databaseType, final
boolean isExceptionThrown) {
return new SQLExecuteCallback<Boolean>(databaseType, isExceptionThrown) {
@Override
protected Boolean executeSQL(final String sql, final Statement statement, final ConnectionMode
connectionMode) throws SQLException {
// Really implement native jdbc
return ((PreparedStatement) statement).execute();
}
};
}
}
5、PreparedStatementExecutor
AbstractStatementExecutor#inputGroups
contain SQL Carry out what is needed SQL、sql Parameters & PrepareStatement etc. .PrepareStatement There is a database connection 、jdbcUrl etc. SQL Necessary conditions for implementation .
public final class PreparedStatementExecutor extends AbstractStatementExecutor {
public void init(final ExecutionContext executionContext) throws SQLException {
setSqlStatementContext(executionContext.getSqlStatementContext());
// obtain AbstractStatementExecutor Class properties inputGroups
getInputGroups().addAll(obtainExecuteGroups(executionContext.getExecutionUnits()));
cacheStatements();
}
private Collection<InputGroup<StatementExecuteUnit>> obtainExecuteGroups(final Collection<ExecutionUnit>
executionUnits) throws SQLException {
return getSqlExecutePrepareTemplate().getExecuteUnitGroups(executionUnits, new SQLExecutePrepareCallback() {
@Override
public List<Connection> getConnections(final ConnectionMode connectionMode, final String dataSourceName,
final int connectionSize) throws SQLException {
//dataSourceName: It's user implementation PreciseShardingAlgorithm The name of the target library returned by the interface
// adopt dataSourceName from AbstractDataSourceAdapter in dataSourceMap Get the corresponding dataSource
// adopt dataSource Get the corresponding database connection
return PreparedStatementExecutor.super.getConnection().getConnections(connectionMode, dataSourceName,
connectionSize);
}
@Override
public StatementExecuteUnit createStatementExecuteUnit(final Connection connection, final ExecutionUnit
executionUnit, final ConnectionMode connectionMode) throws SQLException {
// establish StatementExecuteUnit:createPreparedStatement adopt
return new StatementExecuteUnit(executionUnit, createPreparedStatement(connection,
executionUnit.getSqlUnit().getSql()), connectionMode);
}
});
}
private PreparedStatement createPreparedStatement(final Connection connection, final String sql) throws
SQLException {
// adopt HikariProxyConnection obtain prepareStatement
return returnGeneratedKeys ? connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
: connection.prepareStatement(sql, getResultSetType(), getResultSetConcurrency(),
getResultSetHoldability());
}
}
StatementExecuteUnit
public final class StatementExecuteUnit {
private final ExecutionUnit executionUnit;
private final Statement statement;
private final ConnectionMode connectionMode;
}
public final class ExecutionUnit {
private final String dataSourceName;
private final SQLUnit sqlUnit;
}
public final class SQLUnit {
private final String sql;
private final List<Object> parameters;
}
Native jdbc
public static void main(String[] args) throws Exception {
//1、 Registration drive
Class.forName("com.mysql.jdbc.Driver");
//2、 Get the connection object
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/day01_db",
"root", "1234");
//3、 Get send SQL Object of statement
PreparedStatement ps = con.prepareStatement("select * from category");
//4、 send out SQL sentence , Return result set
ResultSet rs = ps.executeQuery();
//5、 Traversal result set
while (rs.next()){
// Traverse this row of data
int cid = rs.getInt("cid");
String cname = rs.getString("cname");
System.out.println("cid:"+cid+"\t cname:"+cname);
}
//6、 close resource
rs.close();
ps.close();
con.close();
}
边栏推荐
- 单商户V4.4,初心未变,实力依旧!
- 保研笔记二 软件工程与计算卷二(13-16章)
- wx.getLocation(Object object)申请方法,最新版
- 软件测试工程师必会的银行存款业务,你了解多少?
- Tips for using pads router
- China Jinmao online electronic signature, accelerating the digitization of real estate business
- 【luogu P3295】萌萌哒(并查集)(倍增)
- TS type declaration
- QT a simple word document editor
- The use of El cascader and the solution of error reporting
猜你喜欢
My colleagues quietly told me that flying Book notification can still play like this
Rasa 3. X learning series -rasa x Community Edition (Free Edition) changes
How to rotate the synchronized / refreshed icon (EL icon refresh)
如何获取localStorage中存储的所有值
Rasa 3.x 学习系列-Rasa 3.2.1 新版本发布
用列表初始化你的vector&&initializer_list简介
PV static creation and dynamic creation
XML configuration file (DTD detailed explanation)
After summarizing more than 800 kubectl aliases, I'm no longer afraid that I can't remember commands!
Spire Office 7.5.4 for NET
随机推荐
7.5模拟赛总结
传输层协议------UDP协议
开源crm客户关系统管理系统源码,免费分享
What are the functions of Yunna fixed assets management system?
FFT 学习笔记(自认为详细)
Bao Yan notes II software engineering and calculation volume II (Chapter 13-16)
Qt 一个简单的word文档编辑器
Zhongjun group launched electronic contracts to accelerate the digital development of real estate enterprises
Redis high availability - master-slave replication, sentinel mode, cluster
Doppler effect (Doppler shift)
上门预约服务类的App功能详解
15 MySQL-存储过程与函数
Redis高可用——主从复制、哨兵模式、集群
The use of El cascader and the solution of error reporting
Zhuan: in the future, such an organization can withstand the risks
GFS distributed file system
Online yaml to CSV tool
单商户V4.4,初心未变,实力依旧!
TS type declaration
Tips for using pads router