Redis 적용기

‍서지오·2023년 9월 17일
0

Server Study

목록 보기
11/11

1. Redis 도커 이미지 pull 및 실행

docker pull redis
docker run -d -t -p 4379:6379 --name redis redis --requirepass "{myPassword}"
  • 도커 run 명령어 시 —requirepass 옵션으로 redis에 비밀번호를 설정

2. redis 컨테이너에 접속

docker exec -it redis /bin/bash //접속 완료

root@a770a65ae1b3:/data# redis-cli
127.0.0.1:6379> keys *
(error) NOAUTH Authentication required.

127.0.0.1:6379> auth 8625
OK

127.0.0.1:6379> keys *
(empty array)
  • docker exec 명령어로 컨테이너에 접속
  • redis-cli : redis를 명령어로 관리하도록 redis 내 접속
  • auth : redis 컨테이너를 실행할 때 넣어줬던 비밀번호로 인증을 거침
  • keys * : 모든 키 조회

3. Spring data RedisRepository

  1. redis.yml

    spring:
      redis:
        host: i9a603.p.ssafy.io
        port: 4379
        password: 8625
    • host : host 주소 지정
    • port : port 지정
    • password : 암호 지정
  2. RedisConfig

    package pokerface.pokerface.config.redis;
    
    import lombok.Getter;
    import lombok.RequiredArgsConstructor;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
    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.StringRedisSerializer;
    
    @Getter
    @Configuration
    @RequiredArgsConstructor
    @EnableRedisRepositories // Redis Repository 활성화
    public class RedisConfig {
    
        @Value("${spring.redis.host}")
        private String host;
    
        @Value("${spring.redis.port}")
        private int port;
    
        @Value("${spring.redis.password}")
        private String password;
    
        /**
         * ec2내 Redis 컨테이너에 연결
         */
        @Bean
        public RedisConnectionFactory redisConnectionFactory(){
            RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
            redisStandaloneConfiguration.setHostName(host); // host 설정
            redisStandaloneConfiguration.setPort(port); // port 설정
            redisStandaloneConfiguration.setPassword(password); // password 설정
    
            return new LettuceConnectionFactory(redisStandaloneConfiguration);
        }
    
        /**
         * RedisConnection에서 넘겨준 byte 값 객체 직렬화
         */
        @Bean
        public RedisTemplate<?,?> redisTemplate(){
            RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory());
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(new StringRedisSerializer());
            return redisTemplate;
        }
    }
    • Redis Template 사용
    • redis에 data가 알아볼 수 있도록 저장되기 위해 직렬화를 거친다.
  3. Room(redis에서 사용할 엔티티)

    package pokerface.pokerface.domain.room.entity;
    
    import lombok.*;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.redis.core.RedisHash;
    import org.springframework.data.redis.core.index.Indexed;
    import pokerface.pokerface.domain.member.entity.Member;
    
    import java.util.List;
    
    @Getter
    @Setter
    @RedisHash(value = "room", timeToLive = 100000)
    @NoArgsConstructor
    @ToString
    public class Room {
        @Id
        private String sessionId;
    
        @Indexed
        private String title;
    
        @Indexed
        private String gameMode;
    
        private Boolean isPrivate;
    
        private String roomPassword;
    
        private List<Member> members;
    
        @Builder
        public Room(String sessionId, String gameMode, String title, Boolean isPrivate, String roomPassword, List<Member> members) {
            this.sessionId = sessionId;
            this.gameMode = gameMode;
            this.title = title;
            this.isPrivate = isPrivate;
            this.roomPassword = roomPassword;
            this.members = members;
        }
    }
    • 객체는 Redis에 Hash 자료구조로 저장되게 된다.
      • *keyspace:@id : 형태로 저장된다.*
    • @RedisHash(value = "room", timeToLive = 100000) : redis에서 관리할 객체라는 걸 명시
      • value : keyspace
      • timeToLive : redis에 데이터를 보관할 기간(초 단위)
    • @Id : 같은 key들 간 구분하는 식별자의 역할을 한다.
    • @Indexed : second key를 두어 조회를 더욱 빠르게 해준다.

    4. Redis 특징

    • key : value 형태로 data 저장
      • *keyspace:@id” : 형태를 띔*
    • value로 지닐 수 있는 자료구조들이 다양함
      • String
      • Lists
      • Set
      • Sorted Sets
      • Hashes
      • Bit arrays
      • HyperLogLogs
      • Streams
    • 자료구조에 따라 조회, 저장, 삭제 명령어가 다르다!
    • keys * : 모든 키 조회
    • get : 특정 key에 해당하는 value 값 조회
    • getall : 특정 key에 해당하는 모든 value 조회

    참고자료
    https://wildeveloperetrain.tistory.com/243

profile
백엔드 개발자를 꿈꾸는 학생입니다!

0개의 댓글