如何扩展 Corda 节点以使用 H2 以外的数据库?

How can the Corda node be extended to work with databases other than H2?

我有 运行 Corda 和 PostgreSQL。如何扩展 Corda 以与其他数据库一起使用?将数据库驱动程序添加为 Gradle 依赖项并尝试连接到其他数据库是否足够?

Corda 使用 Hibernate 5.x 和 HikariCP JDBC 连接池。

所有查询均由 Hibernate 生成,预计来自 finance 模块的查询(CashSelection 使用 JDBC PreparedStatement 和 SQL 特定于每个数据库供应商)。

正在配置数据库

在运行时,节点会在其 node.conf 文件中查找 JDBC 设置。默认情况下,它连接到嵌入式 H2 服务器(参见 Corda 源代码中的文件 /node/src/main/resources/reference.conf)。

要将 Corda 与其他数据库一起使用(*) 或使用非默认设置连接,node.conf 文件需要设置节点的数据源属性:

dataSourceProperties = {
    dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource"
    dataSource.url = "jdbc:postgresql://[HOST]:[PORT]/postgres"
    dataSource.user = [USER]
    dataSource.password = [PASSWORD]
}
database = {
    transactionIsolationLevel = READ_COMMITTED
}
jarDirs = [PATH_TO_JDBC_DRIVER_DIR]

其中 dataSourceProperties 是典型的 JDBC 设置,database 条目包含 Hibernate 特定设置,jarDirs 是包含驱动程序的目录的路径列表(例如 jarDirs = ['/Library/postgres-lib'])。

在部署节点中配置数据库

您可以通过传递 deployNodes 中的设置来避免手动配置数据库设置。例如:

node {
    name "O=Bank C,L=Tokyo,C=JP"
    p2pPort 10010
    webPort 10011
    rpcSettings {
        address("localhost:10036")
        adminAddress("localhost:10037")
    }
    cordapps = ["$project.group:finance:$corda_release_version"]
    rpcUsers = ext.rpcUsers
    extraConfig = [
        ‘dataSourceProperties.dataSource.url’ : ‘jdbc:postgresql://localhost:32774/postgres’,
        ‘dataSourceProperties.dataSourceClassName’ : ‘org.postgresql.ds.PGSimpleDataSource’,
        ‘dataSourceProperties.dataSource.user’ : ‘postgres’,
        ‘dataSourceProperties.dataSource.password’ : ‘postgres’,
        ‘jarDirs’ : [ ‘/Library/Java/postgres’ ]
    ]
}

添加驱动程序

添加这些设置后,需要在部署节点后将 JDBC 驱动程序添加到 extraConfig.jarDirs 中指定的位置。

另一种方法是在 node/build.gradle 中添加 JDBC 驱动程序依赖项(就像对 PostgreSQL 所做的那样)。只要节点是 compiled/built,它就会包含开箱即用的驱动程序。

(*) Corda Open Source 附带 H2 文件数据库,并且对 Postgres 和 Sql Server 提供实验性支持。 Corda Enterprise 拥有对其他数据库的广泛测试支持,包括 Sql Server、AzureSQL、Postgres 和 Oracle 数据库。尽管使用 Hibernate/JDBC,但某些查询可能需要修改才能在所有支持的数据库中兼容。 Corda Enterprise 支持此兼容性。

补充一下 Joel 的回答: 选项 schema = [SCHEMA] 在 Corda 开源中不可用,一些驱动程序允许在 JDBC URL 字符串中设置当前模式。 对于 Corda 3.X 包含 . 的 dataSourceProperties 键应该用双引号括起来以正确覆盖默认设置(在 https://github.com/corda/corda/issues/4037 中描述)例如

dataSourceProperties = {
    "dataSource.url" = "jdbc:postgresql://[HOST]:[PORT]/postgres"
    ...

或在部署节点中:

extraConfig = [
               'dataSourceProperties': [
                          '"dataSource.url"': 'jdbc:postgresql://localhost:5432/postgres',
                          ...