本文主要研究一下sharding-jdbc的ShardingTransactionManager

ShardingTransactionManager

incubator-shardingsphere-4.0.0-RC1/sharding-transaction/sharding-transaction-core/src/main/java/org/apache/shardingsphere/transaction/spi/ShardingTransactionManager.java

public interface ShardingTransactionManager extends AutoCloseable {
    
    /**
     * Initialize sharding transaction manager.
     *
     * @param databaseType database type
     * @param resourceDataSources resource data sources
     */
    void init(DatabaseType databaseType, Collection<ResourceDataSource> resourceDataSources);
    
    /**
     * Get transaction type.
     *
     * @return transaction type
     */
    TransactionType getTransactionType();
    
    /**
     * Judge is in transaction or not.
     * 
     * @return in transaction or not
     */
    boolean isInTransaction();
    
    /**
     * Get transactional connection.
     *
     * @param dataSourceName data source name
     * @return connection
     * @throws SQLException SQL exception
     */
    Connection getConnection(String dataSourceName) throws SQLException;
    
    /**
     * Begin transaction.
     */
    void begin();
    
    /**
     * Commit transaction.
     */
    void commit();
    
    /**
     * Rollback transaction.
     */
    void rollback();
}
  • ShardingTransactionManager继承了AutoCloseable接口,它定义了init、getTransactionType、isInTransaction、getConnection、begin、commit、rollback方法

XAShardingTransactionManager

incubator-shardingsphere-4.0.0-RC1/sharding-transaction/sharding-transaction-2pc/sharding-transaction-xa/sharding-transaction-xa-core/src/main/java/org/apache/shardingsphere/transaction/xa/XAShardingTransactionManager.java

public final class XAShardingTransactionManager implements ShardingTransactionManager {
    
    private final Map<String, SingleXADataSource> singleXADataSourceMap = new HashMap<>();
    
    private final XATransactionManager xaTransactionManager = XATransactionManagerLoader.getInstance().getTransactionManager();
    
    private ThreadLocal<List<String>> enlistedXAResource = new ThreadLocal<List<String>>() {
        @Override
        public List<String> initialValue() {
            return new LinkedList<>();
        }
    };
    
    @Override
    public void init(final DatabaseType databaseType, final Collection<ResourceDataSource> resourceDataSources) {
        for (ResourceDataSource each : resourceDataSources) {
            DataSource dataSource = each.getDataSource();
            if (dataSource instanceof AtomikosDataSourceBean) {
                continue;
            }
            SingleXADataSource singleXADataSource = new SingleXADataSource(databaseType, each.getUniqueResourceName(), dataSource);
            singleXADataSourceMap.put(each.getOriginalName(), singleXADataSource);
            xaTransactionManager.registerRecoveryResource(each.getUniqueResourceName(), singleXADataSource.getXaDataSource());
        }
        xaTransactionManager.init();
    }
    
    @Override
    public TransactionType getTransactionType() {
        return TransactionType.XA;
    }
    
    @SneakyThrows
    @Override
    public boolean isInTransaction() {
        return Status.STATUS_NO_TRANSACTION != xaTransactionManager.getTransactionManager().getStatus();
    }
    
    @SneakyThrows
    @Override
    public Connection getConnection(final String dataSourceName) {
        SingleXAConnection singleXAConnection = singleXADataSourceMap.get(dataSourceName).getXAConnection();
        if (!enlistedXAResource.get().contains(dataSourceName)) {
            xaTransactionManager.enlistResource(singleXAConnection.getXAResource());
            enlistedXAResource.get().add(dataSourceName);
        }
        return singleXAConnection.getConnection();
    }
    
    @SneakyThrows
    @Override
    public void begin() {
        xaTransactionManager.getTransactionManager().begin();
    }
    
    @SneakyThrows
    @Override
    public void commit() {
        try {
            xaTransactionManager.getTransactionManager().commit();
        } finally {
            enlistedXAResource.remove();
        }
    }
    
    @SneakyThrows
    @Override
    public void rollback() {
        try {
            xaTransactionManager.getTransactionManager().rollback();
        } finally {
            enlistedXAResource.remove();
        }
    }
    
