读写分离
一主多从:可以将查询请求均匀的分散到多个数据副本,能够进一步的提升系统的处理能力。
多主多从:不但能够提升系统的吞吐量,还能够提升系统的可用性,可以达到在任何一个数据库宕机,甚至磁盘物理损坏的情况下仍然不影响系统的正常运行。
水平分片:根据某种规则将数据分散至多个库或表中,每个分片仅包含数据的一部分。
读写分离:根据 SQL 语义的分析,将读操作和写操作分别路由至主库与从库。
支持项
不支持项
读写分离原理:
sharding-jdbc-spring-boot-starter.java 启动时, 加载 spring.shardingsphere.masterslave 配置。
SpringBootConfiguration.java 实现 EnvironmentAware.java 接口
public class SpringBootConfiguration implements EnvironmentAware{... ...}
复制代码
EnvironmentAware.java
/**
* Interface to be implemented by any bean that wishes to be notified
* of the {@link Environment} that it runs in.
*
* @author Chris Beams
* @since 3.1
* @see org.springframework.core.env.EnvironmentCapable
*/
public interface EnvironmentAware extends Aware {
/**
* Set the {@code Environment} that this component runs in.
*/
void setEnvironment(Environment environment);
}
复制代码
Aware.java
/**
* A marker superinterface indicating that a bean is eligible to be notified by the
* Spring container of a particular framework object through a callback-style method.
* The actual method signature is determined by individual subinterfaces but should
* typically consist of just one void-returning method that accepts a single argument.
*
* <p>Note that merely implementing {@link Aware} provides no default functionality.
* Rather, processing must be done explicitly, for example in a
* {@link org.springframework.beans.factory.config.BeanPostProcessor}.
* Refer to {@link org.springframework.context.support.ApplicationContextAwareProcessor}
* for an example of processing specific {@code *Aware} interface callbacks.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
*/
public interface Aware {
}
复制代码
Bean 加载完成后执行 setEnvironment()方法,将数据源保存到 dataSourceMap。
/**
* Get master-slave data source bean.
*
* @return data source bean
* @throws SQLException SQL exception
*/
@Bean
@Conditional(MasterSlaveRuleCondition.class)
public DataSource masterSlaveDataSource() throws SQLException {
return MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, new MasterSlaveRuleConfigurationYamlSwapper().swap(masterSlaveRule), props.getProps());
}
... ...
//将数据源保存到dataSourceMap
@Override
public final void setEnvironment(final Environment environment) {
String prefix = "spring.shardingsphere.datasource.";
for (String each : getDataSourceNames(environment, prefix)) {
try {
dataSourceMap.put(each, getDataSource(environment, prefix, each));
} catch (final ReflectiveOperationException ex) {
throw new ShardingSphereException("Can't find datasource type!", ex);
} catch (final NamingException namingEx) {
throw new ShardingSphereException("Can't find JNDI datasource!", namingEx);
}
}
}
复制代码
评论