DB 연결 설정 분리

✒️ 2026-07-01 20:26 내용 수정


실습 참고 자료


중복 연결 설정 제거

package myproject.redis.lettuce;
  
import io.lettuce.core.api.sync.RedisCommands;  
  
@FunctionalInterface  
public interface CommandAction {  
	// Redis 명령 실행부
    void doInExecute(RedisCommands<String, String> redisCommands);  
}
package myproject.redis.lettuce;  
  
import io.lettuce.core.RedisClient;  
import io.lettuce.core.RedisURI;  
import io.lettuce.core.api.StatefulRedisConnection;  
import io.lettuce.core.api.sync.RedisCommands;  
  
public class CommandTemplate {  
    public static void commandAction(CommandAction action) {  
        // Redis 클라이언트 생성  
        RedisClient redisClient = RedisClient.create(getRedisUri());  
  
        // Connection 연결  
        StatefulRedisConnection<String, String> connection = redisClient.connect();  
  
        // Redis 명령어  
        RedisCommands<String, String> redisCommands = connection.sync();  
  
        // 구현부  
        action.doInExecute(redisCommands);  
  
        connection.close();  
        redisClient.shutdown();  
    }  
  
    // Redis URI 생성  
    public static RedisURI getRedisUri() {  
        // host 주소  
        String host = "localhost";  
          
        return RedisURI.builder()  
                .withHost(host)  
                .withPort(6379) // 포트 번호. Docker에서 설정한 값과 동일하게 설정  
                .withDatabase(0) // 0 - 15까지 존재  
                .build();  
    }  
}
package io.github.crewhub.redis.lettuce.string;  
  
import io.github.crewhub.redis.lettuce.CommandAction;  
import io.github.crewhub.redis.lettuce.CommandTemplate;  
import org.junit.jupiter.api.Test;  
  
public class RedisLettuceStringRange {  
    @Test  
    public void incrDecr() {  
        CommandAction action = (redisCommands -> {  
            // Redis 연결 테스트를 위한 Key-value            
            String key = "lettuce:string";  
            String value = "hello";  
  
            redisCommands.set(key, value);  
        });  
        CommandTemplate.commandAction(action);  
    }  
}
CommandAction action = new CommandAction() {
    @Override
    public void doInExecute(RedisCommands<String, String> redisCommands) {
		String key = "lettuce:string";  
		String value = "hello";  
		
        redisCommands.set(key, value);  
    }
};