Home Spring Redis
Post
Cancel

Spring Redis

정리 코드

Spring Redis 연동하기

개발 환경 : Spring boot 3.2.2, java17

의존성

1
2
3
4
5
6
7
8
  dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
  }


docker-redis 구축 : docker redis 구축 방법


Spring boot application 설정 : 추후 환경 설정을 위해 설정 프로필을 분리 설정

1
2
3
4
5
6
7
8
9
10
 application.yaml 설정
 spring:
   profiles:
    active: data

 application-data.yaml 설정
 data:
   redis:
     host: 127.0.0.1
     port: 6379


RedisConfig 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@Slf4j
@Configuration
public class RedisConfig {

    @Value("${data.redis.host}")
    private String HOST;

    @Value("${data.redis.port}")
    private int PORT;


    @Bean("sessionRedisConnectionsFactory")
    public RedisConnectionFactory sessionRedisConnectionsFactory() {
        return redisConnectionFactory(HOST, PORT);
    }

    @Bean("sessionRedisTemplate")
    public RedisTemplate<String, Object> sessionRedisTemplate() {
        return returnRedisTemplate(sessionRedisConnectionsFactory());
    }

    private RedisConnectionFactory redisConnectionFactory(final String host, final int port) {
        return new LettuceConnectionFactory(host, port);
    }

    private RedisTemplate<String, Object> returnRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));

        redisTemplate.setDefaultSerializer(new Jackson2JsonRedisSerializer<>(Object.class));

        return redisTemplate;
    }

}


Spring Redis CrudRepository 구성

  • 1 ] spring redis entity
  • 2 ] spring redis repository
  • 3 ] spring redis service
  • 4 ] 서비스 테스트


spring redis entity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Getter
@Setter
@ToString
@NoArgsConstructor
@RedisHash(value = "user") // timeToLive 옵션으로 세션 타임 설정 가능
public class RedisUserSession {

    @Id //  RedisHash value 뒤에 붙는 해쉬값
    private String hash;

    private String userId;

    private String password;

    private LocalDateTime signIn;

    @Builder
    public RedisUserSession(String userId, String password) {
        this.userId = userId;
        this.password = password;
        this.signIn = LocalDateTime.now();
    }

}


spring redis repository

1
2
3
4
import org.spring.redis.entity.redis.RedisUserSession;
import org.springframework.data.repository.CrudRepository;
public interface RedisUserSessionRepository extends CrudRepository<RedisUserSession, String> {
}


spring redis service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface RedisUserSessionService {
    RedisUserSession saveRedisUserSession(RedisUserSession redisUserSession);
}

@Slf4j
@Service
@RequiredArgsConstructor
public class RedisUserSessionServiceImpl implements RedisUserSessionService {
    private final RedisUserSessionRepository redisUserSessionRepository;
    @Override
    public RedisUserSession saveRedisUserSession(RedisUserSession redisUserSession) {
        RedisUserSession result = redisUserSessionRepository.save(redisUserSession);
        log.info("result = {}", result);
        return result;
    }
}


redis service test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@SpringBootTest
public class RedisRepositoryTest {

    @Autowired
    RedisUserSessionService redisUserSessionService;

    @Test
    public void redis_user_session_set_test() {
        RedisUserSession redisUserSession = RedisUserSession.builder()
                .userId("홍길동")
                .password("1q2w3e4r!")
                .build();
        RedisUserSession session = redisUserSessionService.saveRedisUserSession(redisUserSession);
        Assertions.assertNotNull(session);
    }

}

실행 전 redis 상태

실행 전

실행 후 redis 상태

실행 후

redis gui 로 본 내부 상태

내부 상태

entity에 설정한 RedisHash value 값을 key, @Id값을 리스트로 저장하고,
value:@Id 를 key, 내부 필드를 value로 하는 HASH 형태로 저장한다.

ToDO : Redis로 회원가입, 로그인, 로그아웃 기능 구현.

This post is licensed under CC BY 4.0 by the author.