当前位置:网站首页>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();
}
边栏推荐
- Spire Office 7.5.4 for NET
- How much do you know about the bank deposit business that software test engineers must know?
- Senparc.Weixin.Sample.MP源码剖析
- Transport layer protocol ----- UDP protocol
- 15 MySQL-存储过程与函数
- 多普勒效应(多普勒频移)
- 行列式学习笔记(一)
- Spreadjs 15.1 CN and spreadjs 15.1 en
- 【luogu CF487E】Tourists(圆方树)(树链剖分)(线段树)
- How to improve eloquence
猜你喜欢
PV static creation and dynamic creation
单商户V4.4,初心未变,实力依旧!
China Jinmao online electronic signature, accelerating the digitization of real estate business
云呐|公司固定资产管理系统有哪些?
What are the functions of Yunna fixed assets management system?
Fiddler Everywhere 3.2.1 Crack
跟着CTF-wiki学pwn——ret2libc1
XML配置文件(DTD详细讲解)
Part III Verilog enterprise real topic of "Niuke brush Verilog"
Initialize your vector & initializer with a list_ List introduction
随机推荐
总结了 800多个 Kubectl 别名,再也不怕记不住命令了!
提升工作效率工具:SQL批量生成工具思想
Bao Yan notebook IV software engineering and calculation volume II (Chapter 8-12)
Open3D 点云随机添加噪声
Qt QPushButton详解
GFS分布式文件系統
关于结构体所占内存大小知识
14 MySQL view
上门预约服务类的App功能详解
Spire.PDF for NET 8.7.2
行列式学习笔记(一)
Do you regret becoming a programmer?
[Luogu p3295] mengmengda (parallel search) (double)
Russian Foreign Ministry: Japan and South Korea's participation in the NATO summit affects security and stability in Asia
USB Interface USB protocol
C # input how many cards are there in each of the four colors.
How to rotate the synchronized / refreshed icon (EL icon refresh)
Zhongjun group launched electronic contracts to accelerate the digital development of real estate enterprises
21. PWM application programming
Cwaitabletimer timer, used to create timer object access