목표

MongoDB 클러스터를 생성하고 Spring-boot 프로젝트와 연동

연동 프로세스

Spring-boot 프로젝트 코드

https://github.com/Shining-Boy/SpringCore-Extention
인프런 강의(https://inf.run/kCYMv)를 바탕으로 작성됨

개요

  1. MongoDB Cluster 생성
  2. mongosh(MongoDB Shell) 설치
  3. mongosh로 MongoDB Cluster에 접근
  4. Database 및 Collection 생성
  5. Spring-boot 프로젝트와 MongoDB 연결
  6. Spring-boot와 MongoDB 연동 테스트
  7. 트러블 슈팅

1. MongoDB Cluster 생성

MongoDB 클라우드 주소

2. mongosh(MongoDB Shell) 설치

mogosh 설치 가이드

  • MongoDB public GPG key 발급 및 저장
$ wget -qO- https://www.mongodb.org/static/pgp/server-7.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-7.0.asc
  • 우분투 버전 확인
$ lsb_release -dc
  • MongoDB를 위한 list파일 생성
$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
  • mongosh 패키지 설치
$ sudo apt-get update
$ sudo apt-get install -y mongodb-mongosh
$ mongosh --version

3. mongosh로 MongoDB Cluster에 접근


$ mongosh "mongodb+srv://cluster0.jcm6x0k.mongodb.net/" --apiVersion 1 --username hellospring89

4. Database 및 Collection 생성

5. Spring-boot 프로젝트와 MongoDB 연결

MongoDB와 Spring-boot 연동 가이드

  • 스프링 프로젝트 코드 구조
  • build.gradle에 Dependency 추가

  • application.properties에 MongoDB 접속정보 기입

spring.data.mongodb.uri=mongodb+srv://hellospring89:<password>@cluster0.jcm6x0k.mongodb.net/Food
spring.data.mongodb.database=Food
  • Entity 생성
package hello.core.food;

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

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Document(collection = "KoreanFood")
@Getter
@Setter
@NoArgsConstructor
public class KoreanFood {
    @Id
    private String id;
    private String name;
    private String calorie;

    public KoreanFood(String id, String name, String calorie) {
        super();
        this.id = id;
        this.name = name;
        this.calorie = calorie;
    }
}
  • Repository 인터페이스 생성
package hello.core.food;

import java.util.List;
import java.util.Optional;

public interface FoodRepository {
    KoreanFood save(KoreanFood food);
    Optional<KoreanFood> findById(Long id);
    Optional<KoreanFood> findByName(String name);
    List<KoreanFood> findAll();
}
  • MongoRepository 인터페이스 생성
package hello.core.food;

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

@Repository
public interface MongoFoodRepository extends MongoRepository<KoreanFood, String>, FoodRepository {
    
}
  • 서비스 인터페이스 생성
package hello.core.food;

import java.util.Optional;

public interface FoodService {
    void register(KoreanFood food);
    Optional<KoreanFood> find(Long foodId);
}
  • 서비스 구현체 생성
package hello.core.food;

import java.util.Optional;

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

@Service
public class FoodServiceImpl implements FoodService{
    private final FoodRepository foodRepository;

    @Autowired
    public FoodServiceImpl(FoodRepository foodRepository) {
        this.foodRepository = foodRepository;
    }

    @Override
    public void register(KoreanFood food) {
        foodRepository.save(food);
    }

    @Override
    public Optional<KoreanFood> find(Long foodId) {
        return foodRepository.findById(foodId);
    }
    
}

6. Spring-boot와 MongoDB 연동 테스트

7. 트러블 슈팅

1) EC2에서 MongoDB로 네트워크 엑세스 실패

  • 오류원인
  • 오류해결

    MongoDB Cluster에서, 허용되는 IP 목록에 AWS EC2의 Public IP 주소를 등록

2) mongosh로 DB삭제 실패

  • 오류원인

    사용자에게 권한 없음

  • 오류해결

    사용자에게 Atlas admin 권한 부여

3) Ec2로 배포하는 과정에서 오류

  • 오류원인

    codedeploy-agent 로그 :
	2023-12-29T07:08:30 ERROR [codedeploy-agent(1656)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Network error: #<Seahorse::Client::NetworkingError: Failed to open TCP connection to codedeploy-commands.ap-northeast-2.amazonaws.com:443 (getaddrinfo: Temporary failure in name resolution)>
	2023-12-29T07:08:41 INFO  [codedeploy-agent(1656)]: Version file found in /opt/codedeploy-agent/.version with agent version OFFICIAL_1.6.0-49_deb.
	2023-12-29T07:08:43 INFO  [codedeploy-agent(1656)]: [Aws::CodeDeployCommand::Client 0 2.114929 3 retries] poll_host_command(host_identifier:"arn:aws:ec2:ap-northeast-2:885183918650:instance/i-0e3d0bcc19888a4b3") Seahorse::Client::NetworkingError Failed to open TCP connection to codedeploy-commands.ap-northeast-2.amazonaws.com:443 (getaddrinfo: Temporary failure in name resolution)

	2023-12-29T07:08:43 ERROR [codedeploy-agent(1656)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Error polling for host commands: Seahorse::Client::NetworkingError - Failed to open TCP connection to codedeploy-commands.ap-northeast-2.amazonaws.com:443 (getaddrinfo: Temporary failure in name resolution) - /usr/lib/ruby/2.7.0/net/http.rb:960:in `initialize'


	InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Network error: #<Seahorse::Client::NetworkingError: Failed to open TCP connection to codedeploy-commands.ap-northeast-2.amazonaws.com:443 (getaddrinfo: Temporary failure in name resolution)>



	 관련 에러 검색 결과 : 

EC2인스턴스에 기존 자격증명 파일이 저장되어 있기 때문에 IAM 권한을 가져오지 못하고 있음

  • 오류해결
    AWS 자격증명 파일 삭제
	$ sudo rm -rf /root/.aws/credentials
profile
Back-End Engineer

0개의 댓글

Powered by GraphCDN, the GraphQL CDN