首页 > 解决方案 > 以编程方式释放数据库 changeloglock

问题描述

我有一个使用 java 的 springboot 应用程序,我想要一个命令行命令来发布 databasechangelogs。

我正在考虑进行查询或仅使用 java 调用 mvn liquibase:releaseLocks 命令。

任何可能性都可行吗?

这就是我运行迁移的方式

  ConfigurableApplicationContext ctx = SpringApplication.run(MigrationsApplication.class, args);
  int exitCode = SpringApplication.exit(ctx, () -> 0);
  logger.info("All migrations were finished with success");
  System.exit(exitCode);

标签: javadatabasespring-bootliquibase

解决方案


正如 Simon 在他的回答中提到的,您可以随时使用 Liquibase Java API 来实现这一点。

此外,我认为不需要明确释放锁。Liquibase 将在成功更新时自动释放它们。

仍然以防万一,您可以参考以下代码块:

//your openConnection logic here
java.sql.Connection connection = openConnection(); 
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));

//This will access your changelog file and create liquibase object
Liquibase liquibase = new liquibase.Liquibase("path/to/changelog.xml", new ClassLoaderResourceAccessor(), database); 

// You can set contexts here to execute required changesets
final Contexts contexts = new Contexts("yourcontext");

// This will execute update on your Database with executing changesets
liquibase.update(contexts, new LabelExpression()); 

// To release locks
liquibase.forceReleaseLocks();

只是一个示例实现(可能有帮助):

public void updateDb(String url, String login, String password, String diffFilePath, String driverClassName) throws Exception{
        Connection c = //create connection from url/login/password/driverClassName;
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        Liquibase liquibase = new liquibase.Liquibase("path/to/changelog.xml", new ClassLoaderResourceAccessor(), database); 
        try {
            liquibase.update(new Contexts("contexts"));
        } catch (SQLException e) {
            throw new DatabaseException(e);
        } finally {
            if (liquibase != null) {
                liquibase.forceReleaseLocks();
            }
            if (c != null) {
                try {
                    c.rollback();
                    c.close();
                } catch (SQLException e) {
                    //nothing to do
                }
            }
        }
}

推荐阅读