2017-02-17 8 views
1

저는 스프링 응용 프로그램을 사용하고 있으며 REST API를 기반으로하는 SOA 아키텍처를 사용하고 있습니다. 예를 들어 API를 가지고 있습니다 (http://myapp/api/createUser)응답으로 비동기 동작을 구현하는 방법 Java에서 응답을 반환하는 동안 전자 메일을 보내려면

그래서 사용자가 생성되면 즉시 사용자에게 이메일을 보내야합니다. 구현했지만 이메일을 보내고 성공/실패, 시간 소모.

스레드에서 전자 메일 부분을 시작하고 백그라운드에서 실행하고 사용자에게 메일을 보내어 API에서 즉시 성공 응답을 반환 할 수 있습니다. 또는 실패한 경우 데이터베이스에 로그인하십시오.

내가 메시지 큐를 구현하고 싶지 않은 API 또는 프레임 워크를 Rabbit MQ 또는 Active Queue와 같이 제안하십시오. 라이브 프로덕션 서버에서 스레드를 생성하여 문제가되지 않는 구현을 공유하십시오.

답변

2

이메일 전송 방법에 @Async를 사용하십시오.

참조 : http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html

예 :

@Async 
public void sendNotificaitoin(User user) throws MailException {  
    javaMailSender.send(mail); 
} 

이 일을 @Async 수 있도록 구성에서 @EnableAsync를 사용하십시오.

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

아래처럼 사용

 @RequestMapping("/signup-success") 
     public String signupSuccess(){ 

      // create user 
      User user = new User(); 
      user.setFirstName("Dan"); 
      user.setLastName("Vega"); 
      user.setEmailAddress("[email protected]"); 

      // send a notification 
      try { 
       notificationService.sendNotificaitoin(user); 
      }catch(Exception e){ 
       // catch error 
       logger.info("Error Sending Email: " + e.getMessage()); 
      } 

      return "Thank you for registering with us."; 
     } 
+0

을 내가 응답 전까지 notificationService.sendNotificaitoin (사용자)를 수신 할 수 없습니다 생각; 전송이 완료되었습니다. 확인 하시겠습니까? 이것이 어딘가에 쓰여진다면 문서를 보내라. –

+0

아니요, 실행하여 확인하십시오. sendNotificaitoin()은 async()로 표시됩니다. – mhshimul

+0

동기 동작을 계속 디버깅하려고했습니다. 메소드에 @Async를 넣었고, 스프링 부트를 사용하지 않고 app-config.xml에서 를 추가했습니다. EnableAsync?를 추가 할 위치를 모릅니다. 제발 도와 줄 수 있어요. –