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

prod 에서 작동하게 수정과 테스트를 위한 수정 #1

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@
public class BirthDayCouponBatchConfig {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
public final SqlSessionFactory sqlSessionFactory;
private final SqlSessionFactory sqlSessionFactory;
private final JobLauncher jobLauncher;
private final CouponMapper couponMapper;
private static final int CHUNK_SIZE = 10;
private static final int CHUNK_SIZE = 10000;

/**
* methodName : runJob <br>
Expand All @@ -69,7 +69,7 @@ public class BirthDayCouponBatchConfig {
* 제공한 입력이 유요하지 않은 경우 발생
* @throws JobRestartException 작업을 다시 시작하려는 불법적인 시도를 나타내는 예외
*/
@Scheduled(cron = "0 30 23 L * *")
@Scheduled(cron = "0 30 23 L * *", zone = "Asia/Seoul")
public void runJob() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException,
JobParametersInvalidException, JobRestartException {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package com.mybooks.batch.config.batch.usergradechangebatchconfig;

import com.mybooks.batch.useractualpayment.model.UserActualPayment;
import com.mybooks.batch.useractualpayment.model.UserGrade;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisBatchItemWriter;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.mybatis.spring.batch.builder.MyBatisBatchItemWriterBuilder;
import org.mybatis.spring.batch.builder.MyBatisPagingItemReaderBuilder;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

/**
* packageName : com.mybooks.batch.config.batch.usergradechangebatchconfig
* fileName : UserGradeChangeBatchConfig
* author : damho-lee
* date : 3/21/24
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 3/21/24 damho-lee 최초 생성
*/
@Configuration
@RequiredArgsConstructor
public class UserGradeChangeBatchConfig {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
private final SqlSessionFactory sqlSessionFactory;
private final JobLauncher jobLauncher;
private static final int CHUNK_SIZE = 10000;

/**
* methodName : runJob <br>
* author : damho-lee <br>
* description : 최근 3개월의 실결제금액에 따라 회원 등급 조회해서 회원등급 변경하는 Job 을 실행시키는 메서드. 3개월에 한 번 1일 오전 1시에 실행<br>
*
* @throws JobInstanceAlreadyCompleteException Job 이 이미 완료되어 실행시킬 Job 이 없다 -> JobParameter 가 다르면 다른 Job 으로 인식한다
* @throws JobExecutionAlreadyRunningException Job 이 이미 실행중이다 -> 스프링 배치가 DB 의 테이블을 참조하는데 배치 프로그램이
* 비정상적으로 종료되는 경우 DB 테이블에 완료되었다고 작성하지 못하기 때문에 발생
* @throws JobParametersInvalidException JobParameter 가 유요하지 않다 -> 필요한 Parameter 가 제공되지 않거나
* 제공한 입력이 유요하지 않은 경우 발생
* @throws JobRestartException 작업을 다시 시작하려는 불법적인 시도를 나타내는 예외
*/
@Scheduled(cron = "0 0 1 1 */3 *", zone = "Asia/Seoul")
public void runJob() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException,
JobParametersInvalidException, JobRestartException {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss");
String formattedDateTime = LocalDateTime.now().format(formatter);

JobParameters parameters = new JobParametersBuilder()
.addString("requestDate", formattedDateTime)
.toJobParameters();
jobLauncher.run(userGradeChangeJob(), parameters);
}

/**
* methodName : userGradeChangeJob <br>
* author : damho-lee <br>
* description : 회원 등급 변경 Job. <br>
*
* @return job
*/
@Bean
public Job userGradeChangeJob() {
return jobBuilderFactory.get("changeUserGradeJob")
.start(changeUserGradeStep(null))
.build();
}

/**
* methodName : changeUserGradeStep <br>
* author : damho-lee <br>
* description : 회원 등급 변경하는 Step. <br>
*
* @param requestDate String
* @return step
*/
@Bean
@JobScope
public Step changeUserGradeStep(@Value("#{jobParameters['requestDate']}") String requestDate) {
return stepBuilderFactory.get("changeUserGradeStep")
.<UserActualPayment, UserGrade>chunk(CHUNK_SIZE)
.reader(userActualPaymentReader(null))
.processor(userActualPaymentProcessor(null))
.writer(updateUserGradeWriter(null))
.build();
}

/**
* methodName : userActualPaymentReader <br>
* author : damho-lee <br>
* description : userId 와 최근 3개월의 실결제금액으로 어느 등급에 해당하는지(userGradeId)를 조회하는 reader. <br>
*
* @param requestDate String
* @return MyBatisPagingItemReader
*/
@Bean
@StepScope
public MyBatisPagingItemReader<UserActualPayment> userActualPaymentReader(
@Value("#{jobParameters['requestDate']}") String requestDate) {
return new MyBatisPagingItemReaderBuilder<UserActualPayment>()
.pageSize(CHUNK_SIZE)
.sqlSessionFactory(sqlSessionFactory)
.queryId("com.mybooks.batch.useractualpayment.mapper.UserActualPaymentMapper.getUserActualPayment")
.build();
}

/**
* methodName : userActualPaymentProcessor <br>
* author : damho-lee <br>
* description : 회원 아이디, 실결제금액, 회원 등급 아이디 -> 회원 아이디, 회원 등급 아이디로 변환하는 processor. <br>
*
* @param requestDate String
* @return ItemProcessor
*/
@Bean
@StepScope
public ItemProcessor<UserActualPayment, UserGrade> userActualPaymentProcessor(
@Value("#{jobParameters['requestDate']}") String requestDate) {
return userActualPayment -> new UserGrade(userActualPayment.getUserId(), userActualPayment.getUserGradeId());
}

/**
* methodName : updateUserGradeWriter <br>
* author : damho-lee <br>
* description : 회원 등급 변경하는 writer. 회원등급 변경일자는 현재시간으로.<br>
*
* @param requestDate String
* @return MyBatisBatchItemWriter
*/
@Bean
@StepScope
public MyBatisBatchItemWriter<UserGrade> updateUserGradeWriter(
@Value("#{jobParameters['requestDate']}") String requestDate) {
return new MyBatisBatchItemWriterBuilder<UserGrade>()
.sqlSessionFactory(sqlSessionFactory)
.statementId("com.mybooks.batch.useractualpayment.mapper.UserActualPaymentMapper.updateUserGrade")
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@
public class UserStatusChangeBatchConfig {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
public final SqlSessionFactory sqlSessionFactory;
private final SqlSessionFactory sqlSessionFactory;
private final JobLauncher jobLauncher;
private static final int CHUNK_SIZE = 10;
private static final int CHUNK_SIZE = 10000;

/**
* methodName : runJob <br>
Expand All @@ -62,7 +62,7 @@ public class UserStatusChangeBatchConfig {
* 제공한 입력이 유효하지 않은 경우 발생
* @throws JobRestartException 작업을 다시 시작하려는 시도를 나타내는 예외
*/
@Scheduled(cron = "0 0 0 * * *")
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Seoul")
public void runJob() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException,
JobParametersInvalidException, JobRestartException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.mybooks.batch.useractualpayment.mapper;

import com.mybooks.batch.useractualpayment.model.UserActualPayment;
import com.mybooks.batch.useractualpayment.model.UserGrade;
import org.apache.ibatis.annotations.Mapper;

/**
* packageName : com.mybooks.batch.useractualpayment.mapper
* fileName : UserActualPaymentMapper
* author : damho-lee
* date : 3/21/24
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 3/21/24 damho-lee 최초 생성
*/
@Mapper
public interface UserActualPaymentMapper {
UserActualPayment getUserActualPayment();

void updateUserGrade(UserGrade userGrade);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.mybooks.batch.useractualpayment.model;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
* packageName : com.mybooks.batch.order.model
* fileName : Order
* author : damho-lee
* date : 3/20/24
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 3/20/24 damho-lee 최초 생성
*/
@Getter
@AllArgsConstructor
public class UserActualPayment {
private Long userId;
private Integer actualPayment;
private Integer userGradeId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.mybooks.batch.useractualpayment.model;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
* packageName : com.mybooks.batch.useractualpayment.model
* fileName : UserGrade
* author : damho-lee
* date : 3/21/24
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 3/21/24 damho-lee 최초 생성
*/
@Getter
@AllArgsConstructor
public class UserGrade {
private Long userId;
private Integer userGradeId;
}
1 change: 1 addition & 0 deletions src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
database.mysql.url=65b73eab47984c8b9b70241c698406cd
6 changes: 4 additions & 2 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ key.manager.path=/keymanager/v1.0/appkey/{app-key}/secrets/{key-id}
key.manager.app-key=CuKPvJQR7enquqrZ
key.manager.password=mybooks
## mysql
database.mysql.url=65b73eab47984c8b9b70241c698406cd
database.mysql.userName=901b405fe80d4c00b14bc099a72a33ad
database.mysql.password=cda93b8395b641bfbe9a967cd60fdd49
database.mysql.initialSize=10
Expand All @@ -17,4 +16,7 @@ database.mysql.maxWait=1000
spring.application.name=batch-service
#mybatis
spring.batch.jdbc.initialize-schema=always
mybatis.executor-type=batch
mybatis.executor-type=batch
##
#spring.profiles.active=dev
database.mysql.url=9053ef8fd6e04a87aab73321a565c1b2
47 changes: 47 additions & 0 deletions src/main/resources/mapper/mybatis-useractualpaymentmapper.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybooks.batch.useractualpayment.mapper.UserActualPaymentMapper">
<select id="getUserActualPayment" resultType="com.mybooks.batch.useractualpayment.model.UserActualPayment">
<![CDATA[
SELECT bo.user_id,
(@actual_payment :=
SUM(COALESCE(total_order_cost, 0))
- SUM(COALESCE(total_wrap_cost, 0))
- SUM(COALESCE(total_delivery_cost, 0))) AS actual_payment,
(SELECT user_grade_id
FROM user_grade
WHERE is_available = true
AND user_grade_min <= @actual_payment
AND user_grade_max > @actual_payment) AS grade
FROM book_order AS bo
LEFT JOIN (SELECT order_id,
SUM(order_total_cost) AS total_order_cost
FROM book_order
WHERE book_order.order_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH)
GROUP BY order_id) AS order_totals ON bo.order_id = order_totals.order_id
LEFT JOIN (SELECT od2.order_id,
order_detail_id,
SUM(w.wrap_cost) AS total_wrap_cost
FROM wrap AS w
LEFT JOIN order_detail AS od2 ON w.wrap_id = od2.wrap_id
WHERE od2.order_detail_created_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH)
GROUP BY order_detail_id) AS wrap_cost_totals
ON order_totals.order_id = wrap_cost_totals.order_id
LEFT JOIN (SELECT order_id,
SUM(dr.delivery_cost) AS total_delivery_cost
FROM book_order AS bo2
LEFT JOIN delivery_rule AS dr ON bo2.delivery_rule_id = dr.delivery_rule_id
WHERE bo2.order_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH)
GROUP BY order_id) AS delivery_cost_totals ON bo.order_id = delivery_cost_totals.order_id
GROUP BY bo.user_id
ORDER BY user_id;
]]>
</select>

<update id="updateUserGrade" parameterType="com.mybooks.batch.useractualpayment.model.UserGrade">
UPDATE user
SET user_grade_id = #{userGradeId},
user_grade_changed_date = CURRENT_DATE
WHERE user_id = #{userId}
</update>
</mapper>
Loading