Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REFACTOR] 메일 비동기 전송 구현 #276

Merged
merged 3 commits into from
Apr 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ public void approveApplicant(Long postId, Long userId, List<Long> applicantIds)

RecruitmentPost recruitmentPost = recruitmentPostService.getRecruitmentPost(postId);
User user = userService.findById(recruitmentPost.getCreatedBy());
mailService.sendApproveMails(postId, applicants, user.getName());

applicants.stream().forEach(
applicant -> mailService.sendApproveMail(postId, applicant, user.getName())
);
}

@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
public interface RecruitmentApplicantRepository extends JpaRepository<RecruitmentApplicant, Long>,
RecruitmentApplicantCustomRepository {

@Query("SELECT a FROM RecruitmentApplicant a JOIN FETCH a.recruitmentPost WHERE a.id IN :ids AND a.deleteStatus = synk.meeteam.global.entity.DeleteStatus.ALIVE")
@Query("SELECT a FROM RecruitmentApplicant a JOIN FETCH a.recruitmentPost JOIN FETCH a.applicant WHERE a.id IN :ids AND a.deleteStatus = synk.meeteam.global.entity.DeleteStatus.ALIVE")
List<RecruitmentApplicant> findAllInApplicantId(@Param("ids") List<Long> applicantIds);

Optional<RecruitmentApplicant> findByRecruitmentPostAndApplicantAndDeleteStatus(RecruitmentPost recruitmentPost,
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/synk/meeteam/global/config/AsyncConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package synk.meeteam.global.config;

import java.util.concurrent.Executor;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport {

public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2); // 기본적으로 실행 대기 중인 Thread 개수
executor.setMaxPoolSize(10); // 동시에 동작하는 최대 Thread 개수
executor.setQueueCapacity(500); // CorePool이 초과될때 Queue에 저장했다가 꺼내서 실행된다. (500개까지 저장함)

executor.setThreadNamePrefix("async-"); // Spring에서 생성하는 Thread 이름의 접두사
executor.initialize();
return executor;
}
}
54 changes: 27 additions & 27 deletions src/main/java/synk/meeteam/infra/mail/MailService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMessage.RecipientType;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
Expand Down Expand Up @@ -74,6 +74,7 @@ public String generateEmailVerifyMailForm(String userName, String emailCode) {
return templateEngine.process(MAIL_VERIFY_TEMPLATE, context);
}

@Async
mikekks marked this conversation as resolved.
Show resolved Hide resolved
@Transactional
public void sendVerifyMail(String platformId, String receiverMail) {
String newEmailCode = UUID.randomUUID().toString();
Expand All @@ -100,35 +101,34 @@ public void sendVerifyMail(String platformId, String receiverMail) {
}
}


@Async
@Transactional
public void sendApproveMails(Long postId, List<RecruitmentApplicant> applicants, String writerName) {
if (applicants == null) {
return;
}
public void sendApproveMail(Long postId, RecruitmentApplicant recruitmentApplicant, String writerName) {

MimeMessage message = mailSender.createMimeMessage();

for (RecruitmentApplicant recruitmentApplicant : applicants) {
User applicant = recruitmentApplicant.getApplicant();
String receiverMail =
applicant.isUniversityMainEmail() ? applicant.getUniversityEmail() : applicant.getSubEmail();

try {
message.addRecipients(RecipientType.TO, receiverMail);// 받는 대상
message.setSubject(MAIL_TITLE_APPROVE);// 제목

String body = generateApproveMailForm(applicant.getName(), postId.toString(),
recruitmentApplicant.getRecruitmentPost().getTitle(),
recruitmentApplicant.getRole().getName(), writerName,
recruitmentApplicant.getRecruitmentPost().getKakaoLink());

message.setText(body, CHAR_SET, SUB_TYPE);// 내용, charset 타입, subtype
// 보내는 사람의 이메일 주소, 보내는 사람 이름
message.setFrom(new InternetAddress(SENDER_ADDRESS, SENDER));// 보내는 대상
mailSender.send(message); // 메일 전송
} catch (Exception e) {
log.info("{}", e);
throw new AuthException(INVALID_MAIL_SERVICE);
}
User applicant = recruitmentApplicant.getApplicant();

String receiverMail =
applicant.isUniversityMainEmail() ? applicant.getUniversityEmail() : applicant.getSubEmail();

try {
message.addRecipients(RecipientType.TO, receiverMail);// 받는 대상
message.setSubject(MAIL_TITLE_APPROVE);// 제목

String body = generateApproveMailForm(applicant.getName(), postId.toString(),
recruitmentApplicant.getRecruitmentPost().getTitle(),
recruitmentApplicant.getRole().getName(), writerName,
recruitmentApplicant.getRecruitmentPost().getKakaoLink());

message.setText(body, CHAR_SET, SUB_TYPE);// 내용, charset 타입, subtype
// 보내는 사람의 이메일 주소, 보내는 사람 이름
message.setFrom(new InternetAddress(SENDER_ADDRESS, SENDER));// 보내는 대상
mailSender.send(message); // 메일 전송
} catch (Exception e) {
log.info("{}", e);
throw new AuthException(INVALID_MAIL_SERVICE);
}

}
Expand Down
Loading