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

[feature/3-cronJob] 쥬시글 변환 크론잡 추가 #26

Merged
merged 2 commits into from
Sep 19, 2023
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
2 changes: 2 additions & 0 deletions src/main/java/com/ewhatever/qna/QnaApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
public class QnaApplication {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ public interface AnswerRepository extends JpaRepository<Answer, Long> {
Long countByAnswerer_UserIdxAndStatusEquals(Long userIdx, String status);
Page<Answer> findByAnswerer_UserIdxAndPost_IsJuicyAndStatusEquals(Long userIdx, Boolean isJuicy, String status, Pageable pageable);
Long countByPost_PostIdxAndStatusEquals(Long postIdx, String status);
int countByPostAndIsJuicyFalse(Post post);
Long countByPost(Post post);
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void addAnswer(Long userIdx, PostAnswerReq postAnswerReq) throws BaseExce
try {
User user = userRepository.findByUserIdxAndStatusEquals(userIdx, ACTIVE).orElseThrow(() -> new BaseException(INVALID_USER));
Post post = postRepository.findById(postAnswerReq.getPostIdx()).orElseThrow(() -> new BaseException(INVALID_POST_IDX));
int currentAnswerCount = answerRepository.countByPostAndIsJuicyFalse(post);
Long currentAnswerCount = answerRepository.countByPost(post);
if (user.getRole().equals(SINY)) {
if (currentAnswerCount < 3) { // 크론잡 주기 사이에 답변이 등록되어 isJuicy 컬럼값에 아직 반영이 안된 경우를 위해 예외처리
Answer answer = Answer.builder()
Expand All @@ -36,7 +36,7 @@ public void addAnswer(Long userIdx, PostAnswerReq postAnswerReq) throws BaseExce
.build();
answerRepository.save(answer);

currentAnswerCount = answerRepository.countByPostAndIsJuicyFalse(post); //currentAnswerCount 최신화
currentAnswerCount = answerRepository.countByPost(post); //currentAnswerCount 최신화
// 3번째 답변이면 쥬시글로 전환
if (currentAnswerCount == 3) {
post.setIsJuicy(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
Page<Post> findAllByIsJuicyTrue(Pageable pageable);
Expand All @@ -24,4 +26,6 @@ public interface PostRepository extends JpaRepository<Post, Long> {

@Query("SELECT CASE WHEN COUNT(p) > 0 THEN true ELSE false END FROM Post p WHERE (p.title LIKE CONCAT('%', :searchWord, '%') OR p.content LIKE CONCAT('%', :searchWord, '%')) AND p.isJuicy = true")
boolean existsJuicyPosts(@Param("searchWord") String searchWord);

List<Post> findAllByIsJuicyFalse();
}
27 changes: 26 additions & 1 deletion src/main/java/com/ewhatever/qna/post/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -142,7 +145,6 @@ public GetPostRes getPost(Long postIdx, Long userIdx) throws BaseException {
User user = userRepository.findByUserIdxAndStatusEquals(userIdx, ACTIVE).orElseThrow(() -> new BaseException(INVALID_USER));
return new GetPostRes(post.getCategory().toString(), getCardList(post), post.getLastModifiedDate(),
post.getCommentCount(), post.getScrapCount(), isScrap(user, post), getCommentList(post, user));

} catch (BaseException e) {
throw e;
} catch (Exception e) {
Expand Down Expand Up @@ -224,4 +226,27 @@ public void scrapPost(Long postIdx, Long userIdx) throws BaseException {
throw new BaseException(DATABASE_ERROR);
}
}

/**
* 매 시간 쥬시글 여부 확인해서 변환해주는 크론잡
*/
@Scheduled(cron = "0 0 0/1 * * *")
@Transactional(rollbackFor = Exception.class)
public void checkJuicy() {
List<Post> postList = postRepository.findAllByIsJuicyFalse();
for (Post post : postList) {
LocalDateTime currentDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
// System.out.println("현재 시간: " + currentDateTime);
LocalDateTime questionDateTime = post.getCreatedDate().truncatedTo(ChronoUnit.HOURS);
// System.out.println("질문 등록 시간: " + questionDateTime);
// int compareResult = currentDateTime.compareTo(questionDateTime);
// System.out.println("비교 결과: " + compareResult);
// Period period = Period.between(questionDate, currentDate);
long timeGap = ChronoUnit.HOURS.between(questionDateTime, currentDateTime);
if (timeGap == 72) {
post.setIsJuicy(true);
postRepository.save(post);
}
}
}
}