[Spring & Redis] rename-command 이후에 RedisTemplate 으로 명령어를 쓰려면?

식빵·2024년 3월 25일
0

Spring Lab

목록 보기
33/33
post-thumbnail

🍀 Docker Redis 띄우기

먼저 테스트를 위해서 docker 로 redis 환경을 세팅하겠습니다~


1. redis.conf 파일 작성

rename-command KEYS WORKERS
  • 중요! keys 라는 명령어를 workers 라는 명령어로 바꿨습니다.

2. Dockerfile 작성

# 베이스 이미지로 Redis를 사용합니다.
FROM redis:6.2.14

# Redis 구성 파일을 복사합니다.
COPY redis.conf /usr/local/etc/redis/redis.conf

# Redis를 실행할 때 구성 파일을 사용합니다.
CMD ["redis-server", "/usr/local/etc/redis/redis.conf"]

3. docker build, docker run

docker build -t custom-redis-image .
docker run --name redis -p 6379:6379 -d custom-redis-image




🍀 테스트

1. 실패 코드 🤢

아래처럼 하면 실패하게 됩니다.
에러 문구도 예상대로 찍히는 걸 확인할 수 있었습니다.

ERR unknown command "KEYS", with args beginning with: "???"

class RedisTesterApplicationTests {
    private static LettuceConnectionFactory redisConnectionFactory;
    private static RedisTemplate<String, Object> redisTemplate;

    @BeforeAll
    static void beforeAll() {
        redisConnectionFactory = new LettuceConnectionFactory("localhost", 6379);
        redisConnectionFactory.afterPropertiesSet();

        redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // Configure key serializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // Configure value serializer
        redisTemplate.setValueSerializer(new StringRedisSerializer());

        // Configure hash value serializer
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        // Configure hash keyHash serializer
        redisTemplate.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());

        // Initialize the RedisTemplate
        redisTemplate.afterPropertiesSet();
    }

    @Test
    void setAndGetTest() {
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");

        // 에러 발생!
        // ERR unknown command `KEYS`, with args beginning with: `key*`,
        Set<String> keys = redisTemplate.keys("key*");
        System.out.println("keys = " + keys);
    }
}

정상적으로 rename-command 가 적용되었기 때문에 실패하는 거랍니다!



2. 명령어 사용법 2가지 🙌

이제 명칭이 새롭게 바뀐 command 를 사용하는 방법을 알아봅시다.

  • 방법1: redisTemplate.execute 을 사용
  • 방법2: lua Script 를 사용

현재 keys 라는 명령어를 workers 라는 명칭으로 바꿨다는 점! 잊지 마시길!


@Slf4j
class RedisTesterApplicationTests {

    private static LettuceConnectionFactory redisConnectionFactory;
    private static RedisTemplate<String, Object> redisTemplate;

    @BeforeAll
    static void beforeAll() {
       /* !!! 앞에서 본 것과 동일하여 생략!!!  */
    }

	/**
    * 방법 1: redisTemplate.execute API 사용
    */
    @Test
    void redisTemplateExecuteTest() {
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");

        byte[] found = (byte[]) redisTemplate.execute((RedisConnection connection) -> {
            return connection.execute("workers", "key1".getBytes());
        }, true);
        System.out.println("workers = " + new String(found));
    }

	/**
    * 방법 2: lua Script 사용
    */
    @Test
    void luaTest() {
    	redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");
    
        // Lau Script Wrapper 생성
        RedisScript<String> script = new DefaultRedisScript<>(
               """
               local current = redis.call('workers', KEYS[1])
               return current
               """.trim(), String.class);

        String execute = redisTemplate.execute(script, List.of("key1"));
        System.out.println("execute = " + execute);
    }

}
profile
백엔드를 계속 배우고 있는 개발자입니다 😊

0개의 댓글