Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java---常用的代码逻辑 #105

Open
AronChung opened this issue Sep 7, 2021 · 0 comments
Open

java---常用的代码逻辑 #105

AronChung opened this issue Sep 7, 2021 · 0 comments
Labels
Projects

Comments

@AronChung
Copy link
Owner

遍历目录找到想要的日志文件

      final File[] files = this.logFile.getParentFile().listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
          return name.startsWith(logFileName);
        }
      });
      Arrays.sort(files, Collections.reverseOrder());

经典的回调函数写法

final SQLTransaction<Integer> transaction = transOperator -> {
      uploadLogFile(transOperator, execId, name, attempt, files, this.defaultEncodingType);
      transOperator.getConnection().commit();
      return 1;
    };
    try {
      this.dbOperator.transaction(transaction);
    } catch (final SQLException e) {
      logger.error("uploadLogFile failed.", e);
      throw new ExecutorManagerException("uploadLogFile failed.", e);
    }


public <T> T transaction(final SQLTransaction<T> operations) throws SQLException {
		Connection conn = null;
		try {
			conn = this.queryRunner.getDataSource().getConnection();
			conn.setAutoCommit(false);
			final DatabaseTransOperator transOperator = new DatabaseTransOperator(this.queryRunner, conn);
			final T res = operations.execute(transOperator);
			conn.commit();
			return res;
		} catch (final SQLException ex) {
			// todo kunkun-tang: Retry logics should be implemented here.
			logger.error("transaction failed", ex);
			if (this.dbMetrics != null) {
				this.dbMetrics.markDBFailTransaction();
			}
			throw ex;
		} finally {
			DbUtils.closeQuietly(conn);
		}
	}


@FunctionalInterface
public interface SQLTransaction<T> {
  public T execute(DatabaseTransOperator transOperator) throws SQLException;
}
@AronChung AronChung added the JAVA label Sep 7, 2021
@AronChung AronChung added this to Java in My Blog Sep 8, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
My Blog
  
Java
Development

No branches or pull requests

1 participant