Skip to content

Commit

Permalink
⚡️ [FEAT] 캐시 제외
Browse files Browse the repository at this point in the history
  • Loading branch information
20210815 committed Dec 7, 2024
1 parent dd9a983 commit 9f76085
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@
import com.carely.backend.dto.news.CreateNewsDTO;
import com.carely.backend.dto.news.NewsResponseDTO;
import com.carely.backend.dto.response.ResponseDTO;
import com.carely.backend.dto.user.CustomUserDetails;
import com.carely.backend.service.NewsService;
import com.carely.backend.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

Expand All @@ -26,9 +24,9 @@ public class NewsController implements NewsAPI {
private final UserService userService;

@GetMapping("/group/{groupId}")
public ResponseEntity<ResponseDTO> getGroupNewsList(@PathVariable("groupId") Long groupId, @AuthenticationPrincipal CustomUserDetails user) {
public ResponseEntity<ResponseDTO> getGroupNewsList(@PathVariable("groupId") Long groupId) {

List<NewsResponseDTO.List> res = newsService.getGroupNewsList(groupId, user.getUsername());
List<NewsResponseDTO.List> res = newsService.getGroupNewsList(groupId);

return ResponseEntity
.status(SuccessCode.SUCCESS_RETRIEVE_NEWS.getStatus().value())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,15 @@
import com.carely.backend.dto.news.CreateCommentDTO;
import com.carely.backend.dto.news.CreateNewsDTO;
import com.carely.backend.dto.response.ResponseDTO;
import com.carely.backend.dto.user.CustomUserDetails;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

public interface NewsAPI {
@Operation(summary = "groupId에 해당하는 소식 목록 보기", description = "groupId에 해당하는 소식 목록을 조회합니다.")
public ResponseEntity<ResponseDTO> getGroupNewsList(@PathVariable("groupId") Long groupId, @AuthenticationPrincipal CustomUserDetails user);

public ResponseEntity<ResponseDTO> getGroupNewsList(@PathVariable("groupId") Long groupId);

@Operation(summary = "소식 상세보기", description = "소식에 달린 답글과 함께 소식을 조회합니다.")
public ResponseEntity<ResponseDTO> getNewsDetail(@PathVariable("newsId") Long newsId);
Expand Down
35 changes: 5 additions & 30 deletions src/main/java/com/carely/backend/service/NewsService.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,36 +29,19 @@ public class NewsService {
private final GroupRepository groupRepository;
private final NewsCommentRepository newsCommentRepository;
private final UserRepository userRepository;
private final CacheService cacheService;


public List<NewsResponseDTO.List> getGroupNewsList(Long groupId, String kakaoId) {
// 1. 캐시에서 데이터 조회
String cacheKey = "groupNews:" + kakaoId;
List<NewsResponseDTO.List> cachedResult = cacheService.get(cacheKey);
if (cachedResult != null) {
return cachedResult; // 캐시 데이터 반환
}

// 3. 그룹 조회 (예외 발생 가능)
public List<NewsResponseDTO.List> getGroupNewsList(Long groupId) {
Group group = groupRepository.findById(groupId)
.orElseThrow(() -> new GroupNotFoundException("그룹을 찾을 수 없습니다."));

// 4. 뉴스 목록 조회
List<News> newsList = newsRepository.findAllByGroupOrderByCreatedAtDesc(group);
List<News> newsList;
newsList = newsRepository.findAllByGroupOrderByCreatedAtDesc(group);

// 5. DTO 변환
List<NewsResponseDTO.List> result = newsList.stream()
return newsList.stream()
.map(NewsResponseDTO.List::toDTO)
.toList();

// Redis에 캐시 저장
cacheService.save(cacheKey, result);

return result;
.collect(Collectors.toList());
}


public NewsResponseDTO.Detail getNewsDetail(Long newsId) {
News news = newsRepository.findById(newsId)
.orElseThrow(() -> new NewsNotFoundException("그룹을 찾을 수 없습니다."));
Expand All @@ -82,10 +65,6 @@ public CreateNewsDTO.Res createNews(Long groupId, @Valid CreateNewsDTO createNew
.build();

News newNews = newsRepository.save(news);

String cacheKey = "groupNews:" + kakaoId;
cacheService.evict(cacheKey);

return CreateNewsDTO.Res.toDTO(newNews);
}

Expand All @@ -104,10 +83,6 @@ public CreateCommentDTO.Res createComment(Long newsId, @Valid CreateCommentDTO c
.build();

NewsComment newsComment = newsCommentRepository.save(comment);

// 캐시 무효화
String cacheKey = "groupNews:" + kakaoId;
cacheService.evict(cacheKey);
return CreateCommentDTO.Res.toDTO(newsComment);
}
}
37 changes: 4 additions & 33 deletions src/main/java/com/carely/backend/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class UserService {
private final VolunteerRepository volunteerRepository;
private final OCRService ocrService;
private final GuestBookRepository guestBookRepository;
private final CacheService cacheService;

public RegisterDTO.Res register(RegisterDTO registerDTO, MultipartFile file) throws IOException {

String imageUrl = null;
Expand Down Expand Up @@ -104,20 +104,6 @@ public RegisterDTO.Res register(RegisterDTO registerDTO, MultipartFile file) thr
.certificateImage(imageUrl)
.build();


// 같은 도시(city)에 있는 회원만 갱신
List<String> affectedKakaoIds = userRepository.findByCity(user.getCity())
.stream()
.map(User::getKakaoId)
.filter(kakaoId1 -> !kakaoId1.equals(user.getKakaoId())) // 본인은 제외
.toList();

for (String kakaoId1 : affectedKakaoIds) {
String cacheKey = "userList:" + kakaoId1;
cacheService.evict(cacheKey); // 캐시 무효화
findAllUsersByCityAndUserTypes(List.of(UserType.ALL), kakaoId);
}

return RegisterDTO.Res.toDTO(userRepository.save(user));
}

Expand All @@ -137,7 +123,6 @@ private static int getAge(String identify) {

LocalDate birthDate = LocalDate.of(year, month, day);
LocalDate currentDate = LocalDate.now();

return Period.between(birthDate, currentDate).getYears() + 1; // 만나이 아님
}

Expand Down Expand Up @@ -315,29 +300,15 @@ public List<MapUserDTO> findAllUsers(String kakaoId) {


public List<MapUserDTO> findAllUsersByCityAndUserTypes(List<UserType> userTypes, String kakaoId) {
// 캐시에서 데이터 조회
String cacheKey = "userList:" + kakaoId;
List<MapUserDTO> cachedUsers = cacheService.get(cacheKey);

if (cachedUsers != null) {
return cachedUsers;
}

// 캐시 미존재 시 데이터베이스에서 조회
User viewer = userRepository.findByKakaoId(kakaoId)
.orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다."));

List<User> users = userRepository.findByUserTypeIn(userTypes);

List<MapUserDTO> result = users.stream()
.filter(user -> !user.getKakaoId().equals(kakaoId)) // 본인 제외
return users.stream()
.filter(user -> !user.getKakaoId().equals(kakaoId)) // 본인 제외
.map(user -> new MapUserDTO().toDTO(user, calculateTotalDuration(user, viewer), viewer))
.collect(Collectors.toList());

// 캐시에 저장 (TTL 1시간)
cacheService.save(cacheKey, result);

return result;
.collect(Collectors.toList()); // 빈 리스트도 collect로 반환
}

// 간병인 리스트 추천
Expand Down

0 comments on commit 9f76085

Please sign in to comment.