88import jakarta .transaction .Transactional ;
99import lombok .RequiredArgsConstructor ;
1010import lombok .extern .slf4j .Slf4j ;
11+ import org .springframework .cache .annotation .CacheEvict ;
12+ import org .springframework .cache .annotation .Cacheable ;
13+ import org .springframework .cache .annotation .Caching ;
1114import org .springframework .dao .DataIntegrityViolationException ;
1215import org .springframework .security .core .parameters .P ;
1316import org .springframework .stereotype .Service ;
@@ -23,6 +26,10 @@ public class LikeServiceImpl implements LikeService {
2326
2427 @ Override
2528 @ Transactional
29+ @ Caching (evict = {
30+ @ CacheEvict (cacheNames = "likeCount" , key = "#targetType + ':' + #targetId" ),
31+ @ CacheEvict (cacheNames = "likeStatus" , key = "#user.id + ':' + #targetType + ':' + #targetId" )
32+ })
2633 public LikeResponse toggleLike (User user , LikeTargetType targetType , Long targetId ) {
2734
2835 boolean liked = false ; // 좋아요 여부 변수
@@ -39,18 +46,20 @@ public LikeResponse toggleLike(User user, LikeTargetType targetType, Long target
3946 likeRepository .save (like );
4047 liked = true ;
4148 }
42-
43- long likeCount = getLikeCount (targetType , targetId ); // 해당 타겟(게시물 or 댓글)의 좋아요 개수 저장 변수
49+ // 토글 응답은 최신 값이 필요하므로 레포로 직접 count
50+ long likeCount = likeRepository . countByTargetTypeAndTargetId (targetType , targetId );
4451
4552 return LikeResponse .of (liked , targetType , targetId , likeCount );
4653 }
4754
4855 @ Override
56+ @ Cacheable (cacheNames = "likeStatus" , key = "#user.id + ':' + #targetType + ':' + #targetId" )
4957 public boolean isLiked (User user , LikeTargetType targetType , Long targetId ) {
5058 return likeRepository .existsByUserAndTargetTypeAndTargetId (user , targetType , targetId );
5159 }
5260
5361 @ Override
62+ @ Cacheable (cacheNames = "likeCount" , key = "#targetType + ':' + #targetId" )
5463 public long getLikeCount (LikeTargetType targetType , Long targetId ) { // 좋아요 개수 추적 메서드
5564 return likeRepository .countByTargetTypeAndTargetId (targetType , targetId );
5665 }
0 commit comments