当前位置:网站首页>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();
}
边栏推荐
- 20.移植Freetype字体库
- Cwaitabletimer timer, used to create timer object access
- 【GYM 102832H】【模板】Combination Lock(二分图博弈)
- mysql-全局锁和表锁
- Redis高可用——主从复制、哨兵模式、集群
- 7.5 装饰器
- 单商户V4.4,初心未变,实力依旧!
- rsync远程同步
- Chapter 16 oauth2authorizationrequestredirectwebfilter source code analysis
- Asynchronous task Whenall timeout - Async task WhenAll with timeout
猜你喜欢
随机推荐
【二叉搜索树】增删改查功能代码实现
Add noise randomly to open3d point cloud
Yunna | what are the main operating processes of the fixed assets management system
18.(arcgis api for js篇)arcgis api for js点采集(SketchViewModel)
多普勒效應(多普勒頻移)
Rasa 3. X learning series -rasa 3.2.1 new release
China Jinmao online electronic signature, accelerating the digitization of real estate business
PADS ROUTER 使用技巧小记
Initialize your vector & initializer with a list_ List introduction
GFS distributed file system
零犀科技携手集智俱乐部:“因果派”论坛成功举办,“因果革命”带来下一代可信AI
Russian Foreign Ministry: Japan and South Korea's participation in the NATO summit affects security and stability in Asia
妙才周刊 - 8
Rasa 3. X learning series -rasa x Community Edition (Free Edition) changes
Problems encountered in the database
QT--线程
Qt 一个简单的word文档编辑器
用列錶初始化你的vector&&initializer_list簡介
Opencvsharp (C openCV) shape detection and recognition (with source code)
SpreadJS 15.1 CN 与 SpreadJS 15.1 EN