View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.infra.session.connection.transaction;
19  
20  import lombok.Getter;
21  import lombok.Setter;
22  
23  import java.util.Optional;
24  
25  /**
26   * Transaction connection context.
27   */
28  @Getter
29  public final class TransactionConnectionContext implements AutoCloseable {
30      
31      private volatile String transactionType;
32      
33      private volatile boolean inTransaction;
34      
35      @Setter
36      private volatile long beginMills;
37      
38      @Setter
39      private volatile boolean exceptionOccur;
40      
41      @Setter
42      private volatile String readWriteSplitReplicaRoute;
43      
44      /**
45       * Begin transaction.
46       *
47       * @param transactionType transaction type 
48       */
49      public void beginTransaction(final String transactionType) {
50          this.transactionType = transactionType;
51          inTransaction = true;
52      }
53      
54      /**
55       * Judge is in distributed transaction or not.
56       *
57       * @return in distributed transaction or not
58       */
59      public boolean isInDistributedTransaction() {
60          return inTransaction && ("XA".equals(transactionType) || "BASE".equals(transactionType));
61      }
62      
63      /**
64       * Get transaction type. 
65       *
66       * @return transaction type
67       */
68      public Optional<String> getTransactionType() {
69          return Optional.ofNullable(transactionType);
70      }
71      
72      /**
73       * Get read write split replica route. 
74       *
75       * @return read write split replica route
76       */
77      public Optional<String> getReadWriteSplitReplicaRoute() {
78          return Optional.ofNullable(readWriteSplitReplicaRoute);
79      }
80      
81      @Override
82      public void close() {
83          transactionType = null;
84          inTransaction = false;
85          beginMills = 0L;
86          exceptionOccur = false;
87          readWriteSplitReplicaRoute = null;
88      }
89  }