io.seata.rm.datasource.DataSourceProxy Java Examples

The following examples show how to use io.seata.rm.datasource.DataSourceProxy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MyBatisConfig.java    From seata-samples with Apache License 2.0 6 votes vote down vote up
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSourceProxy);
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    // bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
    bean.setMapperLocations(resolver.getResources("classpath*:mybatis/**/*-mapper.xml"));

    SqlSessionFactory factory = null;
    try {
        factory = bean.getObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return factory;
}
 
Example #2
Source File: DataSourceConfiguration.java    From seata-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSourceProxy dataSourceProxy,
                                                   MybatisProperties mybatisProperties) {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSourceProxy);

    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        Resource[] mapperLocaltions = resolver.getResources(mybatisProperties.getMapperLocations()[0]);
        bean.setMapperLocations(mapperLocaltions);

        if (StringUtils.isNotBlank(mybatisProperties.getConfigLocation())) {
            Resource[] resources = resolver.getResources(mybatisProperties.getConfigLocation());
            bean.setConfigLocation(resources[0]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bean;
}
 
Example #3
Source File: DataSourceConfiguration.java    From seata-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSourceProxy dataSourceProxy,
                                                   MybatisProperties mybatisProperties) {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSourceProxy);

    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        Resource[] mapperLocaltions = resolver.getResources(mybatisProperties.getMapperLocations()[0]);
        bean.setMapperLocations(mapperLocaltions);

        if (StringUtils.isNotBlank(mybatisProperties.getConfigLocation())) {
            Resource[] resources = resolver.getResources(mybatisProperties.getConfigLocation());
            bean.setConfigLocation(resources[0]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bean;
}
 
Example #4
Source File: EtDataSourceManager.java    From EasyTransaction with Apache License 2.0 6 votes vote down vote up
private void undoRecords(Connection conn, String resourceId, List<byte[]> rollbackInfos) throws SQLException {

        DataSourceProxy dataSourceProxy = get(resourceId);

        for (byte[] rollbackInfo : rollbackInfos) {
            BranchUndoLog branchUndoLog = UndoLogParserFactory.getInstance().decode(rollbackInfo);

            for (SQLUndoLog sqlUndoLog : branchUndoLog.getSqlUndoLogs()) {
                TableMeta tableMeta = TableMetaCache.getTableMeta(dataSourceProxy, sqlUndoLog.getTableName());
                sqlUndoLog.setTableMeta(tableMeta);
                AbstractUndoExecutor undoExecutor = UndoExecutorFactory.getUndoExecutor(dataSourceProxy.getDbType(), sqlUndoLog);
                undoExecutor.executeOn(conn);
            }

        }

    }
 
Example #5
Source File: EtDataSourceManager.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Override
    public Long branchRegister(BranchType branchType, String resourceId, String clientId, String xid, String applicationData, String lockKey) throws TransactionException {
//        public Long branchRegister(BranchType branchType, String resourceId, String clientId, String xid, String lockKey) throws TransactionException {

        Integer callSeq = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.CALL_SEQ);

        // check locks
        if (StringUtils.isNullOrEmpty(lockKey)) {
            return callSeq== null?-1:callSeq.longValue();
        }

        //ET要求使用Spring管控下的事务,因此本方法可以获得对应的当前连接,获取当前连接来执行时为了避免争夺连接词的连接导致死锁
        DataSourceProxy dataSourceProxy = get(resourceId);
        ConnectionProxy cp = (ConnectionProxy) DataSourceUtils.getConnection(dataSourceProxy);
        Connection targetConnection = cp.getTargetConnection();
        
        if (callSeq != null) {
            // callSeq != null means it's in ET transaction control
            try {
                doLockKeys(xid, lockKey, targetConnection);
            } catch (SQLException e) {
                throw new RuntimeException("Obtain Lock failed, Rollback transaction:" + lockKey, e);
            }

        } else {
            // callSeq == null means it's just a local transaction or a master transaction in ET
            // it need to check lock
            if(!lockQuery(branchType, resourceId, xid, lockKey)) {
                throw new RuntimeException("Obtain Lock failed, Rollback transaction:" + lockKey);
            }
            
            // not need to save undolog ,undo will be handle by local transaction, just hack to clean undo log
            cp.getContext().getUndoItems().clear();
        }
        
        return callSeq== null?-1:callSeq.longValue();
    }
 
