百度智能云

All Product Document

          Cloud-Native Application Platform CNAP

          Distributed Transaction Access

          Preparation

          • Download Maven in the development environment and configure the environment.
          • Install JDK1.8 in the development environment and complete the environment configuration (currently only supports version 1.8)
          • Currently, only the combination with the Tianhe microservice platform is supported. Please refer to the "Spring-Cloud-Application Access" document for access
          • Install the distributed transaction-related jar package into Maven in the development environment: Download transaction dependency package and install it based on README in the compressed package

          Introduce Dependencies

          Modify the pom.xml file and introduce the required maven dependencies according to the usage scenarios.

          <!--Access between services via rest --> 
          <dependency>
              <groupId>com.baidu.btcc</groupId>
              <artifactId>btcc-rest-template</artifactId>
              <version>2.3.0-SNAPSHOT</version>
          </dependency>
          <!--Access between services via feign--> 
          <dependency>
              <groupId>com.baidu.btcc</groupId>
              <artifactId>btcc-spring-cloud</artifactId>
              <version>2.3.0-SNAPSHOT</version>
          </dependency>

          Add Configuration Items

          Add the following configuration to application.properties to upload transaction data.

          # Name of the module to which the transaction belongs 
          btcc.moduleName=xxxx
          # User authentication information, which can be viewed and updated through the console 
          btcc.token=xxxx
          # Transaction grouping, which needs to be managed through the console 
          btcc.transGroup=xxxx
          # Upload address of transaction data 
          btcc.serverAddress=list://100.64.253.71:8024
          # Perform operations of confirm and cancel synchronously/asynchronously; true indicates synchronization, and false indicates asynchronous 
          btcc.isSync=false
          # Timeout for connecting btcc-server 
          btcc.connectTimeoutMillis=200
          # Read timeout for accessing btcc-server 
          btcc.readTimeoutMillis=1000
          # Write timeout for accessing btcc-server 
          btcc.writeTimeoutMillis=200
          # Maximum number of connections to btcc-server 
          btcc.maxTotalConnections=1000
          # Minimum number of idle connections to btcc-server 
          btcc.minIdleConnections=10
          # Maximum number of retries to access btcc-server 
          btcc.maxTryTimes=3
          # Number of worker threads accessing btcc-server 
          btcc.workThreadNum=10

          Enable Transactions

          To enable the distributed transaction function, additional configuration needs to be added to the code:

          • Turn on scanning of com.baidu.btcc
          • Parse btcc configuration to ensure that BtccConfig objects are available
          • Set interceptors for RestTemplate and AsyncRestTemplate

          The modified code example is shown below.

          @SpringBootApplication
          @EnableFeignClients
          @EnableDiscoveryClient
          @ComponentScan(basePackages = "com.baidu.btcc")
          public class OrderApplication {
              @Bean
              @ConfigurationProperties("btcc")
              public BtccConfig btccConfig() {
                  return new BtccConfig();
              }
           
              @LoadBalanced
              @Bean
              public RestTemplate restTemplate() {
                  RestTemplate restTemplate = new RestTemplate();
                  restTemplate.setInterceptors(Lists.newArrayList(new BtccRestTemplateInterceptor()));
                  return restTemplate;
              }
           
              @LoadBalanced
              @Bean
              public AsyncRestTemplate asyncRestTemplate(){
                  AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
                  asyncRestTemplate.setInterceptors(Lists.newArrayList(new BtccRestTemplateAsyncInterceptor()));
                  return asyncRestTemplate;
              }
           
              public static void main(String[] args) {
                  SpringApplication.run(OrderApplication.class, args);
              }
          }

          Service Transformation

          Add annotations to the try methods of the transaction initiator and transaction participant to create a transaction message:

          @BtccTransactional(confirmMethod = "", cancelMethod = "", mode="")

          Among them,

          • confirmMethod represents the transaction confirmation function, which is empty by default.
          • cancelMethod represents the transaction cancellation function, which is empty by default.
          • mode indicates the transaction mode. It is optional. The default is MT (MT means manual rollback, AT means automatic rollback).

          Note:

          • @BtccTransactional can guarantee local transactions, so there is no need to explicitly add spring's @Transactional annotation.
          • For the transaction initiator, there is generally no need to set confirmMethod or cancelMethod.
          • For the transaction participant, cancelMethod must be provided in MT mode to ensure that a rollback can be performed when a transaction fails.
          • The try/confirm/cancel methods must be defined in the interface, and @BtccTransactional is added to the implementation method.
          • The same try/confirm/cancel methods must have the same input parameters.

          AT mode

          1.Configure the data source proxy

          Use the com.baidu.btcc.client.datasource.DataSourceProxy provided by btcc. The code example is as follows.

          @Configuration
          @PropertySource("classpath:application.properties")
          public class DatabaseConfig {
              @Value("${spring.datasource.url}")
              private String jdbcUrl;
              @Value("${spring.datasource.username}")
              private String username;
              @Value("${spring.datasource.password}")
              private String password;
              // Other configuration items 
           
              @Bean
              public DataSource dataSource() throws SQLException {
                  HikariDataSource dataSource = new HikariDataSource();
                  dataSource.setJdbcUrl(jdbcUrl);
                  dataSource.setUsername(username);
                  dataSource.setPassword(password);
                  // Set other configuration items 
                  return new DataSourceProxy(dataSource);
              }
          }

          2.Create database table

          Create undo_log and btcc_global_lock tables in the database. For the SQL statements required to create the tables, please refer to Transaction Dependency Package .

          3.Service use

          Add annotation @BtccTransactional (mode="AT") to the transaction initiator and participant.

          Note:

          Currently AT mode only supports mysql database 
          AT mode is suitable for relatively simple SQL. If the cancel scenario is complicated, MT mode is recommended.
          Previous
          Image Production
          Next
          Configuration Center Access