    @Override
    public void close() throws Exception {
        for (SingleXADataSource each : singleXADataSourceMap.values()) {
            xaTransactionManager.removeRecoveryResource(each.getResourceName(), each.getXaDataSource());
        }
        singleXADataSourceMap.clear();
        xaTransactionManager.close();
        enlistedXAResource = null;
    }
}
  • XAShardingTransactionManager实现了ShardingTransactionManager接口,它拥有singleXADataSourceMap、xaTransactionManager、enlistedXAResource三个属性,其init方法对这三个属性进行了初始化
  • getTransactionType方法返回的是TransactionType.XA;isInTransaction方法则依据xaTransactionManager.getTransactionManager().getStatus()来判断;getConnection方法从singleXADataSourceMap取出singleXAConnection,然后执行其getConnection方法
  • begin方法执行的是xaTransactionManager.getTransactionManager().begin();commit方法则调用了xaTransactionManager.getTransactionManager().commit(),其会在finally中执行enlistedXAResource.remove();rollback方法调用了xaTransactionManager.getTransactionManager().rollback(),其也在finally中执行enlistedXAResource.remove();close方法则执行xaTransactionManager.removeRecoveryResource、singleXADataSourceMap.clear()、xaTransactionManager.close()

XAShardingTransactionManagerTest

incubator-shardingsphere-4.0.0-RC1/sharding-transaction/sharding-transaction-2pc/sharding-transaction-xa/sharding-transaction-xa-core/src/test/java/org/apache/shardingsphere/transaction/xa/XAShardingTransactionManagerTest.java

@RunWith(MockitoJUnitRunner.class)
public final class XAShardingTransactionManagerTest {
    
    private XAShardingTransactionManager xaShardingTransactionManager = new XAShardingTransactionManager();
    
    @Mock
    private XATransactionManager xaTransactionManager;
    
    @Mock
    private TransactionManager transactionManager;
    
    @Before
    public void setUp() {
        when(xaTransactionManager.getTransactionManager()).thenReturn(transactionManager);
        ReflectiveUtil.setProperty(xaShardingTransactionManager, "xaTransactionManager", xaTransactionManager);
    }
    
    @Test
    public void assertGetTransactionType() {
        assertThat(xaShardingTransactionManager.getTransactionType(), is(TransactionType.XA));
    }
    
    @Test
    public void assertRegisterXATransactionalDataSources() {
        Collection<ResourceDataSource> resourceDataSources = createResourceDataSources(DruidXADataSource.class, DatabaseType.MySQL);
        xaShardingTransactionManager.init(DatabaseType.MySQL, resourceDataSources);
        for (ResourceDataSource each : resourceDataSources) {
            verify(xaTransactionManager).registerRecoveryResource(each.getUniqueResourceName(), (XADataSource) each.getDataSource());
        }
    }
    
    @Test
    public void assertRegisterAtomikosDataSourceBeans() {
        xaShardingTransactionManager.init(DatabaseType.MySQL, createAtomikosDataSourceBeanResource());
        verify(xaTransactionManager, times(0)).registerRecoveryResource(anyString(), any(XADataSource.class));
    }
    
    @Test
    public void assertRegisterNoneXATransactionalDAtaSources() {
        Collection<ResourceDataSource> resourceDataSources = createResourceDataSources(HikariDataSource.class, DatabaseType.MySQL);
        xaShardingTransactionManager.init(DatabaseType.MySQL, resourceDataSources);
        Map<String, SingleXADataSource> cachedXADatasourceMap = getCachedSingleXADataSourceMap();
        assertThat(cachedXADatasourceMap.size(), is(2));
    }
    
    @Test
    public void assertIsInTransaction() throws SystemException {
        when(transactionManager.getStatus()).thenReturn(Status.STATUS_ACTIVE);
        assertTrue(xaShardingTransactionManager.isInTransaction());
    }
    
    @Test
    public void assertIsNotInTransaction() throws SystemException {
        when(transactionManager.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION);
        assertFalse(xaShardingTransactionManager.isInTransaction());
    }
    
    @Test
    public void assertGetConnection() {
        setCachedSingleXADataSourceMap("ds1");
        Connection actual = xaShardingTransactionManager.getConnection("ds1");
        assertThat(actual, instanceOf(Connection.class));
        verify(xaTransactionManager).enlistResource(any(SingleXAResource.class));
    }
    