Example #6
Source File: DruidConfiguration.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Data source data source.
 *
 * @param druidDataSource the druid data source
 * @return the data source
 */
@ConfigurationProperties(prefix = "spring.datasource")
@Primary
@Bean("dataSource")
public DataSource dataSource(DruidDataSource druidDataSource) {
	DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource);
	return dataSourceProxy;
}
 
Example #7
Source File: SeataConfiguration.java    From spring-boot-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSourceProxy);
    sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/mapper/*.xml"));
    sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
    return sqlSessionFactoryBean.getObject();
}
 
Example #8
Source File: SeataConfiguration.java    From spring-boot-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSourceProxy);
    sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/mapper/*.xml"));
    sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
    return sqlSessionFactoryBean.getObject();
}
 
Example #9
Source File: SeataAutoConfig.java    From demo-seata-springcloud with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化mybatis sqlSessionFactory
 * 
 * @param dataSourceProxy
 * @return
 * @throws Exception
 * @author sly
 * @time 2019年6月11日
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
	SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
	factoryBean.setDataSource(dataSourceProxy);
	factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
	factoryBean.setTypeAliasesPackage("com.sly.seata.common.model");
	factoryBean.setTransactionFactory(new JdbcTransactionFactory());
	return factoryBean.getObject();
}
 
Example #10
Source File: SeataAutoConfig.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
/**
 * init mybatis sqlSessionFactory
 * @Param: dataSourceProxy  datasource proxy
 * @Return: DataSourceProxy  datasource proxy
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSourceProxy);
    factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/mapper/*.xml"));
    factoryBean.setTransactionFactory(new JdbcTransactionFactory());
    return factoryBean.getObject();
}
 
Example #11
Source File: SeataAutoConfig.java    From demo-seata-springcloud with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化mybatis sqlSessionFactory
 * 
 * @param dataSourceProxy
 * @return
 * @throws Exception
 * @author sly
 * @time 2019年6月11日
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
	SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
	factoryBean.setDataSource(dataSourceProxy);
	factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
	factoryBean.setTypeAliasesPackage("com.sly.seata.common.model");
	factoryBean.setTransactionFactory(new JdbcTransactionFactory());
	return factoryBean.getObject();
}
 
Example #12
Source File: SeataAutoConfig.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
/**
 * init mybatis sqlSessionFactory
 * @Param: dataSourceProxy  datasource proxy
 * @Return: DataSourceProxy  datasource proxy
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSourceProxy);
    factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/mapper/*.xml"));
    factoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
    return factoryBean.getObject();
}
 
Example #13
Source File: SeataAutoConfig.java    From demo-seata-springcloud with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化mybatis sqlSessionFactory
 * 
 * @param dataSourceProxy
 * @return
 * @throws Exception
 * @author sly
 * @time 2019年6月11日
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
	SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
	factoryBean.setDataSource(dataSourceProxy);
	factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
	factoryBean.setTypeAliasesPackage("com.sly.seata.common.model");
	factoryBean.setTransactionFactory(new JdbcTransactionFactory());
	return factoryBean.getObject();
}
 
Example #14
Source File: SeataAutoConfig.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
/**
 * init mybatis sqlSessionFactory
 * @Param: dataSourceProxy  datasource proxy
 * @Return: DataSourceProxy  datasource proxy
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSourceProxy);
    factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/mapper/*.xml"));
    factoryBean.setTransactionFactory(new JdbcTransactionFactory());
    return factoryBean.getObject();
}
 
Example #15
Source File: EtDataSourceManager.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Override
public boolean lockQuery(BranchType branchType, String resourceId, String xid, String lockKeys) throws TransactionException {
    
    DataSourceProxy dataSourceProxy = get(resourceId);
    //ET要求使用Spring管控下的事务,因此本方法可以获得对应的当前连接,获取当前连接来执行时为了避免争夺连接词的连接导致死锁
    ConnectionProxy cp = (ConnectionProxy) DataSourceUtils.getConnection(dataSourceProxy);
    Connection targetConnection = cp.getTargetConnection();
    try {
        return queryLockKeys(xid, lockKeys, targetConnection);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: ShardingSpringBootConfiguration.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
    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);
        Preconditions.checkState(!dataSourceProps.isEmpty(), "Wrong datasource properties!");
        if (dataSourceProps.containsKey(jndiName)) {
            return getJndiDataSource(dataSourceProps.get(jndiName).toString());
        }
//        return DataSourceUtil.getDataSource(dataSourceProps.get("type").toString(), dataSourceProps);
        /**
         * modify
         * use seata DataSourceProxy
         */
        return new DataSourceProxy(DataSourceUtil.getDataSource(dataSourceProps.get("type").toString(), dataSourceProps));
    }
 
