-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathLikeEventHandler.java
More file actions
60 lines (52 loc) · 2.28 KB
/
LikeEventHandler.java
File metadata and controls
60 lines (52 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.loopers.application.like;
import com.loopers.domain.like.event.LikeCreatedEvent;
import com.loopers.domain.like.event.LikeDeletedEvent;
import com.loopers.domain.product.ProductRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionalEventListener;
import static org.springframework.transaction.event.TransactionPhase.AFTER_COMMIT;
@Slf4j
@Component
@RequiredArgsConstructor
public class LikeEventHandler {
private final ProductRepository productRepository;
@Async
@TransactionalEventListener(phase = AFTER_COMMIT)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void handleLikeCreated(LikeCreatedEvent event) {
try {
productRepository.findByIdForUpdate(event.productId())
.ifPresent(product -> {
product.increaseLikeCount();
productRepository.save(product);
});
log.info("좋아요 집계 증가 완료 - productId={}, userId={}",
event.productId(), event.userId());
} catch (Exception e) {
log.error("좋아요 집계 증가 실패 - productId={}, error={}",
event.productId(), e.getMessage());
}
}
@Async
@TransactionalEventListener(phase = AFTER_COMMIT)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void handleLikeDeleted(LikeDeletedEvent event) {
try {
productRepository.findByIdForUpdate(event.productId())
.ifPresent(product -> {
product.decreaseLikeCount();
productRepository.save(product);
});
log.info("좋아요 집계 감소 완료 - productId={}, userId={}",
event.productId(), event.userId());
} catch (Exception e) {
log.error("좋아요 집계 감소 실패 - productId={}, error={}",
event.productId(), e.getMessage());
}
}
}