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

[Refactor] #263 - User 데이터 캐싱 #265

Merged
merged 4 commits into from
Apr 11, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class ObjectiveService implements IndexService {
private final ObjectiveRepository objectiveRepository;

public void createObjective(final Long userId, final OKRCreateRequestDto request) {
User user = userRepository.findById(userId)
User user = userRepository.findByIdWithCache(userId)
.orElseThrow(() -> new NotFoundException(NOT_FOUND_USER));

List<Objective> objectives = objectiveRepository.findAllByUserId(userId);
Expand Down
35 changes: 35 additions & 0 deletions moonshot-auth/src/main/java/org/moonshot/config/CacheConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package org.moonshot.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Duration;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
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.SerializationPair;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
@RequiredArgsConstructor
public class CacheConfig {

private final RedisConnectionFactory redisConnectionFactory;
private final ObjectMapper objectMapper;

@Bean
public CacheManager redisCacheManager() {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.entryTtl(Duration.ofSeconds(60 * 60));

return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory).cacheDefaults(redisCacheConfiguration).build();
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.moonshot.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -8,10 +10,12 @@
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableRedisRepositories
@RequiredArgsConstructor
public class RedisConfig {

@Value("${redis.host}")
Expand All @@ -20,6 +24,8 @@ public class RedisConfig {
@Value("${redis.port}")
private int port;

private final ObjectMapper objectMapper;

@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
Expand All @@ -30,7 +36,7 @@ public RedisConnectionFactory redisConnectionFactory() {
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
redisTemplate.setConnectionFactory(redisConnectionFactory());
return redisTemplate;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class UserPrincipalDetailsService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findById(Long.parseLong(username))
return userRepository.findByIdWithCache(Long.parseLong(username))
.map(UserPrincipal::new)
.orElseThrow(UnauthorizedException::new);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.moonshot.user.repository;

import java.util.Optional;
import org.moonshot.user.model.User;

public interface UserCustomRepository {

Optional<User> findByIdWithCache(Long id);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.moonshot.user.repository;

import static org.moonshot.user.model.QUser.user;

import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.moonshot.user.model.User;
import org.springframework.cache.annotation.Cacheable;

@RequiredArgsConstructor
public class UserCustomRepositoryImpl implements UserCustomRepository {

private final JPAQueryFactory queryFactory;

@Override
@Cacheable(value = "user", cacheManager = "redisCacheManager")
public Optional<User> findByIdWithCache(final Long id) {
return Optional.ofNullable(queryFactory.selectFrom(user)
.where(user.id.eq(id)).fetchOne());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.moonshot.user.repository;


import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.moonshot.user.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface UserJpaRepository extends JpaRepository<User, Long> {

Optional<User> findUserBySocialId(String socialId);
Optional<User> findUserByNickname(String nickname);
@Query("SELECT u FROM User u WHERE u.deleteAt < :currentDate")
List<User> findIdByDeletedAtBefore(LocalDateTime currentDate);

}

Original file line number Diff line number Diff line change
@@ -1,19 +1,4 @@
package org.moonshot.user.repository;


import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.moonshot.user.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface UserRepository extends JpaRepository<User, Long> {

Optional<User> findUserBySocialId(String socialId);
Optional<User> findUserByNickname(String nickname);
@Query("SELECT u FROM User u WHERE u.deleteAt < :currentDate")
List<User> findIdByDeletedAtBefore(LocalDateTime currentDate);

public interface UserRepository extends UserJpaRepository, UserCustomRepository {
}

Loading