Example #17
Source File: SeataATShardingTransactionManagerTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertInit() {
    Map<String, DataSource> actual = getDataSourceMap();
    assertThat(actual.size(), is(1));
    assertThat(actual.get("demo_ds"), instanceOf(DataSourceProxy.class));
    assertThat(seataATShardingTransactionManager.getTransactionType(), is(TransactionType.BASE));
}
 
Example #18
Source File: SeataATShardingTransactionManager.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
public void init(final DatabaseType databaseType, final Collection<ResourceDataSource> resourceDataSources) {
    if (enableSeataAT) {
        initSeataRPCClient();
        for (ResourceDataSource each : resourceDataSources) {
            dataSourceMap.put(each.getOriginalName(), new DataSourceProxy(each.getDataSource()));
        }
    }
}
 
Example #19
Source File: CouponApplication.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSourceProxy() {
    
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl("jdbc:mysql://localhost:3306/coupon?characterEncoding=UTF-8&useSSL=false");
    druidDataSource.setUsername("root");
    druidDataSource.setPassword("123456");
    
    return new DataSourceProxy(druidDataSource);
}
 
Example #20
Source File: EtDataSourceManager.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
private void cleanLocks(String xid, long branchId, Connection conn, List<byte[]> rollbackInfos, String resourceId) throws SQLException {

        DataSourceProxy dataSourceProxy = get(resourceId);
        PreparedStatement pdst = conn.prepareStatement(DELETE_LOCK_SQL);

        int cleanRecords = 0;
        for (byte[] rollbackInfo : rollbackInfos) {
            BranchUndoLog branchUndoLog = UndoLogParserFactory.getInstance().decode(rollbackInfo);

            for (SQLUndoLog sqlUndoLog : branchUndoLog.getSqlUndoLogs()) {

                Set<String> tableLockKeys = new HashSet<String>();

                String tableName = sqlUndoLog.getTableName().replace("`", "");
                TableMeta tableMeta = TableMetaCache.getTableMeta(dataSourceProxy, tableName);
                sqlUndoLog.setTableMeta(tableMeta);

                // TODO it assumes only support single filed primary key
                List<Field> beforeImage = sqlUndoLog.getBeforeImage().pkRows();
                List<Field> afterImage = sqlUndoLog.getAfterImage().pkRows();

                tableLockKeys.addAll(beforeImage.stream().map(k -> k.getValue().toString()).collect(Collectors.toList()));
                tableLockKeys.addAll(afterImage.stream().map(k -> k.getValue().toString()).collect(Collectors.toList()));

                for (String key : tableLockKeys) {
                    pdst.setString(1, tableName);
                    pdst.setString(2, key);
                    pdst.addBatch();
                    cleanRecords++;
                }
            }
        }
        
        if (cleanRecords > 0) {
            pdst.executeUpdate();
        }
    }
 
Example #21
Source File: DataSourceConfiguration.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception{
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSourceProxy);
    sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
    .getResources("classpath*:/mapper/*.xml"));
    sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
    return sqlSessionFactoryBean.getObject();
}
 
