본문 바로가기
MSA/MSA관련기술

Redis 환경설정 방법

by 문자메일 2022. 11. 29.

 

1. build.gradle dependency에 redis 추가 필요

implementation 'org.springframework.boot:spring-boot-starter-data-redis'

 

2. application.yml 에 redis url 주소 입력

spring:

  redis:
    url: redis://127.0.0.1:6379

 

 

3. 레디스 설정 위한 RedisConfiguration.java 파일 생성 필요

@Configuration
@EnableRedisRepositories
@RequiredArgsConstructor
public class RedisConfiguration {

    private final RedisProperties redisProperties;

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        RedisURI redisURI = RedisURI.create(redisProperties.getUrl());
        org.springframework.data.redis.connection.RedisConfiguration configuration =
                LettuceConnectionFactory.createRedisConfiguration(redisURI);
        LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration);
        factory.afterPropertiesSet();
        return factory;
    }

    @Bean
    public RedisTemplate<String, User> userRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, User> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<User>(User.class));
        return redisTemplate;
    }
}

 

4. 레디스 레퍼지토리 생성

@Slf4j
@Repository
@RequiredArgsConstructor
public class UserCacheRepository {

    private final RedisTemplate<String, User> userRedisTemplate;
    private final static Duration USER_CACHE_TTL = Duration.ofDays(3);

    public void setUser(User user){
        String key = getKey(user.getUsername());
        log.info("Set User to Redis {}, {}", key, user);
        userRedisTemplate.opsForValue().set(key, user, USER_CACHE_TTL);
    }

    public Optional<User> getUser(String userName){
        String key = getKey(userName);
        User user = userRedisTemplate.opsForValue().get(key);
        log.info("Get data from Redis {} , {}", key, user);
        return Optional.ofNullable(user);
    }

    private String getKey(String userName){
        return "USER:" + userName;
    }
}

 

 

 

환경설정은 윗 부분까지 끝이고, 아래는 레디스 레퍼지토리 사용하는 코드 복붙

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserEntityRepository userEntityRepository;
    private final AlarmEntityRepository alarmEntityRepository;
    private final BCryptPasswordEncoder encoder;
    private final UserCacheRepository userCacheRepository;

    @Value("${jwt.secret-key}")
    private String secretKey;

    @Value("${jwt.token.expired-time-ms}")
    private Long expiredTimeMs;

    public User loadUserByUserName(String userName){
        return userCacheRepository.getUser(userName).orElseGet(()->
                        userEntityRepository.findByUserName(userName).map(User::fromEntity).orElseThrow(()->
                                new SnsApplicationException(ErrorCode.USER_NOT_FOUND, String.format("%s not founded", userName))
                        )
                );
    }

    @Transactional
    public User join(String userName, String password){
        // 회원가입하려는 userName으로 회원가입된 user가 있는지
        userEntityRepository.findByUserName(userName).ifPresent(it->{
            throw new SnsApplicationException(ErrorCode.DUPLICATED_USER_NAME, String.format("%s is duplicated", userName));
        });
        
        // 회원가입 진행  = user를 등록
        UserEntity userEntity = userEntityRepository.save(UserEntity.of(userName, encoder.encode(password)));

        return User.fromEntity(userEntity);
    }

    public String login(String userName, String password){
        // 회원가입 여부 체크
        User user = loadUserByUserName(userName);

        userCacheRepository.setUser(user);

        // 비밀번호 체크
        if(!encoder.matches(password, user.getPassword())){
            throw new SnsApplicationException(ErrorCode.INVALID_PASSWORD);
        }

        // 토큰 생성
        String token = JwtTokenUtils.generateToken(userName, secretKey, expiredTimeMs);

        return token;
    }

    // TODO : alarm return
    public Page<Alarm> alarmList(Integer userId, Pageable pageable){
        return alarmEntityRepository.findAllByUserId(userId, pageable).map(Alarm::fromEntity);
    }

}

'MSA > MSA관련기술' 카테고리의 다른 글

kafka 데이터 동기화 방법, connect  (0) 2022.12.04
kafka 설치 & 환경구성  (0) 2022.12.02
서버 성능 측정 방법  (0) 2022.11.29
도커 및 도커 컴포즈 정리  (1) 2022.11.10
MSA 정리  (1) 2022.10.14

댓글