[英]Connecting to Heroku Postgres from Spring Boot
I'm looking for the simplest , cleanest way of connecting to Heroku Postgres in a Spring Boot app using JPA/Hibernate.我正在寻找使用 JPA/Hibernate 在Spring Boot应用程序中连接到Heroku Postgres的最简单、最干净的方法。
I don't see a good, complete example for this combo in either Heroku or Spring Boot documentation, so I'd like to document this on Stack Overflow.我在 Heroku 或 Spring Boot 文档中都没有看到这个组合的好的、完整的例子,所以我想在 Stack Overflow 上记录这个。
I'm trying to go with something like this:我正在尝试使用这样的方法:
@Configuration
public class DataSourceConfig {
Logger log = LoggerFactory.getLogger(getClass());
@Bean
@Profile("postgres")
public DataSource postgresDataSource() {
String databaseUrl = System.getenv("DATABASE_URL")
log.info("Initializing PostgreSQL database: {}", databaseUrl);
URI dbUri;
try {
dbUri = new URI(databaseUrl);
}
catch (URISyntaxException e) {
log.error(String.format("Invalid DATABASE_URL: %s", databaseUrl), e);
return null;
}
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':'
+ dbUri.getPort() + dbUri.getPath();
// fully-qualified class name to distuinguish from javax.sql.DataSource
org.apache.tomcat.jdbc.pool.DataSource dataSource
= new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setUrl(dbUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
I'm using Profiles , which seems a good match for what I want: on Heroku SPRING_PROFILES_ACTIVE
is set to postgres
, while in local development spring.profiles.active
is h2
to use a H2 in-memory database (whose config omitted here).我正在使用Profiles ,这似乎与我想要的很匹配:在 Heroku 上
SPRING_PROFILES_ACTIVE
设置为postgres
,而在本地开发中spring.profiles.active
是h2
以使用 H2 内存数据库(此处省略其配置)。 This approach seems to work fine.这种方法似乎工作正常。
In application-postgres.properties
( profile-specific properties ):在
application-postgres.properties
( 特定于配置文件的属性)中:
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driverClassName=org.postgresql.Driver
DataSource
from Tomcat seemed like a good option since the default dependencies include it, and because Spring Boot reference guide says :来自 Tomcat 的
DataSource
似乎是一个不错的选择,因为默认依赖项包括它,并且因为Spring Boot 参考指南说:
We prefer the Tomcat pooling DataSource for its performance and concurrency, so if that is available we always choose it.
我们更喜欢 Tomcat 池数据源的性能和并发性,因此如果可用,我们总是选择它。
(I'm also seeing BasicDataSource
from Commons DBCP being used with Spring Boot . But to me this does not seem like the cleanest choice as the default dependencies do not include Commons DBCP. And in general I'm wondering if Apache Commons could really , in 2015, be the recommended way to connect to Postgres... Also Heroku documentation offers " BasicDataSource
in Spring" for this kind of scenario; I assume this refers to Commons DBCP, since I don't see such class in Spring itself.) (我也看到
BasicDataSource
从下议院DBCP 正在使用Spring启动时使用。但对我来说这似乎不是最干净的选择作为默认的依赖不包括下议院DBCP。而在一般情况我想知道如果Apache下议院可能真的,在 2015 年,成为连接到 Postgres 的推荐方式...... Heroku 文档还为这种场景提供了“ BasicDataSource
in Spring”;我假设这是指 Commons DBCP,因为我在 Spring 本身中没有看到这样的类。)
Dependencies:依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1205-jdbc42</version>
</dependency>
Current status : failing with "Not loading a JDBC driver as driverClassName property is null":当前状态:失败并显示“未加载 JDBC 驱动程序,因为 driverClassName 属性为空”:
eConfig$$EnhancerBySpringCGLIB$$463388c1 : Initializing PostgreSQL database: postgres:[...]
j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
[...]
o.a.tomcat.jdbc.pool.PooledConnection : Not loading a JDBC driver as driverClassName property is null.
o.a.tomcat.jdbc.pool.PooledConnection : Not loading a JDBC driver as driverClassName property is null.
[...]
org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
In logs I see that my postgresDataSource
is called just fine, and that PostgreSQLDialect is in use (without this it was failing with "Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set").在日志中,我看到我的
postgresDataSource
被调用得很好,并且 PostgreSQLDialect正在使用中(如果没有这个,它就会失败,“当'hibernate.dialect'未设置时,对 DialectResolutionInfo 的访问不能为空”)。
My specific questions我的具体问题
spring.datasource.driverClassName
, so why "Not loading a JDBC driver as driverClassName property is null"?spring.datasource.driverClassName
,那么为什么“未加载 JDBC 驱动程序作为 driverClassName 属性为空”?DataSource
fine or would you recommend something else?DataSource
是否DataSource
或者您会推荐其他东西吗?postgresql
dependency as above with a specific version ?postgresql
依赖项? (I was getting "no suitable driver found" error without this.) I read all answers, but didn´t find what Jonik was looking for:我阅读了所有答案,但没有找到Jonik正在寻找的内容:
I'm looking for the simplest, cleanest way of connecting to Heroku Postgres in a Spring Boot app using JPA/Hibernate
我正在寻找使用 JPA/Hibernate 在 Spring Boot 应用程序中连接到 Heroku Postgres 的最简单、最干净的方法
The development process most people want to use with Spring Boot & Heroku includes a local H2 in-memory database for testing & fast development cycles - and the Heroku Postgres database for staging and production on Heroku.大多数人希望与 Spring Boot 和 Heroku 一起使用的开发过程包括用于测试和快速开发周期的本地 H2 内存数据库 - 以及用于在 Heroku 上登台和生产的Heroku Postgres 数据库。
Let´s have a look on what we have to do step by step.让我们一步一步来看看我们必须做的事情。 I have a example project in place that provides a fully working Heroku deployment and configuration for Postgres - only for the sake of completeness, if you want to test it yourself: github.com/jonashackt/spring-boot-vuejs .
我有一个示例项目,它为 Postgres 提供了一个完全有效的 Heroku 部署和配置——只是为了完整性,如果你想自己测试它: github.com/jonashackt/spring-boot-vuejs 。
We need the following depencencies:我们需要以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- In-Memory database used for local development & testing -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Switch back from Spring Boot 2.x standard HikariCP to Tomcat JDBC,
configured later in Heroku (see https://stackoverflow.com/a/49970142/4964553) -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<!-- PostgreSQL used in Staging and Production environment, e.g. on Heroku -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
</dependency>
One tricky thing here is the usage of tomcat-jdbc
, but we´ll cover that in a second.这里有一个棘手的事情是
tomcat-jdbc
的使用,但我们稍后会介绍。
In Heroku Environment Variables are named Config Vars
.在 Heroku 中,环境变量被命名为
Config Vars
。 You heard right, all we have to do is to configure Enviroment Variables!你没听错,我们要做的就是配置环境变量! We just need the correct ones.
我们只需要正确的。 Therefore head over to https://data.heroku.com/ (I assume there´s already a Postgres database configured for your Heroku app, which is the default behavior).
因此,请访问https://data.heroku.com/ (我假设已经为您的 Heroku 应用程序配置了 Postgres 数据库,这是默认行为)。
Now click on your application´s corresponding Datastore
and switch over to the Settings
tab.现在单击您的应用程序相应的
Datastore
并切换到Settings
选项卡。 Then click on View Credentials...
, which should look something similar like this:然后单击
View Credentials...
,它应该看起来像这样:
Now open a new browser tab and go to your Heroku application´s Settings
tab also.现在打开一个新的浏览器选项卡并转到您的 Heroku 应用程序的
Settings
选项卡。 Click on Reveal Config Vars
and create the following Environment Variables:单击
Reveal Config Vars
变量并创建以下环境变量:
SPRING_DATASOURCE_URL
= jdbc :postgres ql :// YourPostgresHerokuHostNameHere :5432/ YourPostgresHerokuDatabaseNameHere (mind the leading jdbc:
and the ql
addition to postgres
!) SPRING_DATASOURCE_URL
= jdbc :postgres ql :// YourPostgresHerokuHostNameHere :5432/ YourPostgresHerokuDatabaseNameHere (注意领先的jdbc:
和ql
添加到postgres
!)SPRING_DATASOURCE_USERNAME
= YourPostgresHerokuUserNameHere SPRING_DATASOURCE_USERNAME
= YourPostgresHerokuUserNameHereSPRING_DATASOURCE_PASSWORD
= YourPostgresHerokuPasswordHere SPRING_DATASOURCE_PASSWORD
= YourPostgresHerokuPasswordHereSPRING_DATASOURCE_DRIVER-CLASS-NAME
= org.postgresql.Driver
(this isn´t always needed since Spring Boot can deduce it for most databases from the url , just for completeness here) SPRING_DATASOURCE_DRIVER-CLASS-NAME
= org.postgresql.Driver
(这并不总是需要的, 因为 Spring Boot 可以从 url 为大多数数据库推断它,只是为了完整SPRING_DATASOURCE_DRIVER-CLASS-NAME
)SPRING_JPA_DATABASE-PLATFORM
= org.hibernate.dialect.PostgreSQLDialect
SPRING_JPA_DATABASE-PLATFORM
= org.hibernate.dialect.PostgreSQLDialect
SPRING_DATASOURCE_TYPE
= org.apache.tomcat.jdbc.pool.DataSource
SPRING_DATASOURCE_TYPE
= org.apache.tomcat.jdbc.pool.DataSource
SPRING_JPA_HIBERNATE_DDL-AUTO
= update
(this will automatically create your tables according to your JPA entities, which is really great - since you don´t need to hurdle with CREATE
SQL statements or DDL files) SPRING_JPA_HIBERNATE_DDL-AUTO
= update
(这将根据您的 JPA 实体自动创建您的表,这真的很棒 - 因为您不需要使用CREATE
SQL 语句或 DDL 文件) In Heroku this should look like this:在 Heroku 中,这应该是这样的:
Now that´s all you have to do!现在,这就是您所要做的! Your Heroku app is restarted every time you change a Config Variable - so your App should now run H2 locally, and should be ready connected with PostgreSQL when deployed on Heroku.
每次更改配置变量时,您的 Heroku 应用程序都会重新启动 - 因此您的应用程序现在应该在本地运行 H2,并且在 Heroku 上部署时应该准备好与 PostgreSQL 连接。
As you might noticed, we added the tomcat-jdbc
dependency to our pom.xml and configured SPRING_DATASOURCE_TYPE=org.apache.tomcat.jdbc.pool.DataSource
as a Environment variable.您可能已经注意到,我们在 pom.xml 中添加了
tomcat-jdbc
依赖项,并将SPRING_DATASOURCE_TYPE=org.apache.tomcat.jdbc.pool.DataSource
配置为环境变量。 There´s only a slight hint in the docs about this saying 关于这句话的文档中只有一点提示
You can bypass that algorithm completely and specify the connection pool to use by setting the spring.datasource.type property.
您可以完全绕过该算法并通过设置 spring.datasource.type 属性来指定要使用的连接池。 This is especially important if you run your application in a Tomcat container, ...
如果您在 Tomcat 容器中运行您的应用程序,这一点尤其重要,...
There are several reasons I switched back to Tomcat pooling DataSource instead of using the Spring Boot 2.x standard HikariCP.我切换回 Tomcat 池化数据源而不是使用 Spring Boot 2.x 标准 HikariCP 有几个原因。 As I already explained here , if you don´t specifiy
spring.datasource.url
, Spring will try to autowire the embedded im-memory H2 database instead of our PostgreSQL one.正如我已经在这里解释的那样,如果您不指定
spring.datasource.url
,Spring 将尝试自动连接嵌入式内存 H2 数据库而不是我们的 PostgreSQL 数据库。 And the problem with Hikari is, that it only supports spring.datasource.jdbc-url
. Hikari 的问题是,它只支持
spring.datasource.jdbc-url
。
Second, if I try to use the Heroku configuration as shown for Hikari (so leaving out SPRING_DATASOURCE_TYPE
and changing SPRING_DATASOURCE_URL
to SPRING_DATASOURCE_JDBC-URL
) I run into the following Exception:其次,如果我尝试使用 Hikari 所示的 Heroku 配置(因此省略
SPRING_DATASOURCE_TYPE
并将SPRING_DATASOURCE_URL
更改为SPRING_DATASOURCE_JDBC-URL
),我会遇到以下异常:
Caused by: java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
So I didn´t get Spring Boot 2.x working on Heroku & Postgres with HikariCP, but with Tomcat JDBC - and I also don´t want to brake my development process containing a local H2 database described upfront.所以我没有让 Spring Boot 2.x 使用 HikariCP 在 Heroku 和 Postgres 上工作,而是使用 Tomcat JDBC - 而且我也不想中断包含预先描述的本地 H2 数据库的开发过程。 Remember: We were looking for the simplest, cleanest way of connecting to Heroku Postgres in a Spring Boot app using JPA/Hibernate!
请记住:我们正在寻找使用 JPA/Hibernate 在 Spring Boot 应用程序中连接到 Heroku Postgres 的最简单、最干净的方法!
Simplest Spring Boot / Heroku / Hibernate Configuration最简单的 Spring Boot / Heroku / Hibernate 配置
Apart from DATABASE_URL
, which is always there, Heroku creates 3 environment variables at Runtime.除了始终存在的
DATABASE_URL
之外,Heroku 在运行时创建了 3 个环境变量。 They are:他们是:
JDBC_DATABASE_URL
JDBC_DATABASE_USERNAME
JDBC_DATABASE_PASSWORD
As you may be aware, Spring Boot will automatically configure your database if it finds spring.datasource.*
properties in your application.properties
file.您可能知道,如果 Spring Boot 在您的
application.properties
文件中找到spring.datasource.*
属性,它将自动配置您的数据库。 Here is an example of my application.properties这是我的 application.properties 的示例
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
Hibernate / Postgres Dependencies Hibernate / Postgres 依赖
In my case I'm using Hibernate (bundled in spring-boot-starter-jpa
with PostgreSQL, so I needed the right dependencies in my build.gradle
:就我而言,我使用的是 Hibernate(与 PostgreSQL 捆绑在
spring-boot-starter-jpa
,所以我需要在build.gradle
正确依赖:
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile('org.postgresql:postgresql:9.4.1212')
}
To get the database connection working (in a stable manner) two things were missing in the setup I described in the question:为了使数据库连接正常工作(以稳定的方式),我在问题中描述的设置中缺少两件事:
dataSource.setDriverClassName("org.postgresql.Driver");
spring.datasource.driverClassName
property to have no effect. And to my understanding, due to the dynamic nature of Heroku's DATABASE_URL
, I need custom datasource to make it work.) spring.datasource.driverClassName
属性无效。据我所知,由于Heroku 的DATABASE_URL
的动态特性,我需要自定义数据源使其工作。)org.postgresql.util.PSQLException: This connection has been closed.
org.postgresql.util.PSQLException: This connection has been closed.
after the app had been running for a while.testOnBorrow
on the Tomcat DataSource:testOnBorrow
:
dataSource.setTestOnBorrow(true); dataSource.setTestWhileIdle(true); dataSource.setTestOnReturn(true); dataSource.setValidationQuery("SELECT 1");
So, the fixed version of my DataSourceConfig:所以,我的 DataSourceConfig 的固定版本:
@Configuration
public class DataSourceConfig {
Logger log = LoggerFactory.getLogger(getClass());
@Bean
@Profile("postgres")
public DataSource postgresDataSource() {
String databaseUrl = System.getenv("DATABASE_URL")
log.info("Initializing PostgreSQL database: {}", databaseUrl);
URI dbUri;
try {
dbUri = new URI(databaseUrl);
}
catch (URISyntaxException e) {
log.error(String.format("Invalid DATABASE_URL: %s", databaseUrl), e);
return null;
}
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':'
+ dbUri.getPort() + dbUri.getPath();
org.apache.tomcat.jdbc.pool.DataSource dataSource
= new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl(dbUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestOnBorrow(true);
dataSource.setTestWhileIdle(true);
dataSource.setTestOnReturn(true);
dataSource.setValidationQuery("SELECT 1");
return dataSource;
}
}
With only this in application-postgres.properties
:在
application-postgres.properties
只有这个:
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
Now, both of the problems I had may be specific to the DataSource from Tomcat ( org.apache.tomcat.jdbc.pool
).现在,我遇到的两个问题可能都特定于来自 Tomcat (
org.apache.tomcat.jdbc.pool
) 的数据源。 Apparently BasicDataSource (Commons DBCP) has more sensible defaults. 显然BasicDataSource (Commons DBCP) 有更合理的默认值。 But as mentiond in the question, I rather used something that comes with Spring Boot by default, especially as it's strongly endorsed in the reference guide.
但是正如问题中所提到的,我宁愿默认使用 Spring Boot 附带的东西,特别是因为它在参考指南中得到了强烈认可。
I'm open to competing / simpler / better solutions, so feel free to post, especially if you can address the doubts 2–4 at the end of the question!我对竞争/更简单/更好的解决方案持开放态度,因此请随时发布,特别是如果您可以解决问题末尾的第 2-4 个问题!
JDBC_DATABASE_*
variables instead JDBC_DATABASE_*
变量Update: Note that using JDBC_DATABASE_*
is much simpler than the above, as pointed out in this answer .更新:请注意,正如本答案中所指出的,使用
JDBC_DATABASE_*
比上述方法简单得多。 For a long time I was under the impression that DATABASE_URL
should be preferred, but nowadays I'm not so sure anymore.很长一段时间我都认为
DATABASE_URL
应该是首选,但现在我不再那么确定了。
Try using JDBC_DATABASE_URL as your spring.datasource.url
instead of parsing up DATABASE_URL.尝试使用JDBC_DATABASE_URL作为
spring.datasource.url
而不是解析 DATABASE_URL。
Parsing up DATABASE_URL is recommended, but if you can't get it to work, the JDBC_DATABASE_URL should be fine.推荐解析 DATABASE_URL,但如果你不能让它工作,JDBC_DATABASE_URL 应该没问题。
This is the top answer for googling Postgres problems with the sample Java Application that Heroku provides.这是使用 Heroku 提供的示例 Java 应用程序在谷歌上搜索 Postgres 问题的最佳答案。
These are the steps that I did to get it to work (Win 7).这些是我为使其工作(Win 7)所做的步骤。
1.) The production Server application.properties file will contain the System environments (make sure this file has been committed) 1.) 生产服务器 application.properties 文件将包含系统环境(确保此文件已提交)
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
2.) Now do git update-index --assume-unchanged .\\src\\main\\resources\\application.properties
2.) 现在执行
git update-index --assume-unchanged .\\src\\main\\resources\\application.properties
3.) Change the local application.properties to be hardcoded. 3.) 将本地 application.properties 更改为硬编码。 You can see the raw values by running
heroku run env
您可以通过运行
heroku run env
来查看原始值
spring.datasource.url=jdbc://..
spring.datasource.username=XYZ
spring.datasource.password=ABC
This is what I had to get the local copy of my application to work.这是我必须让我的应用程序的本地副本工作的原因。 If anyone found a better way please do share!
如果有人找到更好的方法,请分享!
@Configuration
@Component
public class HerokuConfigCloud {
private static final Logger logger =
LoggerFactory.getLogger(HerokuConfigCloud .class);
@Bean()
//@Primary this annotation to be used if more than one DB Config was used. In that case,
// using @Primary would give precedence to a the particular "primary" config class
@Profile("heroku")
public DataSource dataSource(
@Value("${spring.datasource.driverClassName}") final String driverClass,
@Value("${spring.datasource.url}") final String jdbcUrl,
@Value("${spring.datasource.username}") final String username,
@Value("${spring.datasource.password}") final String password
) throws URISyntaxException {
return DataSourceBuilder
.create()
.username(username)
.password(password)
.url(url)
.driverClassName(driverClass)
.build();
}
}
I built a library to make this easy: https://github.com/vic-cw/heroku-postgres-helper我建立了一个库来简化这个过程: https : //github.com/vic-cw/heroku-postgres-helper
This is all the more helpful if you need to access the database both in your build script and in your application logic.如果您需要在构建脚本和应用程序逻辑中访问数据库,这将更加有用。 See why here .
看看这里的原因。
build.gradle:构建.gradle:
// If using connection string in build script:
buildscript {
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
classpath 'com.github.vic-cw:heroku-postgres-helper:0.1.0'
}
}
import com.github.viccw.herokupostgreshelper.HerokuPostgresHelper;
// Use connection string in build script:
flyway {
url = HerokuPostgresHelper.getDatabaseJdbcConnectionString()
driver = 'org.postgresql.Driver'
}
// If using connection string inside application logic:
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
compile group: 'com.github.vic-cw', name: 'heroku-postgres-helper', version: '0.1.0'
}
Java application code: Java应用代码:
import com.github.viccw.herokupostgreshelper.HerokuPostgresHelper;
...
String databaseConnectionString = HerokuPostgresHelper.getDatabaseJdbcConnectionString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.