Example #22
Source File: DataSourceConfiguration.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception{
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSourceProxy);
    sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/mapper/*.xml"));
    sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
    return sqlSessionFactoryBean.getObject();
}
 
Example #23
Source File: DataSourceConfiguration.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception{
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSourceProxy);
    sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/mapper/*.xml"));
    sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
    return sqlSessionFactoryBean.getObject();
}
 
Example #24
Source File: DataSourceUtil.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Gets data source.
 *
 * @param name the name
 * @return the data source
 */
public static DataSource getDataSource(String name) {
    String driverKey = "jdbc." + name + ".driver";
    String urlKey = "jdbc." + name + ".url";
    String userNameKey = "jdbc." + name + ".username";
    String pwdKey = "jdbc." + name + ".password";
    DataSource dataSource = new DruidDataSource();
    ((DruidDataSource)dataSource).setDriverClassName(PropertiesUtil.getPropertieValue(JDBC_PRO_PATH, driverKey));
    ((DruidDataSource)dataSource).setUrl(PropertiesUtil.getPropertieValue(JDBC_PRO_PATH, urlKey));
    ((DruidDataSource)dataSource).setUsername(PropertiesUtil.getPropertieValue(JDBC_PRO_PATH, userNameKey));
    ((DruidDataSource)dataSource).setPassword(PropertiesUtil.getPropertieValue(JDBC_PRO_PATH, pwdKey));
    return new DataSourceProxy(dataSource);
}
 
Example #25
Source File: EtDataSourceManager.java    From EasyTransaction with Apache License 2.0 4 votes vote down vote up
@Override
public void registerResource(Resource resource) {
    DataSourceProxy dataSourceProxy = (DataSourceProxy) resource;
    getManagedResources().put(dataSourceProxy.getResourceId(), dataSourceProxy);
}
 
Example #26
Source File: EtDataSourceManager.java    From EasyTransaction with Apache License 2.0 4 votes vote down vote up
private <R> R executeInTransaction(String resourceId, ExecuteWithConn<R> execute) throws TransactionException {
    
    
    DataSourceProxy dataSourceProxy = get(resourceId);

    Connection conn = null;
    PreparedStatement selectPST = null;
    try {
        
        conn = dataSourceProxy.getPlainConnection();

        // The entire undo process should run in a local transaction.
        conn.setAutoCommit(false);

        R r = execute.execute(conn);

        conn.commit();
        
        return r;

    } catch (Throwable e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException rollbackEx) {
                LOGGER.warn("Failed to close JDBC resource ... ", rollbackEx);
            }
        }
        throw new TransactionException(TransactionExceptionCode.BranchRollbackFailed_Retriable, e);

    } finally {
        try {
            if (selectPST != null) {
                selectPST.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException closeEx) {
            LOGGER.warn("Failed to close JDBC resource ... ", closeEx);
        }
    }
}
 
Example #27
Source File: SeataConfiguration.java    From spring-boot-samples with Apache License 2.0 4 votes vote down vote up
@Primary
@Bean("dataSource")
public DataSourceProxy dataSource(DataSource hikariDataSource) {
    return new DataSourceProxy(hikariDataSource);
}
 
Example #28
Source File: EasyTransTestConfiguration.java    From EasyTransaction with Apache License 2.0 4 votes vote down vote up
@Bean
public DataSource useCoupon(EasyTransTestProperties properties){
    //use fescar proxy
    return new DataSourceProxy(createDatasource(properties));
}
 
Example #29
Source File: SeataConfiguration.java    From spring-boot-samples with Apache License 2.0 4 votes vote down vote up
@Primary
@Bean("dataSource")
public DataSourceProxy dataSource(DataSource hikariDataSource) {
    return new DataSourceProxy(hikariDataSource);
}
 
Example #30
Source File: JbootSeataManager.java    From jboot with Apache License 2.0 4 votes vote down vote up
public DataSource wrapDataSource(DataSource dataSource) {
    return config.isEnable() && config.isConfigOk()
            ? new DataSourceProxy(dataSource)
            : dataSource;
}