티스토리 뷰

Developer

ElastiCache with SpringData

rocksea 2021. 5. 21. 02:25
Amazon ElastiCache is a fully managed in-memory data store and cache service by Amazon Web Services (AWS). The service improves the performance of web applications by retrieving information from managed in-memory caches, instead of relying entirely on slower disk-based databases. ElastiCache supports two open-source in-memory caching engines: Memcached and Redis (also called "ElastiCache for Redis").
Amazon ElastiCache

ElastiCache는 메모리 기반의 데이터 저장소이며, I/O 퍼포먼스를 향상시키기 위해 사용한다. 메모리 특성상 전원공급이 중단되면 데이터가 휘발되기 때문에 주로 캐시 데이터, 큐를 저장하는 것을 목적으로 사용되지만, 휘발되지 않기위한 장치가 존재한다(AOF, RDB 모드). 캐시엔진으로 Redis나 Memcached를 사용한다.

 

RedisClient For Java


Jedis와 Lettuce가 가장 많이 쓰이며, Reactive(netty, reactor)기반의 Lettuce를 많이 사용하는 추세다.
간단한 기능구현을 원한다면 Jedis를 사용하는것도 좋다. Spring Data Redis에 두가지 방법 모두 제공하니 적합한 방식을 통해 구현하도록 한다. 중간에 클라이언트를 교체하는 경우 트레이드오프가 발생하니 초기에 용도에 맞는 클라이언트를 잘 선택하는 것을 권장한다.

If you still can’t decide, you can always use Spring Data Redis, which will abstract away Jedis and Lettuce so you can change your mind in the future. Of course, that comes with its own set of tradeoffs.

 

Simple code of jedis

import redis.clients.jedis.Jedis;

public class JedisSetGet {

    private static final String YOUR_CONNECTION_STRING = "redis://:foobared@yourserver:6379/0";

    public static void main(String[] args) {

        Jedis jedis = new Jedis(YOUR_CONNECTION_STRING);

        jedis.set("foo", "bar");
        String result = jedis.get("foo");

        jedis.close();

        System.out.println(result); // "bar"
    }
}

 

Simple code of Lettuce

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

public class LettuceSetGet {

    private static final String YOUR_CONNECTION_STRING = "redis://:foobared@yourserver:6379/0";

    public static void main(String[] args) {
        RedisClient redisClient = RedisClient.create(YOUR_CONNECTION_STRING);
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        RedisCommands<String, String> sync = connection.sync();

        sync.set("foo", "bar");

        String result = sync.get("foo");

        connection.close();
        redisClient.shutdown();

        System.out.println(result); // "bar"
    }
}

 

Examples of SpringDataRedis


Gradle Dependencies

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

 

Configuration

@Configuration
@EnableRedisRepositories(basePackageClasses = {CustomQuestionRepository.class})
public class RedisConfig {
    @Bean
    public LettuceConnectionFactory redisConnectionFactory(
            @Value("${spring.redis.port}") int redisPort,
            @Value("${spring.redis.host}") String redisHost) {
        return new LettuceConnectionFactory(redisHost, redisPort);
    }

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

 

Domain Model

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@RedisHash("member")
public class Member implements Serializable {

    @Id private UUID id;
    private String memberId;
    private String name;
}

 

Repository

public interface MemberRepository extends CrudRepository<Member, UUID> {}

 

Test 코드

@DataJpaTest
@AutoConfigureDataRedis
@DisplayName("Member Repository 테스트")
public class MemberRepositoryTest {

    @Autowired private MemberRepository memberRepository;

    @Test
    public void memberShouldBePushedToRedis() {
        Member member =
                Member.builder().id(UUID.randomUUID()).memberId("rocksea").name("락시").build();
        MemberRepository.save(member);
    }
}

 

KEY 조회

127.0.0.1:6379> keys *
1) "member:c9e52ea2-9292-4f39-8c25-2aad7c5a041b"

 

References


Jedis vs. Lettuce: An Exploration | Redis Labs

Lettuce Reference Guide

redis/jedis

Embedded Redis Server with Spring Boot Test | Baeldung

'Developer' 카테고리의 다른 글

퇴사 회고록  (0) 2021.09.15
Infrastructure as Code with Terraform  (0) 2021.07.22
MongoDB with SpringData  (0) 2021.01.08
[OpenJDK] How to install OpenJDK  (0) 2020.10.20
How to create VPC for HA(High Availability) on AWS  (0) 2020.09.02
댓글