    @Test
    public void assertGetConnectionWithoutEnlist() {
        setCachedSingleXADataSourceMap("ds1");
        Connection actual = xaShardingTransactionManager.getConnection("ds1");
        assertThat(actual, instanceOf(Connection.class));
        xaShardingTransactionManager.getConnection("ds1");
        assertThat(actual, instanceOf(Connection.class));
        verify(xaTransactionManager).enlistResource(any(SingleXAResource.class));
    }
    
    @Test
    public void assertClose() throws Exception {
        setCachedSingleXADataSourceMap("ds1");
        xaShardingTransactionManager.close();
        Map<String, SingleXADataSource> cachedSingleXADataSourceMap = getCachedSingleXADataSourceMap();
        verify(xaTransactionManager).removeRecoveryResource(anyString(), any(XADataSource.class));
        assertThat(cachedSingleXADataSourceMap.size(), is(0));
    }
    
    @SneakyThrows
    @SuppressWarnings("unchecked")
    private Map<String, SingleXADataSource> getCachedSingleXADataSourceMap() {
        Field field = xaShardingTransactionManager.getClass().getDeclaredField("singleXADataSourceMap");
        field.setAccessible(true);
        return (Map<String, SingleXADataSource>) field.get(xaShardingTransactionManager);
    }
    
    @SneakyThrows
    private void setCachedSingleXADataSourceMap(final String datasourceName) {
        Field field = xaShardingTransactionManager.getClass().getDeclaredField("singleXADataSourceMap");
        field.setAccessible(true);
        field.set(xaShardingTransactionManager, createMockSingleXADataSourceMap(datasourceName));
    }
    
    @SneakyThrows
    private Map<String, SingleXADataSource> createMockSingleXADataSourceMap(final String datasourceName) {
        SingleXADataSource singleXADataSource = mock(SingleXADataSource.class);
        SingleXAConnection singleXAConnection = mock(SingleXAConnection.class);
        XADataSource xaDataSource = mock(XADataSource.class);
        SingleXAResource singleXAResource = mock(SingleXAResource.class);
        Connection connection = mock(Connection.class);
        when(singleXAConnection.getConnection()).thenReturn(connection);
        when(singleXAConnection.getXAResource()).thenReturn(singleXAResource);
        when(singleXADataSource.getXAConnection()).thenReturn(singleXAConnection);
        when(singleXADataSource.getResourceName()).thenReturn(datasourceName);
        when(singleXADataSource.getXaDataSource()).thenReturn(xaDataSource);
        Map<String, SingleXADataSource> result = new HashMap<>();
        result.put(datasourceName, singleXADataSource);
        return result;
    }
    
    private Collection<ResourceDataSource> createResourceDataSources(final Class<? extends DataSource> dataSourceClass, final DatabaseType databaseType) {
        List<ResourceDataSource> result = new LinkedList<>();
        result.add(new ResourceDataSource("ds1", DataSourceUtils.build(dataSourceClass, databaseType, "demo_ds_1")));
        result.add(new ResourceDataSource("ds2", DataSourceUtils.build(dataSourceClass, databaseType, "demo_ds_2")));
        return result;
    }
    
    private Collection<ResourceDataSource> createAtomikosDataSourceBeanResource() {
        List<ResourceDataSource> result = new LinkedList<>();
        result.add(new ResourceDataSource("ds1", new AtomikosDataSourceBean()));
        result.add(new ResourceDataSource("ds2", new AtomikosDataSourceBean()));
        return result;
    }
}
  • 这里mock了xaTransactionManager、transactionManager

小结

  • XAShardingTransactionManager实现了ShardingTransactionManager接口,它拥有singleXADataSourceMap、xaTransactionManager、enlistedXAResource三个属性,其init方法对这三个属性进行了初始化
  • getTransactionType方法返回的是TransactionType.XA;isInTransaction方法则依据xaTransactionManager.getTransactionManager().getStatus()来判断;getConnection方法从singleXADataSourceMap取出singleXAConnection,然后执行其getConnection方法
  • begin方法执行的是xaTransactionManager.getTransactionManager().begin();commit方法则调用了xaTransactionManager.getTransactionManager().commit(),其会在finally中执行enlistedXAResource.remove();rollback方法调用了xaTransactionManager.getTransactionManager().rollback(),其也在finally中执行enlistedXAResource.remove();close方法则执行xaTransactionManager.removeRecoveryResource、singleXADataSourceMap.clear()、xaTransactionManager.close()

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


引用和评论

0 条评论