Framework/프로젝트로 스프링 이해하기

[이커머스 프로젝트] 이메일 전송 기능 구현 (Mailgun, Feign)

simDev1234 2022. 11. 25. 16:57

|  절차

1. Mailgun 회원 가입 및 API 사용법 확인

2. Feign 라이브러리를 사용하여, Mailgun의 이메일 전송 Api 호출

3. Test 코드를 작성하여 전송 확인

 

1.  Mailgun 회원가입 및 API 사용 방법 확인하기

[1] 회원가입

[2] 이메일 전송 API 사용 방법 확인

- Post API : 인증키를 헤더로 보내고, 쿼리 스트링으로 발신자/수신자/제목/내용을 보내는 POST API

   - API KEY를 인증키로 사용

   - API base URL 정보에 따라서 이메일을 전송

[3] 테스트용으로 수신을 받을 수 있는 이메일을 추가해둔다.

- Mailgun은 무료 계정인 경우에 이렇게 이메일을 추가해두어야만 한다고 한다.

 

|  Feign 을 사용하기

[1] 의존성 주입

ext{
    set('springCloudVersion', '2021.0.1')
}

dependencyManagement{
    imports{
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
}

[2] application.properties에 환경 설정하기

server.port=8081
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
feign.okhttp.enabled=true

* 우아한 형제들 포스팅을 보았는데, feign을 httpclient 로도 사용할 수 있고, 또는 okhttp로도 사용할 수 있다고 한다.

* OkHttp에 대한 장점을 퍼봤는데 내용은 아래와 같다.

OkHttp has HTTP/2, a built-in response cache, web sockets, and a simpler API. 
It’s got better defaults and is easier to use efficiently. 
It’s got a better URL model, a better cookie model, a better headers model and a better call model. OkHttp makes canceling calls easy. 
OkHttp has carefully managed TLS defaults that are secure and widely compatible. 
Okhttp works with Retrofit, which is a brilliant API for REST. 
It also works with Okio, which is a great library for data streams. 
OkHttp is a small library with one small dependency (Okio) and is less code to learn. 
OkHttp is more widely deployed, with a billion Android 4.4+ devices using it internally.

[ 출처 ] https://github.com/square/okhttp/issues/3472

[3] Main에 @EnableFeignClients 추가

- 또는 [4] Config 파일에 넣어주어도 무방할 것 같다.

@SpringBootApplication
@EnableFeignClients
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

[4] Config 파일 만들기

- Post api 요청을 보낼 때 인증키를 헤더로 보내야 하기 때문에 BasciAuthRequestInterceptor를 설정 파일에 추가한다.

- @Bean 위에 @Qualifier가 붙어있는데, 이는 매개변수나 필드를 통해 의존성을 주입할 때 사용되는 어노테이션이다.

  이 Bean은 mailgun 에서만 사용하겠다는 표시이다.

@Configuration
public class FeignConfig {

    @Value("mailgun.key")
    String mailgunKey;

    @Qualifier(value = "mailgun")
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){
        return new BasicAuthRequestInterceptor("api", mailgunKey);
    }
}

[5] Mailgun에 post API를 호출하는 메소드를 담은 interface를 작성한다.

- @FeignClient(name = "", url = "") : name은 이게 무슨 인터페이스인지, url은 호출하려는 baseurl

- @Qualifier로 FeignConfig의 Interceptor Bean이 잘 작동하게 해준다.

- @PostMapping 안에 앞서 보았던 Post Api에 들어가야하는 하위 경로를 작성하고,

- @SpringQueryMap을 통해 쿼리문으로 들어갈 발신자/수신자/제목/내용을 전달한다.

@FeignClient(name = "mailgun", url = "https://api.mailgun.net/v3/")
@Qualifier(value = "mailgun")
public interface MailGunClient {

    @PostMapping("sandbox9fb170321f8b42a2a544e2bba68bce09.mailgun.org/messages")
    ResponseEntity<String> sendEmail(@SpringQueryMap SendMailForm form);


}

 

3. 테스트 코드를 통해서 잘 작동하는 지 확인한다.

@SpringBootTest
class EmailSendServiceTest {

    @Autowired
    private EmailSendService emailSendService;

    @Test
    public void emailTest(){
        String response = emailSendService.sendEmail().toString();
        System.out.println(response);
    }

}

 

 

[ 출처 ]

부트캠프 수업 내용 정리

https://techblog.woowahan.com/2657/