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

Feat: RedisCache를 통한 캐싱 적용 (#44) #45

Merged
merged 3 commits into from
Oct 31, 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
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ dependencies {
// Jwt dependency
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' // Spring Boot MyBatis
implementation "io.jsonwebtoken:jjwt:0.9.1"

// Redis dependency
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
}

tasks.named('test') {
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/diareat/diareat/DiareatApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class DiareatApplication {

Expand Down
26 changes: 26 additions & 0 deletions src/main/java/com/diareat/diareat/config/RedisCacheConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.diareat.diareat.config;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisCacheConfig { // Redis Cache 설정

@Bean
public CacheManager diareatCacheManager(RedisConnectionFactory cf) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.entryTtl(Duration.ofMinutes(3L)); // 캐시 만료 시간 3분
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(cf).cacheDefaults(redisCacheConfiguration).build();
}
}
21 changes: 10 additions & 11 deletions src/main/java/com/diareat/diareat/user/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import com.diareat.diareat.util.api.ResponseCode;
import com.diareat.diareat.util.exception.UserException;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand Down Expand Up @@ -40,6 +42,7 @@ public Long saveUser(CreateUserDto createUserDto) {
}

// 회원 기본정보 조회
@Cacheable(value = "ResponseSimpleUserDto", key = "#userId", cacheManager = "diareatCacheManager")
@Transactional(readOnly = true)
public ResponseSimpleUserDto getSimpleUserInfo(Long userId) {
User user = getUserById(userId);
Expand All @@ -48,13 +51,15 @@ public ResponseSimpleUserDto getSimpleUserInfo(Long userId) {
}

// 회원정보 조회
@Cacheable(value = "ResponseUserDto", key = "#userId", cacheManager = "diareatCacheManager")
@Transactional(readOnly = true)
public ResponseUserDto getUserInfo(Long userId) {
User user = getUserById(userId);
return ResponseUserDto.from(user);
}

// 회원정보 수정
@CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto"}, key = "#updateUserDto.userId", cacheManager = "diareatCacheManager")
@Transactional
public void updateUserInfo(UpdateUserDto updateUserDto) {
User user = getUserById(updateUserDto.getUserId());
Expand All @@ -63,6 +68,7 @@ public void updateUserInfo(UpdateUserDto updateUserDto) {
}

// 회원 기준섭취량 조회
@Cacheable(value = "ResponseUserNutritionDto", key = "#userId", cacheManager = "diareatCacheManager")
@Transactional(readOnly = true)
public ResponseUserNutritionDto getUserNutrition(Long userId) {
User user = getUserById(userId);
Expand All @@ -71,6 +77,7 @@ public ResponseUserNutritionDto getUserNutrition(Long userId) {
}

// 회원 기준섭취량 직접 수정
@CacheEvict(value = "ResponseUserNutritionDto", key = "#updateUserNutritionDto.userId", cacheManager = "diareatCacheManager")
@Transactional
public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) {
User user = getUserById(updateUserNutritionDto.getUserId());
Expand All @@ -80,13 +87,14 @@ public void updateBaseNutrition(UpdateUserNutritionDto updateUserNutritionDto) {
}

// 회원 탈퇴
@CacheEvict(value = {"ResponseSimpleUserDto", "ResponseUserDto", "ResponseUserNutritionDto"}, key = "#userId", cacheManager = "diareatCacheManager")
@Transactional
public void deleteUser(Long userId) {
validateUser(userId);
userRepository.deleteById(userId);
}

// 회원의 친구 검색 결과 조회
// 회원의 친구 검색 결과 조회 -> 검색 및 팔로우는 굉장히 돌발적으로 이루어질 가능성이 높아 캐시 적용 X
@Transactional(readOnly = true)
public List<ResponseSearchUserDto> searchUser(Long hostId, String name) {
validateUser(hostId);
Expand Down Expand Up @@ -118,15 +126,6 @@ public void unfollowUser(Long userId, Long unfollowId) {
followRepository.delete(Follow.makeFollow(userId, unfollowId));
}

// 회원의 팔로우 목록 조회 (현재 외부 Dto 변환은 Food에서 위임받아 진행할지 협의하지 않았기에 일단 User 리스트로 반환)
@Transactional(readOnly = true)
public List<User> getFollowList(Long userId) {
validateUser(userId);
List<User> users = followRepository.findAllByFromUser(userId);
users.add(getUserById(userId)); // 자기 자신도 랭킹에 포함
return users;
}

private void validateUser(Long userId) {
if (!userRepository.existsById(userId))
throw new UserException(ResponseCode.USER_NOT_FOUND);
Expand All @@ -136,4 +135,4 @@ private User getUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND));
}
}
}
7 changes: 6 additions & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@
spring.profiles.include = db

# swagger
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

# redis
spring.redis.serializer=org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
spring.cache.type=redis
spring.cache.redis.cache-null-values=true