지연 초기화와 싱글턴 패턴

Java 코드 최적화

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Redis 캐시 클라이언트 구축하기

  • Redis에 접속하는 캐시 클라이언트를 만든다고 가정해 봅시다
  • Redis 클라이언트는 타사 제공업체에서 호스팅됩니다
  • 클라이언트 연결을 설정하려면 네트워크 호출이 필요하며, 500ms가 걸린다고 가정해 봅시다

$$

Redis 연결을 설정하기 위한 네트워크 호출

Java 코드 최적화

간단한 (즉시) 구현

public class RedisCache {
    // The client library we use to connect to Redis
    private final RedisClient client;

    public RedisCache() {
        // The connection is setup inside the constructor
        connection = new RedisClient("cache.mycompany.com");
    }
}
  • Redis 연결의 즉시 초기화
Java 코드 최적화

이 방식의 잠재적 문제

간단해 보이고 실제로 작동하지만, 잠재적인 문제가 있습니다

Redis 클라이언트가 전혀 필요하지 않다면 어떨까요?

  • 시작 시 귀중한 시간을 낭비했습니다
  • 불필요한 연결을 생성했습니다
Java 코드 최적화

지연 초기화

public class RedisCache {
    private RedisClient client;

    // Instead of setting up the connection in the constructor,
    // we only set it up when someone needs to get the client.
    public RedisClient getClient() {
        if (connection == null) {
            connection = new RedisClient("cache.mycompany.com");
        }
        return connection;
    }
}
Java 코드 최적화

이 방식의 또 다른 문제

// UserService needs cache access
public class UserService {
    private RedisCache userCache = new RedisCache();  // First connection
}

// PaymentService also needs cache
public class PaymentService {
    private RedisCache paymentCache = new RedisCache();  // Second connection
}

// ...same for OrderService ...
Java 코드 최적화

싱글턴 패턴

public class RedisCache {
    private static RedisCache instance;
    private RedisClient client;

    // The constructor is private so that we ensure we only
    // create RedisCache inside this class
    private RedisCache() {}

    public static RedisCache getInstance() 
        // We only create a RedisCache if one does not already exist
        if (instance == null) { instance = new RedisCache(); }
        return instance;
    }

    // ... The rest is the same as before ...
}
Java 코드 최적화

연습해 봅시다!

Java 코드 최적화

Preparing Video For Download...