postgresql 从 Spring Boot 连接到 Heroku Postgres
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33633243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connecting to Heroku Postgres from Spring Boot
提问by Jonik
I'm looking for the simplest, cleanest way of connecting to Heroku Postgresin a Spring Bootapp 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). This approach seems to work fine.
我正在使用Profiles,这似乎与我想要的很匹配:在 HerokuSPRING_PROFILES_ACTIVE
上设置为postgres
,而在本地开发中spring.profiles.active
是h2
使用 H2 内存数据库(此处省略其配置)。这种方法似乎工作正常。
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:
DataSource
from Tomcat 似乎是一个不错的选择,因为默认依赖项包括它,并且因为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 notinclude 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 documentationoffers "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
Commons DBCP与 Spring Boot 一起使用。但对我来说,这似乎不是最干净的选择,因为默认依赖项不包括 Commons DBCP。总的来说,我想知道 Apache Commons 是否真的可以,在2015 年,是连接到 Postgres 的推荐方式...... Heroku 文档也BasicDataSource
为这种场景提供了“在 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$3388c1 : 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 isin use (without this it was failing with "Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set").
在日志中,我看到 mypostgresDataSource
被调用得很好,并且 PostgreSQLDialect正在使用中(如果没有这个,它就会失败,“当'hibernate.dialect' 未设置时,对 DialectResolutionInfo 的访问不能为空”)。
My specific questions
我的具体问题
- Well, how to get this working? I amsetting
spring.datasource.driverClassName
, so why "Not loading a JDBC driver as driverClassName property is null"? - Is the use of Tomcat's
DataSource
fine or would you recommend something else? - Is it mandatory to define
postgresql
dependency as above with a specific version? (I was getting "no suitable driver found" error without this.) - Is there a simpler way to do all this (while sticking to Java code and/or properties; no XML please)?
- 那么,如何让这个工作?我正在设置
spring.datasource.driverClassName
,那么为什么“未加载 JDBC 驱动程序,因为 driverClassName 属性为空”? - 使用Tomcat的
DataSource
好还是你推荐别的东西? - 是否必须
postgresql
使用特定版本定义上述依赖项?(如果没有这个,我会收到“找不到合适的驱动程序”错误。) - 有没有更简单的方法来完成所有这些(同时坚持使用 Java 代码和/或属性;请不要使用 XML)?
采纳答案by jonashackt
Simplest cleanest way for Spring Boot 2.x with Heroku & Postgres
使用 Heroku 和 Postgres 的 Spring Boot 2.x 最简单最干净的方法
I read all answers, but didn′t find what Jonikwas 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 databasefor staging and production on Heroku.
大多数人希望与 Spring Boot 和 Heroku 一起使用的开发过程包括用于测试和快速开发周期的本地 H2 内存数据库 - 以及用于在 Heroku 上登台和生产的Heroku Postgres 数据库。
- First thing is - you don′t need to use Spring profiles for that!
- Second: You don′t need to write/change any code!
- 首先是 - 您不需要为此使用 Spring 配置文件!
- 第二:您无需编写/更改任何代码!
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。
The pom.xml
pom.xml
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
,但我们稍后会介绍。
Configure Environment Variables on Heroku
在 Heroku 上配置环境变量
In Heroku Environment Variables are named 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).
在 Heroku 中,环境变量被命名为Config Vars
. 你没听错,我们要做的就是配置环境变量!我们只需要正确的。因此,请访问https://data.heroku.com/(我假设已经为您的 Heroku 应用程序配置了一个 Postgres 数据库,这是默认行为)。
Now click on your application′s corresponding Datastore
and switch over to the Settings
tab. Then click on View Credentials...
, which should look something similar like this:
现在单击您的应用程序的相应Datastore
并切换到Settings
选项卡。然后点击View Credentials...
,它应该看起来像这样:
Now open a new browser tab and go to your Heroku application′s Settings
tab also. Click on Reveal Config Vars
and create the following Environment Variables:
现在打开一个新的浏览器选项卡,也转到您的 Heroku 应用程序Settings
选项卡。单击Reveal Config Vars
并创建以下环境变量:
SPRING_DATASOURCE_URL
= jdbc:postgresql://YourPostgresHerokuHostNameHere:5432/YourPostgresHerokuDatabaseNameHere(mind the leadingjdbc:
and theql
addition topostgres
!)SPRING_DATASOURCE_USERNAME
= YourPostgresHerokuUserNameHereSPRING_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_JPA_DATABASE-PLATFORM
=org.hibernate.dialect.PostgreSQLDialect
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 withCREATE
SQL statements or DDL files)
SPRING_DATASOURCE_URL
= jdbc:postgres ql:// YourPostgresHerokuHostNameHere:5432/ YourPostgresHerokuDatabaseNameHere(注意前导jdbc:
和ql
添加postgres
!)SPRING_DATASOURCE_USERNAME
= YourPostgresHerokuUserNameHereSPRING_DATASOURCE_PASSWORD
= YourPostgresHerokuPasswordHereSPRING_DATASOURCE_DRIVER-CLASS-NAME
=org.postgresql.Driver
(这并不总是需要的,因为 Spring Boot 可以从 url 为大多数数据库推断它,只是为了完整起见)SPRING_JPA_DATABASE-PLATFORM
=org.hibernate.dialect.PostgreSQLDialect
SPRING_DATASOURCE_TYPE
=org.apache.tomcat.jdbc.pool.DataSource
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 连接。
Just if you′re asking: Why do we configure Tomcat JDBC instead of Hikari
就像你问:为什么我们配置Tomcat JDBC而不是Hikari
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. There′s only a slight hint in the docs about thissaying
您可能已经注意到,我们将tomcat-jdbc
依赖项添加到我们的 pom.xml 并配置SPRING_DATASOURCE_TYPE=org.apache.tomcat.jdbc.pool.DataSource
为环境变量。关于这句话的文档中只有一点提示
You can bypass that algorithm completely and specify the connection pool to use by setting the spring.datasource.type property. This is especially important if you run your application in a Tomcat container, ...
您可以完全绕过该算法并通过设置 spring.datasource.type 属性来指定要使用的连接池。如果您在 Tomcat 容器中运行应用程序,这一点尤其重要,...
There are several reasons I switched back to Tomcat pooling DataSource instead of using the Spring Boot 2.x standard 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. And the problem with Hikari is, that it only supports spring.datasource.jdbc-url
.
我切换回 Tomcat 池化数据源而不是使用 Spring Boot 2.x 标准 HikariCP 有几个原因。正如我已经在这里解释的那样,如果您不指定spring.datasource.url
,Spring 将尝试自动连接嵌入式内存 H2 数据库而不是我们的 PostgreSQL 数据库。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. Remember: We were looking for the simplest, cleanest way of connecting to Heroku Postgres in a Spring Boot app using JPA/Hibernate!
所以我没有让 Spring Boot 2.x 使用 HikariCP 在 Heroku 和 Postgres 上工作,而是使用 Tomcat JDBC - 而且我也不想中断包含预先描述的本地 H2 数据库的开发过程。请记住:我们正在寻找使用 JPA/Hibernate 在 Spring Boot 应用程序中连接到 Heroku Postgres 的最简单、最干净的方法!
回答by sparkyspider
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. They are:
除了DATABASE_URL
始终存在的 ,Heroku 在运行时创建 3 个环境变量。他们是:
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. Here is an example of my application.properties
您可能知道,如果 Spring Bootspring.datasource.*
在您的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(spring-boot-starter-jpa
与 PostgreSQL捆绑在一起,因此我需要在我的build.gradle
.
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile('org.postgresql:postgresql:9.4.1212')
}
回答by Jonik
To get the database connection working (in a stable manner) two things were missing in the setup I described in the question:
为了使数据库连接正常工作(以稳定的方式),我在问题中描述的设置中缺少两件事:
- As jny pointed out, I needed to set JDBC driver explicitly:
dataSource.setDriverClassName("org.postgresql.Driver");
- (The reason for this is that I'm defining a custom datasource, overriding Spring's default, causing my
spring.datasource.driverClassName
property to have no effect. And to my understanding, due to the dynamic nature of Heroku'sDATABASE_URL
, I need custom datasource to make it work.)
- After this the connection worked, but it wasn't stable; I started getting
org.postgresql.util.PSQLException: This connection has been closed.
after the app had been running for a while. A somewhat surprising solution(based on this answer) was to enable certain tests such astestOnBorrow
on the Tomcat DataSource:dataSource.setTestOnBorrow(true); dataSource.setTestWhileIdle(true); dataSource.setTestOnReturn(true); dataSource.setValidationQuery("SELECT 1");
- 正如 jny 指出的,我需要明确设置 JDBC 驱动程序:
dataSource.setDriverClassName("org.postgresql.Driver");
- (这样做的原因是我正在定义一个自定义数据源,覆盖 Spring 的默认值,导致我的
spring.datasource.driverClassName
属性无效。据我所知,由于Heroku 的动态特性DATABASE_URL
,我需要自定义数据源才能使其工作。)
- 此后连接工作,但不稳定;
org.postgresql.util.PSQLException: This connection has been closed.
在应用程序运行了一段时间后,我开始了。一个有点令人惊讶的解决方案(基于这个答案)是启用某些测试,例如testOnBorrow
在 Tomcat 数据源上: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
). ApparentlyBasicDataSource (Commons DBCP) has more sensible defaults. But as mentiond in the question, I rather used something that comes with Spring Boot by default, especially as it's strongly endorsedin the reference guide.
现在,我遇到的两个问题可能都特定于来自 Tomcat( org.apache.tomcat.jdbc.pool
)的数据源。显然BasicDataSource (Commons DBCP) 有更合理的默认值。但是正如问题中所提到的,我宁愿默认使用 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 个问题!
Using JDBC_DATABASE_*
variables instead
使用JDBC_DATABASE_*
变量代替
Update: Note that using JDBC_DATABASE_*
is much simpler than the above, as pointed out in this answer. For a long time I was under the impression that DATABASE_URL
should be preferred, but nowadays I'm not so sure anymore.
更新:请注意JDBC_DATABASE_*
,正如本答案中所指出的,使用比上面的要简单得多。很长一段时间我都认为DATABASE_URL
应该优先考虑,但现在我不再那么确定了。
回答by Vic Seedoubleyew
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.
如果您需要在构建脚本和应用程序逻辑中访问数据库,这将更加有用。看看这里的原因。
Usage:
用法:
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();
回答by smooth_smoothie
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. You can see the raw values by running heroku run env
3.) 将本地 application.properties 更改为硬编码。您可以通过运行查看原始值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!
这是我必须让我的应用程序的本地副本工作的原因。如果有人找到更好的方法,请分享!
回答by logixplayer
@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();
}
}
回答by codefinger
Try using JDBC_DATABASE_URLas 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 应该没问题。