I am trying to build spring boot MongoDB project provided at https://spring.io/guides/gs/accessing-data-mongodb/ which is using spring-boot-starter-parent 2.0.0.RELEASE,
and getting
stack trace:
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.3.jar:na]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.net.SocketException: Socket operation on non-socket (Error setting socket option)
at java.net.PlainSocketImpl.socketSetOption0(Native Method) ~[na:1.8.0_151]
at java.net.PlainSocketImpl.socketSetOption(PlainSocketImpl.java:88) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.setOption(AbstractPlainSocketImpl.java:275) ~[na:1.8.0_151]
at java.net.Socket.setTcpNoDelay(Socket.java:980) ~[na:1.8.0_151]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:36) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongodb-driver-core-3.6.3.jar:na]
... 3 common frames omitted
When I changed spring-boot-starter-parent version to 1.5.9.RELEASE or 1.5.10.RELEASE, the same code is working fine. So is there any problem with version 2.0.0.RELEASE when using spring data mongo.
System details:
mongod version: 3.4.13
openjdk version "1.8.0_151"
I had to install and start mongodb first for spring-boot-starter-parent 2.0.x
assuming you are using MacOS
# to install mongodb
➜ ~ brew install mongodb
# To have launchd start mongodb now and restart at login
➜ ~ brew services start mongodb
after that everything worked as expected:
2018-04-05 22:13:43.189 INFO 26777 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-04-05 22:13:43.229 INFO 26777 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:1}] to localhost:27017
2018-04-05 22:13:43.234 INFO 26777 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 3]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3049505}
2018-04-05 22:13:43.352 INFO 26777 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-04-05 22:13:43.469 INFO 26777 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:2}] to localhost:27017
2018-04-05 22:13:43.471 INFO 26777 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 3]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1552605}
Related
I am using spring boot 2.5.3 and postgreSQL for backend.
I want this app to run on localhost:5000/api/v1/customers as well as from docker-compose.
application.properties:
server.port=5000
#Database setup
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://localhost:5432/customers
spring.datasource.username=postgres
spring.datasource.password=postgres
This works with localhost, with mvn spring-boot:run
But, when I use the following application.properties settings from localhost to db
server.port=5000
#Database setup
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://db:5432/customers
spring.datasource.username=postgres
spring.datasource.password=postgres
Dockerfile
FROM maven:3.8.1-openjdk-11-slim
COPY ./target/customer-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
docker-compose.yml
version: '3.1'
services:
app:
container_name: customer-container
image: customer-image:v1
build: ./
ports:
- "5000:5000"
depends_on:
- db
db:
image: postgres
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=customers
I cannot connect to localhost:5000/api/v1/customers after mvn spring-boot:run
Error:
org.postgresql.util.PSQLException: Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:303) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:223) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.Driver.makeConnection(Driver.java:465) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.Driver.connect(Driver.java:264) ~[postgresql-42.2.23.jar:42.2.23]
Tried to create a docker image docker build -t customer-image:v1 .
, and run docker-compose build docker-compose up there are no error.
Logs says it is running on port 5000.
customer-container | 2021-08-29 12:43:42.053 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 5000 (http)
customer-container | 2021-08-29 12:43:42.068 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
customer-container | 2021-08-29 12:43:42.069 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.50]
customer-container | 2021-08-29 12:43:42.189 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
customer-container | 2021-08-29 12:43:42.190 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1876 ms
customer-container | 2021-08-29 12:43:42.487 INFO 1 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
customer-container | 2021-08-29 12:43:42.567 INFO 1 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
customer-container | 2021-08-29 12:43:42.702 INFO 1 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
customer-container | 2021-08-29 12:43:42.827 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
customer-container | 2021-08-29 12:43:42.970 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
customer-container | 2021-08-29 12:43:42.995 INFO 1 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
customer-container | 2021-08-29 12:43:43.631 WARN 1 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
customer-container | 2021-08-29 12:43:43.631 WARN 1 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "customer" does not exist, skipping
customer-container | 2021-08-29 12:43:43.642 INFO 1 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
customer-container | 2021-08-29 12:43:43.656 INFO 1 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
customer-container | 2021-08-29 12:43:44.252 WARN 1 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
customer-container | 2021-08-29 12:43:44.991 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 5000 (http) with context path ''
customer-container | 2021-08-29 12:43:45.290 INFO 1 --- [ main] c.p.customer.CustomerApplication : Started CustomerApplication in 5.654 seconds (JVM running for 6.531)
This works localhost:5000/api/v1/customers when docker-compose is up.
Is there a way we can have condtional name for host in this line?Is there any other way?
spring.datasource.url=jdbc:postgresql://db:5432/customers
Since the host development environment and the container runtime environment are different, you can use environment variables to differentiate between them. Spring Boot knows how to set Spring properties from environment variables. So I'd recommend:
In your application.properties file, set spring.datasource.url to the localhost URL you'd use in development.
In your Compose setup, set the SPRING_DATASOURCE_URL environment variable to the name specific to that Compose setup
version: '3.8'
services:
db: { ... }
app:
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/customers
...
Do not create a separate Spring profile per environment; you would not want to recompile your jar file if you changed the database name or password, or deployed this in Kubernetes, or used a cloud-hosted database like Amazon RDS, or...
So, you want to be able to run both locally and from docker?
If that's the case, you need to extract the database connection string to an environment variable that you set at runtime
spring.datasource.url = ${DB_HOST}:${DB_PORT}/
spring.datasource.username = ${DB_USERNAME}
spring.datasource.password = ${DB_PASSWD}
Or you can introduce two different property files that get set from a Spring profile, which you also would set at runtime; Refer SPRING_PROFILES_ACTIVE environment variable
Based on what I see, you are not supposed to use localhost on spring.datasource.url because your docker is within the container itself, you should be using
jdbc:postgresql://host.docker.internal:5432/customers instead. For more details, you can view from this link https://docs.docker.com/desktop/windows/networking/#i-cannot-ping-my-containers
Is there a way we can have condtional name for host in this line?Is there any other way?
As for this, it would be prefered to set it as an environmetn variable on your docker compose file and connect using dbconn url
If you are using linux as your operating system on which you are running your docker , you can set this property
network_mode: host
on both the containers, this will attach your container's port to your localhost port.
You will need to remove the port forwarding config for this to work.
This is my first time using MongoDB with Spring, and all I'm trying to do is start the Spring server however the connection closes straight away after it's opened.
After looking around on similar scenarios, there were suggestions about removing the Spring Data JPA dependency which I did but did not help. Another suggestion said to add h2 as a dependency to as Spring Starter needed it before a few things, which did help as previous the connection didn't even open. I've also edited the properties file, but nothing seems to work.
Gradle file:
group = 'com.danielturato'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-security'
runtimeOnly 'com.h2database:h2'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
application.properties:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mongo
server.port=8095
The logs:
2019-08-22 00:04:13.109 INFO 16376 --- [ main] com.danielturato.esports.Application : Starting Application on DESKTOP-E2MJ251 with PID 16376 (started by danie in D:\Projects\eSports Project)
2019-08-22 00:04:13.111 INFO 16376 --- [ main] com.danielturato.esports.Application : No active profile set, falling back to default profiles: default
2019-08-22 00:04:13.368 INFO 16376 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-08-22 00:04:13.411 INFO 16376 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 39ms. Found 1 repository interfaces.
2019-08-22 00:04:14.117 INFO 16376 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-08-22 00:04:14.117 INFO 16376 --- [ main] org.mongodb.driver.cluster : Adding discovered server localhost:27017 to client view of cluster
2019-08-22 00:04:14.150 INFO 16376 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:14}] to localhost:27017
2019-08-22 00:04:14.153 INFO 16376 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 0]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1950400}
2019-08-22 00:04:14.154 INFO 16376 --- [localhost:27017] org.mongodb.driver.cluster : Discovered cluster type of STANDALONE
2019-08-22 00:04:14.378 INFO 16376 --- [ main] com.danielturato.esports.Application : Started Application in 1.482 seconds (JVM running for 1.99)
2019-08-22 00:04:14.414 INFO 16376 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:15}] to localhost:27017
2019-08-22 00:04:14.429 INFO 16376 --- [ Thread-2] org.mongodb.driver.connection : Closed connection [connectionId{localValue:2, serverValue:15}] to localhost:27017 because the pool has been closed.
If anyone has anymore suggestions, that would be appreciated !
I had a previous question that (I think at least) that more or less became useless as I managed to fix the errors I was presented with.. However my new error, is that I cannot seem to connect to mongodb from within my docker image
docker-compose.yml:
version: '3.1'
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mongo
ports:
- 8080:8080
mongo:
image: mongo
ports:
- '27017:27017'
networks:
mongo_net:
ipv4_address: 172.28.0.2
networks:
mongo_net:
driver: bridge
ipam:
driver: default
config:
-
subnet: 172.28.0.2/24
application.properties:
spring.data.mongodb.database=myDb
spring.data.mongodb.host=172.28.0.2
spring.data.mongodb.port=27017
And the actual error:
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.4.jar!/:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.4.jar!/:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.4.jar!/:na]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111]
Caused by: java.net.SocketTimeoutException: connect timed out
You’ve explicitly created a network in your docker-compose.yml file, and set your database to use that network. Docker Compose also creates a default network for you, and since your application doesn’t explicitly declare any networks, that attaches to only the default network. Then the two containers are on different networks and the one can’t reach the other.
The easiest solution here is to just delete all of the manual network configuration:
version: '3.1'
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
depends_on:
- mongo
ports:
- '8080:8080'
mongo:
image: mongo
ports:
- '27017:27017'
The name of the service block will be a valid DNS hostname, and in your configuration you can set spring.data.mongodb.host=mongo.
I agree David answer is right. But here is a takeaway, your configuration works too, I tried with my sample and here is the result.
Issue is your app is not attached to the network.
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mongo
ports:
- 8080:8080
networks:
- mongo_net
sample docker-compose.yml
version: '3.1'
services:
mongo-app:
image: barath-mongo
ports:
- "9000:9000"
depends_on:
- mongo
environment:
SPRING_DATA_MONGODB_PORT: 27017
SPRING_DATA_MONGODB_HOST: 172.28.0.2
SPRING_DATA_MONGODB_DATABASE: myDb
networks:
- mongo_net
mongo:
image: mongo
ports:
- '27017:27017'
networks:
mongo_net:
ipv4_address: 172.28.0.2
networks:
mongo_net:
driver: bridge
ipam:
driver: default
config:
-
subnet: 172.28.0.2/24
mongo container ip address:
$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ec2-user_mongo_1
172.28.0.2
docker network settings
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.28.0.2/24"
}
]
},
"Internal": false,
"Attachable": true,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"02b8b4148dd830eaddeb7e9ebd6305a6ae3c106bae5a495103c632aec7999274": {
"Name": "ec2-user_mongo-app_1",
"EndpointID": "885088d551888e1dec95b1c0e337c6a4b84f1bb2aebc4407963d3c0b4f6ec09d",
"MacAddress": "02:42:ac:1c:00:03",
"IPv4Address": "172.28.0.3/24",
"IPv6Address": ""
},
"3e4266fca3c8163412cc1c4733cad004aa0f366dc9fe30d03c7ecafe87b4e826": {
"Name": "ec2-user_mongo_1",
"EndpointID": "a6a72c7fc314a294c53d5c394ac1757702a0a95c588af2f730e971953dbbaa5f",
"MacAddress": "02:42:ac:1c:00:02",
"IPv4Address": "172.28.0.2/24",
"IPv6Address": ""
}
},
output :
ongo-app_1 | 2019-01-28 17:07:29.710 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:1}] to 172.28.0.2:27017
mongo-app_1 | 2019-01-28 17:07:29.735 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=172.28.0.2:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=20314562}
mongo-app_1 | 2019-01-28 17:07:29.742 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.cluster : Discovered cluster type of STANDALONE
mongo-app_1 | 2019-01-28 17:07:30.387 INFO 1 --- [ main] com.barath.app.service.CustomerService : Saving the customer with customer details com.barath.app.document.Customer#37654521
mongo_1 | 2019-01-28T17:07:30.488+0000 I NETWORK [listener] connection accepted from 172.28.0.3:56250 #2 (2 connections now open)
mongo_1 | 2019-01-28T17:07:30.491+0000 I NETWORK [conn2] received client metadata from 172.28.0.3:56250 conn2: { driver: { name: "mongo-java-driver", version: "3.8.2" }, os: { type: "Linux", name: "Linux", architecture: "amd64", version: "4.14.77-81.59.amzn2.x86_64" }, platform: "Java/Oracle Corporation/1.8.0_191-b12" }
mongo-app_1 | 2019-01-28 17:07:30.497 INFO 1 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:2}] to 172.28.0.2:27017
mongo_1 | 2019-01-28T17:07:30.576+0000 I STORAGE [conn2] createCollection: myDb.customer with generated UUID: 6bd5b022-16b6-4a04-96b0-d94988155a53
mongo-app_1 | 2019-01-28 17:07:31.514 INFO 1 --- [ main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
mongo-app_1 | 2019-01-28 17:07:31.879 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
mongo-app_1 | 2019-01-28 17:07:32.372 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
mongo-app_1 | 2019-01-28 17:07:32.432 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
mongo-app_1 | 2019-01-28 17:07:32.522 INFO 1 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
mongo-app_1 | 2019-01-28 17:07:32.977 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9000 (http) with context path ''
mongo-app_1 | 2019-01-28 17:07:32.984 INFO 1 --- [ main] com.barath.app.Application : Started Application in 11.151 seconds (JVM running for 13.149)
I downloaded the example from Spring Data MongoDB 2.0 - Reactive examples.
I'm failing to understand how to make it work.
I set up a cluster in cloud.mongodb.com and they supply me with:
If I am using driver 3.6 or later:
mongodb+srv://stavalfi:<PASSWORD>#cluster0-9yjy8.mongodb.net/test
Else, if I am using driver 3.4 or earlier:
mongodb://stavalfi:<PASSWORD>#cluster0-shard-00-00-
9yjy8.mongodb.net:27017,cluster0-shard-00-01-
9yjy8.mongodb.net:27017,cluster0-shard-00-02-
9yjy8.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin
I don't know what is the version of the driver which spring uses so I chose the first one:
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
#EnableReactiveMongoRepositories
#AutoConfigureAfter(EmbeddedMongoAutoConfiguration.class)
#RequiredArgsConstructor
class ApplicationConfiguration extends AbstractReactiveMongoConfiguration {
private final Environment environment;
public static void main(String args[]) throws InterruptedException {
ConfigurableApplicationContext run = SpringApplication.run(ApplicationConfiguration.class);
run.getBean(ReactiveMongoTemplate.class)
.save("something to push")
.subscribe(System.out::println, Throwable::printStackTrace, () -> System.out.println("success"));
Thread.sleep(1000000);
}
#Bean
public LoggingEventListener mongoEventListener() {
return new LoggingEventListener();
}
#Override
#Bean
#DependsOn("embeddedMongoServer")
public MongoClient reactiveMongoClient() {
return MongoClients.create(String.format("mongodb+srv://stavalfi:<MyAccountPassword!>#cluster0-9yjy8.mongodb.net/test"));
// int port = environment.getProperty("local.mongo.port", Integer.class);
// return MongoClients.create(String.format("mongodb://localhost:%d", port));
}
#Override
protected String getDatabaseName() {
return "reactive";
}
}
I'm sure I'm not doing anything as Spring Data MongoDB project expected me to do.
The Exception I get while creating the Bean: MongoClient
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reactiveMongoClient' defined in example.springdata.mongodb.people.ApplicationConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.reactivestreams.client.MongoClient]: Factory method 'reactiveMongoClient' threw exception; nested exception is java.lang.UnsupportedOperationException: No SSL support in java.nio.channels.AsynchronousSocketChannel. For SSL support use com.mongodb.connection.netty.NettyStreamFactoryFactory
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at example.springdata.mongodb.people.ApplicationConfiguration.main(ApplicationConfiguration.java:53) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.reactivestreams.client.MongoClient]: Factory method 'reactiveMongoClient' threw exception; nested exception is java.lang.UnsupportedOperationException: No SSL support in java.nio.channels.AsynchronousSocketChannel. For SSL support use com.mongodb.connection.netty.NettyStreamFactoryFactory
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
... 17 common frames omitted
Caused by: java.lang.UnsupportedOperationException: No SSL support in java.nio.channels.AsynchronousSocketChannel. For SSL support use com.mongodb.connection.netty.NettyStreamFactoryFactory
at com.mongodb.connection.AsynchronousSocketChannelStreamFactory.<init>(AsynchronousSocketChannelStreamFactory.java:58) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.AsynchronousSocketChannelStreamFactory.<init>(AsynchronousSocketChannelStreamFactory.java:43) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.async.client.MongoClients.getStreamFactory(MongoClients.java:237) ~[mongodb-driver-async-3.6.3.jar:na]
at com.mongodb.async.client.MongoClients.create(MongoClients.java:181) ~[mongodb-driver-async-3.6.3.jar:na]
at com.mongodb.async.client.MongoClients.create(MongoClients.java:172) ~[mongodb-driver-async-3.6.3.jar:na]
at com.mongodb.reactivestreams.client.MongoClients.create(MongoClients.java:90) ~[mongodb-driver-reactivestreams-1.7.1.jar:na]
at com.mongodb.reactivestreams.client.MongoClients.create(MongoClients.java:75) ~[mongodb-driver-reactivestreams-1.7.1.jar:na]
at example.springdata.mongodb.people.ApplicationConfiguration.reactiveMongoClient(ApplicationConfiguration.java:70) [classes/:na]
at example.springdata.mongodb.people.ApplicationConfiguration$$EnhancerBySpringCGLIB$$6152c801.CGLIB$reactiveMongoClient$1(<generated>) ~[classes/:na]
at example.springdata.mongodb.people.ApplicationConfiguration$$EnhancerBySpringCGLIB$$6152c801$$FastClassBySpringCGLIB$$4cbf5891.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at example.springdata.mongodb.people.ApplicationConfiguration$$EnhancerBySpringCGLIB$$6152c801.reactiveMongoClient(<generated>) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
... 18 common frames omitted
How can I fix this?
Played around with this some. You can find details from Mongo Java Driver tutorials.
First I tried using the DSL approach, which would be neat to have all the setup as code:
application.yml
mongo:
user: training_mongo
password: <my_password>
hosts:
- training-abcde.mongodb.net
database: training
MongoProperties.java
#ConfigurationProperties("mongo")
#Component
public class MongoProperties {
private String user;
private String password;
private List<String> hosts;
private String database;
ApplicationConfiguration.java
#Configuration
#EnableWebFlux
#EnableReactiveMongoRepositories
public class ApplicationConfig extends AbstractReactiveMongoConfiguration {
[...]
#Override
public MongoClient reactiveMongoClient() {
return create(MongoClientSettings.builder()
.clusterSettings(ClusterSettings.builder()
.hosts(mongoProperties.getHosts()
.stream()
.map(ServerAddress::new)
.collect(toList()))
.build())
.streamFactoryFactory(NettyStreamFactory::new)
.sslSettings(SslSettings.builder()
.enabled(true)
.build())
.credential(MongoCredential.createCredential(
mongoProperties.getUser(),
mongoProperties.getDatabase(),
mongoProperties.getPassword().toCharArray()))
.build());
}
#Override
protected String getDatabaseName() {
return DB_NAME;
}
This however crashes, because Netty fires a DNS lookup through the Java stack and that fails:
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.147 INFO 16148 --- [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017
[DEBUG] [TestEventLogger]
[DEBUG] [TestEventLogger] com.mongodb.MongoSocketOpenException: Exception opening socket
[ ... stacktrace ...]
[DEBUG] [TestEventLogger]
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.278 INFO 16148 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[training-abcde.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.279 INFO 16148 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.975 INFO 16148 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
[TestEventLogger] 2018-08-06 17:22:18.006 INFO 16148 --- [ngodb.net:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server training-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger]
[DEBUG] [TestEventLogger] com.mongodb.MongoSocketOpenException: Exception opening socket
[... stacktrace ...]
[DEBUG] [TestEventLogger] Caused by: java.net.UnknownHostException: No such host is known (training-abcde.mongodb.net)
[DEBUG] [TestEventLogger] at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:925) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1505) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:844) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1495) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1354) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1288) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getByName(InetAddress.java:1238) ~[na:na]
[DEBUG] [TestEventLogger] at io.netty.util.internal.SocketUtils$8.run(SocketUtils.java:146) ~[netty-common-4.1.25.Final.jar:4.1.25.Final]
[DEBUG] [TestEventLogger] at io.netty.util.internal.SocketUtils$8.run(SocketUtils.java:143) ~[netty-common-4.1.25.Final.jar:4.1.25.Final]
[DEBUG] [TestEventLogger] at java.base/java.security.AccessController.doPrivileged(Native Method) ~[na:na]
But doing things less elegantly via the connection URL seem to work:
ApplicationConfiguration.java:
#Configuration
#EnableWebFlux
#EnableReactiveMongoRepositories
public class ApplicationConfig extends AbstractReactiveMongoConfiguration {
private static final String CONNECTION_URL = "mongodb+srv://%s:%s#%s/%s?retryWrites=true&streamType=netty&ssl=true";
[...]
#Override
public MongoClient reactiveMongoClient() {
return MongoClients.create(getMongoConnectionUrl());
}
#Override
protected String getDatabaseName() {
return DB_NAME;
}
private String getMongoConnectionUrl() {
String connectionUrl = String.format(CONNECTION_URL, mongoProperties.getUser(), mongoProperties.getPassword(),
mongoProperties.getHosts().get(0), mongoProperties.getDatabase());
return connectionUrl;
}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.132 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='training-shard-0'}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.132 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-shard-00-00-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.135 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-shard-00-01-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.139 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-shard-00-02-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.831 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.450 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:161155}] to training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.468 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=training-shard-00-00-abcde.mongodb.net:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 6]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=16287599, setName='training-shard-0', canonicalAddress=training-shard-00-00-abcde.mongodb.net:27017, hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017], passives=[], arbiters=[], primary='training-shard-00-00-abcde.mongodb.net:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000008, setVersion=1, lastWriteDate=Mon Aug 06 18:25:37 SRET 2018, lastUpdateTimeNanos=70366873909383}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.473 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max election id to 7fffffff0000000000000008 from replica set primary training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.474 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max set version to 1 from replica set primary training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.475 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Discovered replica set primary training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.479 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:4, serverValue:71172}] to training-shard-00-02-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.496 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=training-shard-00-02-abcde.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 6]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=16406907, setName='training-shard-0', canonicalAddress=training-shard-00-02-abcde.mongodb.net:27017, hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017], passives=[], arbiters=[], primary='training-shard-00-00-abcde.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Mon Aug 06 18:25:37 SRET 2018, lastUpdateTimeNanos=70366902099001}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.497 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:224436}] to training-shard-00-01-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.512 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=training-shard-00-01-abcde.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 6]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=14614118, setName='training-shard-0', canonicalAddress=training-shard-00-01-abcde.mongodb.net:27017, hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017], passives=[], arbiters=[], primary='training-shard-00-00-abcde.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Mon Aug 06 18:25:37 SRET 2018, lastUpdateTimeNanos=70366918148773}
I think it haven't SSL Certificate or may be the wrong or dummy SSL Certificate are there. That's why it's display No SSL support in java.nio.channels.AsynchronousSocketChannel
From the docs:
If you are using the reactive driver, Netty is required for SSL. The auto-configuration configures this factory automatically if Netty is available and the factory to use hasn’t been customized already.
Make sure that you have netty on the classpath (either selected modules or netty-all).
I added apache metamodel into my project.
<dependency>
<groupId>org.apache.metamodel</groupId>
<artifactId>MetaModel-full</artifactId>
<version>5.0.0</version>
</dependency>
mongo-java-driver came as a dependency.
[INFO] | +- org.apache.metamodel:MetaModel-mongodb-mongo3:jar:5.0.0:compile
[INFO] | | +- org.apache.metamodel:MetaModel-mongodb-common:jar:5.0.0:compile
[INFO] | | \- org.mongodb:mongo-java-driver:jar:3.4.3:compile
[INFO] | +- org.apache.metamodel:MetaModel-mongodb-mongo2:jar:5.0.0:compile
Then I see some logs like.
2018-01-16 02:33:09.467 INFO 15417 --- [ restartedMain] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-01-16 02:33:09.512 DEBUG 15417 --- [ restartedMain] org.mongodb.driver.cluster : Updating cluster description to {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]
2018-01-16 02:33:09.521 DEBUG 15417 --- [localhost:27017] org.mongodb.driver.connection : Closing connection connectionId{localValue:1}
2018-01-16 02:33:09.525 INFO 15417 --- [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 common frames omitted
2018-01-16 02:33:09.527 DEBUG 15417 --- [localhost:27017] org.mongodb.driver.cluster : Updating cluster description to {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}]
When I dig source code of mongo-java-driver I see mongo-java-driver starts a Thread to monitor default mongodb server. I dont want to exclude mongodb driver but how can I disable com.mongodb.connection.DefaultServerMonitor thread.
After further search I realized that it is spring-boot autoconfiguration issue. My application is a spring-boot app. spring-boot auto config finds a mongos-java-driver jar in classpath and start-up mongo-drive.
Added #EnableAutoConfiguration(exclude = {MongoAutoConfiguration.class}) and mongo-java-driver doesn't start anymore.