简体   繁体   English

如何从Spring Boot连接到在线MongoDB数据库?

[英]How to connect to online MongoDB database from Spring Boot?

I want to connect to an online MongoDB database hosted at Mlab, from inside a Spring Boot application. 我想从Spring Boot应用程序内部连接到Mlab托管的在线MongoDB数据库。

I have configured the application.properties with the URI: 我已经使用URI配置了application.properties:

spring.data.mongodb.uri = mongodb://myuser:mypassword@ds129532.mlab.com:29532/consilium-dev

However, the application still connects to the local MongoDB database. 但是,该应用程序仍连接到本地MongoDB数据库。 How can I make it connect to the Mlab database? 如何使其连接到Mlab数据库?

SOLUTION: The resources folder was not situated in the right folder. 解决方案:资源文件夹不在正确的文件夹中。 It should be in src/java/resources 它应该在src / java / resources中

Using database values in the application.properties didn't work for me for online mongodb. 对于在线mongodb,在application.properties使用数据库值对我不起作用。 It works fine for local db. 它适用于本地数据库。 But Once I google and found an example online where they added it in this way below and it worked for me. 但是,一旦我在Google上搜索并找到一个示例,他们就在下面以这种方式添加了示例,它对我有用。

spring.data.mongodb.uri=mongodb://<USERNAME>:<PASSWORD>@ds261828.mlab.com:61828/springdb.

In my case, spring boot was connecting to the uri specified in application.properties file while testing in my PC but once deployed to heroku, it always connected to the localhost irrespective of what was specified in application.properties . 在我的情况下,Spring Boot在我的PC上进行测试时正在连接到application.properties文件中指定的uri,但一旦部署到heroku,它便始终连接到localhost而不管在application.properties中指定了什么。 Solution was to pass the database uri as command line arguments while deploying the jar to the server because this will take precedence over the properties. 解决方案是在将jar部署到服务器时将数据库uri作为命令行参数传递,因为这将优先于属性。 To do so, create a Procfile like: 为此,创建一个Procfile像:

web: java -Dserver.port=$PORT -Dspring.data.mongodb.uri=mongodb://<user>:<pass>@<host>:<port>/<db> -jar my-app.jar

And using heroku toolkit, run following command. 并使用heroku工具包,运行以下命令。

heroku deploy:jar -j my-app.jar -i Procfile --app <host-name>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM