11

Please suggest any solution for the below exception which is occuring while running my rest api while executing springboot application with mongodb cloud db. I have created collection in mongodb as well and configured below properties.

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.1.1.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.1.1.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.1.1.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:589) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
    at java.base/java.net.Socket.connect(Socket.java:648) ~[na:na]
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:78) ~[mongodb-driver-core-4.1.1.jar:na]
    at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.1.1.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.1.1.jar:na]
    ... 4 common frames omitted
Model class
------------
package com.praveen.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import lombok.Data;

@Document
public class Products {

    @Id
    private String id;
    private Integer p_id;
    private String p_name;
    private Integer p_cost;
    private Integer countInStock;
    private Integer numReviews;
    private String image;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Integer getP_id() {
        return p_id;
    }
    public void setP_id(Integer p_id) {
        this.p_id = p_id;
    }
    public String getP_name() {
        return p_name;
    }
    public void setP_name(String p_name) {
        this.p_name = p_name;
    }
    public Integer getP_cost() {
        return p_cost;
    }
    public void setP_cost(Integer p_cost) {
        this.p_cost = p_cost;
    }
    public Integer getCountInStock() {
        return countInStock;
    }
    public void setCountInStock(Integer countInStock) {
        this.countInStock = countInStock;
    }
    public Integer getNumReviews() {
        return numReviews;
    }
    public void setNumReviews(Integer numReviews) {
        this.numReviews = numReviews;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
    @Override
    public String toString() {
        return "Products [id=" + id + ", p_id=" + p_id + ", p_name=" + p_name + ", p_cost=" + p_cost + ", countInStock="
                + countInStock + ", numReviews=" + numReviews + ", image=" + image + "]";
    }
    
    
}

RestController class
---------------------

package com.praveen.rest;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import com.praveen.entity.Products;
import com.praveen.service.ProductsService;

@RestController
public class ProductsRestController {

    @Autowired
    private ProductsService service;
    
    @GetMapping("/products")
    public ResponseEntity<List<Products>> getProducts(){
        List<Products> allProducts = service.getAllProducts();
        if(allProducts != null) {
            return new ResponseEntity<List<Products>>(allProducts, HttpStatus.OK);
        }else {
            return new ResponseEntity<List<Products>>(HttpStatus.BAD_REQUEST);
        }
    }
}

Service class
--------------
package com.praveen.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.praveen.entity.Products;
import com.praveen.repository.ProductsRepository;

@Service
public class ProductsServiceImpl implements ProductsService {

    @Autowired
    private ProductsRepository prodRepo;
    
    @Override
    public List<Products> getAllProducts() {
        List<Products> productsList = prodRepo.findAll();
        if(productsList != null) {
            System.out.println(productsList);
            return productsList;
        }
        return null;
    }

}

Repository 
-----------
package com.praveen.repository;

import java.io.Serializable;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.praveen.entity.Products;

@Repository
public interface ProductsRepository extends MongoRepository<Products, Serializable> {

}

application.properties
-----------------------
spring.data.mongodb.url = mongodb+srv://praveen:[email protected]/miniproject?retryWrites=true&w=majority
spring.data.mongodb.database = products
spring.data.mongodb.port = 27017
spring.data.mongodb.repositories.enabled=true
pom.xml
-------
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.praveen</groupId>
    <artifactId>NgRx-Products</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>05-MiniProject-NgRx-Products</name>
    <description>NgRx package with Products data using springboot</description>
    <properties>
        <java.version>15</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Please suggest any solution for the above exception, I have given all my files in the above.

2
  • ConnectException: Connection refused is a network issue meaning that your app cant connect to your mongo host port. You could maybe first try with a local mongo server. Or else try to troubleshoot your network (using telnet, checking your firewall/proxy, etc), or maybe try first using mongo client. Commented Feb 27, 2021 at 21:59
  • I'm running into the same issue after moving the application to a new server (Linux). I am using IntelliJ IDEA and using 'create datasource' it successfully connects to the external MongoDB server. It worked fine on the other host. Commented Apr 8, 2021 at 17:54

6 Answers 6

7

Try adding this annotation to your main class file @EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})

Sign up to request clarification or add additional context in comments.

1 Comment

Is this approach safe?
2

Spring boot 3 and Kotlin:

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration

@SpringBootApplication(
    exclude = [MongoAutoConfiguration::class],
)

Comments

1

this exception occurs due to mongodb incorrect port in application properties. So only changing spring.data.mongodb.port=27017 in application.properties file made it work. Also make sure you started mongodb server locally.

Comments

0

Search services in start. open it. search for mongodb there. start/restart mongodb services from there. It should work properly.

Comments

0

Check the connect to MongoDB sever locally with url:portNumber mentioned in the application.properties from where your code is getting executed.

Comments

0

You can do it in some simple steps:

  • search for services in start menu.
  • search mongo DB server and click on it.
  • click on start/restart. Now try connecting in mongo DB, it works properly now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.