聊聊sharding-jdbc的WrapperAdapter
阿新 • • 發佈:2019-12-31
序
本文主要研究一下sharding-jdbc的WrapperAdapter
Wrapper
jdk-12.jdk/Contents/Home/lib/src.zip!/java.sql/java/sql/Wrapper.java
public interface Wrapper {
<T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException;
boolean isWrapperFor(java.lang.Class<?> iface) throws java.sql.SQLException;
}
複製程式碼
- Wrapper介面定義了unwrap、isWrapperFor方法
WrapperAdapter
incubator-shardingsphere-4.0.0-RC1/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/WrapperAdapter.java
public abstract class WrapperAdapter implements Wrapper {
private final Collection<JdbcMethodInvocation> jdbcMethodInvocations = new ArrayList<>();
@SuppressWarnings("unchecked" )
@Override
public final <T> T unwrap(final Class<T> iface) throws SQLException {
if (isWrapperFor(iface)) {
return (T) this;
}
throw new SQLException(String.format("[%s] cannot be unwrapped as [%s]",getClass().getName(),iface.getName()));
}
@Override
public final boolean isWrapperFor(final Class<?> iface) {
return iface.isInstance(this);
}
/**
* record method invocation.
*
* @param targetClass target class
* @param methodName method name
* @param argumentTypes argument types
* @param arguments arguments
*/
@SneakyThrows
public final void recordMethodInvocation(final Class<?> targetClass,final String methodName,final Class<?>[] argumentTypes,final Object[] arguments) {
jdbcMethodInvocations.add(new JdbcMethodInvocation(targetClass.getMethod(methodName,argumentTypes),arguments));
}
/**
* Replay methods invocation.
*
* @param target target object
*/
public final void replayMethodsInvocation(final Object target) {
for (JdbcMethodInvocation each : jdbcMethodInvocations) {
each.invoke(target);
}
}
}
複製程式碼
- WrapperAdapter宣告實現java.sql.Wrapper介面,它定義了JdbcMethodInvocation集合;recordMethodInvocation方法會往jdbcMethodInvocations新增JdbcMethodInvocation;replayMethodsInvocation方法則會挨個執行JdbcMethodInvocation的invoke方法
JdbcMethodInvocation
incubator-shardingsphere-4.0.0-RC1/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocation.java
@RequiredArgsConstructor
public class JdbcMethodInvocation {
@Getter
private final Method method;
@Getter
private final Object[] arguments;
/**
* Invoke JDBC method.
*
* @param target target object
*/
@SneakyThrows
public void invoke(final Object target) {
method.invoke(target,arguments);
}
}
複製程式碼
- JdbcMethodInvocation的invoke方法執行的是method.invoke
小結
WrapperAdapter宣告實現java.sql.Wrapper介面,它定義了JdbcMethodInvocation集合;recordMethodInvocation方法會往jdbcMethodInvocations新增JdbcMethodInvocation;replayMethodsInvocation方法則會挨個執行JdbcMethodInvocation的invoke方法