简体   繁体   English

Spring Boot 无法访问本地主机 Mongodb

[英]Spring Boot can't reach localhost Mongodb

I'm following this example of creating a Spring Boot app that connects with a Mongo DB.我正在按照这个创建与 Mongo DB 连接的 Spring Boot 应用程序的示例进行操作。 However, when I run my application I get:但是,当我运行我的应用程序时,我得到:

Exception in monitor thread while connecting to server localhost:8081

With the following properties:具有以下属性:

spring.data.mongodb.uri=mongodb://root:example@localhost:8081/test

And the following MongoClient :以及以下MongoClient

MongoClient with metadata {"driver": {"name": "mongo-java-driver|sync|spring-boot", "version": "4.8.0"}, "os": {"type": "Linux", "name": "Linux", "architecture": "amd64", "version": "5.15.0-56-generic"}, "platform": "Java/Eclipse Adoptium/17.0.5+8"} created with settings MongoClientSettings{readPreference=primary, writeConcern=WriteConcern{w=null, wTimeout=null ms, journal=null}, retryWrites=true, retryReads=true, readConcern=ReadConcern{level=null}, credential=MongoCredential{mechanism=null, userName='root', source='test', password=<hidden>, mechanismProperties=<hidden>}, streamFactoryFactory=null, commandListeners=[], codecRegistry=ProvidersCodecRegistry{codecProviders=[ValueCodecProvider{}, BsonValueCodecProvider{}, DBRefCodecProvider{}, DBObjectCodecProvider{}, DocumentCodecProvider{}, CollectionCodecProvider{}, IterableCodecProvider{}, MapCodecProvider{}, GeoJsonCodecProvider{}, GridFSFileCodecProvider{}, Jsr310CodecProvider{}, JsonObjectCodecProvider{}, BsonCodecProvider{}, EnumCodecProvider{}, com.mongodb.Jep395RecordCodecProvider@1b9d9a2b]}, clusterSettings={hosts=[localhost:8081], srvServiceName=mongodb, mode=SINGLE, requiredClusterType=UNKNOWN, requiredReplicaSetName='null', serverSelector='null', clusterListeners='[]', serverSelectionTimeout='30000 ms', localThreshold='30000 ms'}, socketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=0, receiveBufferSize=0, sendBufferSize=0}, heartbeatSocketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=10000, receiveBufferSize=0, sendBufferSize=0}, connectionPoolSettings=ConnectionPoolSettings{maxSize=100, minSize=0, maxWaitTimeMS=120000, maxConnectionLifeTimeMS=0, maxConnectionIdleTimeMS=0, maintenanceInitialDelayMS=0, maintenanceFrequencyMS=60000, connectionPoolListeners=[], maxConnecting=2}, serverSettings=ServerSettings{heartbeatFrequencyMS=10000, minHeartbeatFrequencyMS=500, serverListeners='[]', serverMonitorListeners='[]'}, sslSettings=SslSettings{enabled=false, invalidHostNameAllowed=false, context=null}, applicationName='null', compressorList=[], uuidRepresentation=JAVA_LEGACY, serverApi=null, autoEncryptionSettings=null, contextProvider=null}

The application is running fine but can't reach the db.应用程序运行良好,但无法访问数据库。 I tried several other settings, such as replacing localhost with 127.0.0.1 and declaring settings in separate values such that:我尝试了其他几种设置,例如将localhost替换为127.0.0.1并在单独的值中声明设置,以便:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=8081
spring.data.mongodb.database=test
spring.data.mongodb.username=root
spring.data.mongodb.password=example

But nothing seems to work.但似乎没有任何效果。 The Mongo DB dashboard is shown at localhost:8081 so I know that the DB is actually running fine. Mongo DB 仪表板显示在localhost:8081 ,因此我知道该数据库实际上运行良好。

This is what I used start a local Mongo DB instance in a Docker container:这就是我用来在 Docker 容器中启动本地 Mongo DB 实例的方式:

# Use root/example as user/password credentials
version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_DATABASE: test
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

Are you using -p 8081:27071 while running your mongo docker container?您在运行 mongo -p 8081:27071吗? I guess your config - 8081:8081 should be updated to '- 8081:27071'.我想您的配置- 8081:8081应该更新为“- 8081:27071”。

Download example code下载示例代码

git clone https://github.com/spring-guides/gs-accessing-mongodb-data-rest

goto gs-accessing-mongodb-data-rest/complete转到 gs-accessing-mongodb-data-rest/complete

create dir resources under `src/main/在`src/main/下创建目录resources

create application.properties创建 application.properties

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
spring.data.mongodb.username=root
spring.data.mongodb.password=example

MongoDB docker compose MongoDB 码头工人组成

docker-compose.yml docker-compose.yml

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_DATABASE: test
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

Start MonogoDB启动MonogoDB

docker compose up

Use mongosh使用 mongosh

mongosh admin -u root -p example

In mongosh在蒙哥什

use test

db.createUser({user: "root", pwd: "example", roles: ["dbOwner"]})

exit

Run Spring Boot运行 Spring Boot

go to gs-accessing-mongodb-data-rest/complete转到 gs-accessing-mongodb-data-rest/complete

mvn clean spring-boot:run

Test测试

curl -i -X POST -H "Content-Type:application/json" -d "{  \"firstName\" : \"Frodo\",  \"lastName\" : \"Baggins\" }" http://localhost:8080/people

Result结果

HTTP/1.1 201 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Location: http://localhost:8080/people/63a7cb0249786806453df30d
Content-Type: application/hal+json
Transfer-Encoding: chunked
Date: Sun, 25 Dec 2022 04:01:06 GMT

{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people/63a7cb0249786806453df30d"
    },
    "person" : {
      "href" : "http://localhost:8080/people/63a7cb0249786806453df30d"
    }
  }

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

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