기타

Redis란 무엇인가?

멍토 2021. 8. 24.

Remote Dictionary Server의 약자이다.

풀이하면 외부에서 딕셔너리(Key-Value)를 이용하는 서버이다.

Redis는 하드에 데이터를 저장하지 않고 Inmemory Data Structure Store 메모리상에 데이터를 저장한다.

DataBase보다 더 빠른 Memory에서 더 자주 접근하고 덜 자주 바뀌는 데이터를 저장하자는 취지에서 나오게 되었다.

Redis는 다양한 자료구조(Collections)를 지원한다

 

Redis는 왜 사용할까?

서버에서도 로컬캐시나 Map과 같은 자료구조를 통해서 캐싱을 시도할 수 있다.

그런데 왜 Redis와 같은 캐시서버를 사용할까?

  1. 분산처리 환경에서 Local 캐시의 경우 일관성이 없을 수 있으며, 일관성이 보장된다고 하더라도 각 서버마다 각각 캐싱을 해야한다는 문제점이 발생한다.
  2. 서버에 캐싱을 하게되면 메모리 사용량이 증가하여 서버의 퍼포먼스에 영향이 생길 수 있다.(생긴다 X, 가능성 존재)
  3. 멀티 쓰레드 환경에서 Map과 같은 자료구조에 접근하다가 문제(Race Condition)가 발생할 수 있다.

이러한 문제를 해결하기 위해서 redis를 사용한다.

추가적으로 캐시로 많이 사용하는 Memcached가 있는데 차이점은 Redis에서는 Collection을 지원한다.

 

Race Condition이란?

Race Condition이란 여러개의 Thread가 경합하는 것으로 Context Swithcing에 따라서 원하지 않는 결과가 발생할 수 있다.

따라서 Redis는 기본적으로 Single Threaded로 동작한다.

 

언제 적용하면 좋을까?

왜 사용하는지를 생각해보면 유추가 가능하다.

분산처리 환경을 만들게 되었을때는 Local Cache를 적용하는 것 보다 캐시서버를 따로 두는것이 유리하다.

혹은 서버상의 스펙문제로 인하여 분리할때, 캐시를 적용해야 할때 적용하면 좋다.

 

Redis 사용지 주의해야 할점

Single Thread이기 때문에 하나의 연산이 오래걸리면 성능상 문제가 발생할 수 있다.

따라서 Keys, Flush, GetAll과 같은 O(N)의 연산은 피해야 한다.

 

Spring과 연동방법

Spring과 같이 사용하기 위해서는 의존성을 먼저 추가해야 한다.

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

 

이후 Redis를 설정하기 위한 Config 파일을 정의한다.

@Configuration
@EnableRedisRepositories
public class RedisConfig {

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

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

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(redisHost, redisPort);
    }

    @Bean
    public RedisTemplate<?, ?> redisTemplate() {
        RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }
}

 

이후 url주소와 포트번호를 넣고 Bean을 생성한다.

나의 경우는 외부에 주소와 포트번호를 공개하지 않기위해 yml 파일에서 가져오는 방식으로 처리했다.

 

객체를 넣어서 처리하기 위해서는 객체를 직렬화 하는 내용을 추가해야 한다.

@RedisHash("TransportCache")
public class TransportCache implements Serializable {

    @Id
    private String id;
    private APITransportResponse apiTransportResponse;

    @TimeToLive(unit = TimeUnit.DAYS)
    private Long timeToLive;

    ...
}

 

이제 해당 객체를 처리해줄 Repository를 만들어야 한다.

public interface SubwayRedisRepository extends CrudRepository<TransportCache, String> {

}

 

이제 Repository에서 지원하는 findById, save등의 함수를 통해서 Redis에 접근이 가능해진다.

TransportCache transportCache = subwayRedisRepository.findById(
                redisId(startStation, endStation))

subwayRedisRepository.save(transportCache);

 

redisTemplate는 어디에 사용될까?

적용할때 설정을 보면 redisConfig에서 적용하고 따로 주입하거나 하는 로직이 보이지 않는다.

그런데 Redis에 잘 접근하고 처리하고 있다.

그렇다면 redisTemplate는 어디에서 연결되고 있을까?

해당내용은 아래 링크에 존재한다.

https://dzone.com/articles/introduction-to-spring-data-redis

https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis.repositories

 

그러면 자동으로 연결되는건 알겠는데 무슨역할일까?

redisTemplate 설정부분을 주석을 처리하고 조회를 해보았다.

정상적으로 조회가 되었다.

 

그렇다면 사용되는 부분이 없는걸까?

혹시 쓰기 영역에서 사용이 되는걸까? Redis 서버에 캐싱된 내용을 전부 밀어버리고 다시 시도했다.

터졌다.

결론 : redisTemplate은 Redis에 데이터를 저장할때 사용되었다.

 

그리고 멍청한 이야기였는데 RedisTemplate에 들어가니 해당 클래스가 하는 역할이 주석으로 적혀있었다.

Helper class that simplifies Redis data access code.

Performs automatic serialization/deserialization between the given objects and the underlying binary data in the Redis store. By default, it uses Java serialization for its objects (through JdkSerializationRedisSerializer ). For String intensive operations consider the dedicated StringRedisTemplate.

The central method is execute, supporting Redis access code implementing the RedisCallback interface. It provides RedisConnection handling such that neither the RedisCallback implementation nor the calling code needs to explicitly care about retrieving/closing Redis connections, or handling Connection lifecycle exceptions. For typical single step actions, there are various convenience methods.

Once configured, this class is thread-safe.

Note that while the template is generified, it is up to the serializers/deserializers to properly convert the given Objects to and from binary data.

This is the central class in Redis support.
See Also:
StringRedisTemplate
Author:
Costin Leau, Christoph Strobl, Ninad Divadkar, Anqing Shao, Mark Paluch, Denis Zavedeev
Type parameters:
<K> – the Redis key type against which the template works (usually a String)
<V> – the Redis value type against which the template work

 

이 외의 추가적인 기능은 나중에 따로 공부해보자.

 

출처 : https://www.youtube.com/watch?v=Gimv7hroM8A&t=698s

https://velog.io/@hyeondev/Redis-%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C

https://jojoldu.tistory.com/297

https://dzone.com/articles/introduction-to-spring-data-redis

https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis.repositories

댓글

💲 광고입니다.