8. Block Cache

Tasker_Jang·2024년 8월 31일

1) Block Cache란 무엇인가?

Block cache는 RocksDB가 데이터를 빠르게 읽어오기 위해 메모리에 저장하는 임시 저장 공간입니다. 블록 캐시는 데이터를 미리 메모리에 올려두어 디스크에서 직접 읽는 것보다 훨씬 빠르게 접근할 수 있게 합니다. 이를 통해 데이터베이스의 읽기 성능을 크게 향상시킬 수 있습니다. LRU (Least Recently Used) 알고리즘 등을 사용하여 효율적으로 캐시를 관리하며, 메모리 사용량을 최적화할 수 있습니다.

2) Block Cache을 다룰 수 있는 주요 메서드

  1. NewLRUCache(size: usize) -> Cache: 지정한 크기로 LRU 기반의 블록 캐시를 생성합니다.

  2. table_options.block_cache = cache: 테이블 옵션에서 블록 캐시를 설정합니다.

  3. cache.insert(key: &[u8], value: &[u8]): 캐시에 데이터 블록을 추가합니다.

  4. cache.lookup(key: &[u8]) -> Option<&[u8]>: 캐시에서 주어진 키와 일치하는 데이터를 검색합니다.

  5. cache.erase(key: &[u8]): 캐시에서 특정 키에 해당하는 데이터를 삭제합니다.

  6. cache.clear(): 캐시의 모든 데이터를 비웁니다.

  7. table_options.no_block_cache = true: 블록 캐시를 비활성화합니다.

  8. cache.SetCapacity(size: usize): 캐시의 최대 크기를 설정합니다.

  9. cache.SetStrictCapacityLimit(limit: bool): 캐시의 엄격한 용량 제한을 설정합니다.

  10. cache.get_usage() -> usize: 현재 캐시 사용량을 반환합니다.

  11. cache.get_pinned_usage() -> usize: 캐시에 고정된 데이터의 사용량을 반환합니다.

3) 예제 코드

use rocksdb::{BlockBasedOptions, Options, DB, Cache};
use std::sync::Arc;

fn main() {
    // 1. Block Cache 생성 (LRU 캐시, 64MB 크기)
    let cache_size = 64 * 1024 * 1024; // 64MB
    let cache = Cache::new_lru_cache(cache_size).expect("Failed to create cache");

    // 2. BlockBased 테이블 옵션 설정
    let mut block_based_options = BlockBasedOptions::default();
    block_based_options.set_block_cache(&cache);

    // 3. RocksDB 옵션 설정
    let mut db_options = Options::default();
    db_options.set_block_based_table_factory(&block_based_options);

    // 4. RocksDB 인스턴스 생성
    let path = "_path_for_rocksdb_storage";
    let db = DB::open(&db_options, path).expect("Failed to open RocksDB");

    // 5. 데이터 삽입
    db.put(b"key1", b"value1").expect("Failed to write to RocksDB");
    db.put(b"key2", b"value2").expect("Failed to write to RocksDB");

    // 6. 데이터 조회
    let value = db.get(b"key1").expect("Failed to read from RocksDB")
        .expect("Key not found");
    println!("Retrieved value for 'key1': {}", String::from_utf8(value).unwrap());

    // 7. 캐시에서 직접 데이터 조회
    if let Some(cached_value) = cache.lookup(b"key1") {
        println!("Found 'key1' in cache: {:?}", cached_value);
    } else {
        println!("'key1' not found in cache.");
    }

    // 8. 캐시에서 키 삭제
    cache.erase(b"key1");

    // 9. 캐시 사용량 확인
    let usage = cache.get_usage();
    println!("Current cache usage: {} bytes", usage);

    // 10. 캐시 클리어
    cache.clear();
    println!("Cache cleared. Current cache usage: {} bytes", cache.get_usage());

    // 11. RocksDB 인스턴스 종료
    drop(db);
}
profile
ML Engineer 🧠 | AI 모델 개발과 최적화 경험을 기록하며 성장하는 개발자 🚀 The light that burns twice as bright burns half as long ✨

0개의 댓글