我正在做Heroku教程https://devcenter.heroku.com/articles/getting-started-with-gradle-on-heroku,在我无法在本地实例中运行数据库之前,一切都很好。
我在intelij和控制台中进行了尝试(构建gradlew之后为$ heroku本地网站)。我尝试将db从Heroku复制到本地postgresDb,但也失败了。
@Value("${spring.datasource.url}")
private String dbUrl;
@Autowired
private DataSource dataSource;
@RequestMapping("/db")
String db(Map<String, Object> model) {
try (Connection connection = dataSource.getConnection()) {
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add("Read from DB: " + rs.getTimestamp("tick"));
}
model.put("records", output);
return "db";
} catch (Exception e) {
model.put("message", e.getMessage());
return "error";
}
}
@Bean
public DataSource dataSource() throws SQLException, URISyntaxException {
if (dbUrl == null || dbUrl.isEmpty()) {
return new HikariDataSource();
} else {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dbUrl);
return new HikariDataSource(config);
}
}
我还尝试从Heroku配置中接收dbUrl
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath() + "?sslmode=require";
进入/ db页面后,我收到HikariPool-1 - dataSource or dataSourceClassName or jdbcUrl is required.
我在做什么错了?
答案 0 :(得分:2)
使用教程中的@Bean。您必须从heroku复制(或只是创建).env文件并添加连接字符串,因为它最初不是存储在其中,但heroku像对待它一样。
heroku run echo $JDBC_DATABASE_URL
JDBC_DATABASE_URL="your_conecction_string_copied_from_console"
粘贴到项目中的.env文件中。heroku local web
Windows的快捷脚本:
echo|set /p="JDBC_DATABASE_URL=" | heroku run echo $JDBC_DATABASE_URL >> .env