コード例 #1
0
  /**
   * Each shard have a database connection, the worker thread may concurrently use a shard
   * connection executing SQL (such as executing ddl statement), If the JDBC driver is
   * spec-compliant, then technically yes, the object is thread-safe, MySQL Connector/J, all methods
   * to execute statements lock the connection with a synchronized block.
   *
   * @param options
   * @return
   */
  protected Connection getConnectionWithStrategy(Options options) {
    String shardName = options.shardName;
    Connection conn;
    switch (holderStrategy) {
      case STRICTLY:
        if (connectionMap.isEmpty()) {
          conn = getRawConnection(options);
          connectionMap.put(shardName, conn);
        } else {
          conn = connectionMap.get(shardName);
          if (conn == null) {
            String lastTransactionNode = connectionMap.keySet().iterator().next();
            throw DbException.get(
                ErrorCode.GENERAL_ERROR_1,
                "STRICTLY transaction mode not supported operation on multi-node, opend on "
                    + lastTransactionNode
                    + " and try on "
                    + shardName);
          }
        }
        break;
      case ALLOW_CROSS_SHARD_READ:
        if (options.readOnly) {
          conn = connectionMap.get(shardName);
          if (conn == null) {
            conn = getRawConnectionForReadOnly(options);
          }
        } else {
          if (connectionMap.isEmpty()) {
            conn = getRawConnection(options);
            connectionMap.put(shardName, conn);
          } else {
            conn = connectionMap.get(shardName);
            if (conn == null) {
              String lastTransactionNode = connectionMap.keySet().iterator().next();
              throw DbException.get(
                  ErrorCode.GENERAL_ERROR_1,
                  "ALLOW_READ_CROSS_DB transaction mode not supported writing operation on multi-node, opend on "
                      + lastTransactionNode
                      + " and try on "
                      + shardName);
            }
          }
        }

        break;

      case BESTEFFORTS_1PC:
        conn = connectionMap.get(shardName);
        if (conn == null) {
          conn = getRawConnection(options);
          connectionMap.put(shardName, conn);
        }
        break;

      default:
        throw DbException.getInvalidValueException("transactionMode", holderStrategy);
    }
    return conn;
  }
コード例 #2
0
 private HolderStrategy transactionMode(String mode) {
   try {
     HolderStrategy holderStrategy =
         StringUtils.isNullOrEmpty(mode)
             ? HolderStrategy.BESTEFFORTS_1PC
             : HolderStrategy.valueOf(mode);
     return holderStrategy;
   } catch (Exception e) {
     throw DbException.getInvalidValueException("transactionMode", mode);
   }
 }