Java 에서 RocksDB 사용하기
RocksDB는 고성능 Key-Value Store 이다.
LSM(Log-Structured Merge) 트리를 기반으로 동작한다.
RocksDB는 임베디드 형태로 동작한다. 별도의 서버 프로세스를 띄우지 않는다.
dependency를 추가한다. gradle의 경우 다음과 같이 추가하면 된다.
implementation("org.rocksdb:rocksdbjni:10.2.1")
다음과 같이 간단한 예제를 작성하여 동작을 확인하였다.
public class Main {
private static final File baseDir = new File("/tmp/rocks", "db");
public static void main(String[] args) {
RocksDB.loadLibrary();
final Options options = new Options();
options.setCreateIfMissing(true);
try {
Files.createDirectories(baseDir.getParentFile().toPath());
Files.createDirectories(baseDir.getAbsoluteFile().toPath());
RocksDB db = RocksDB.open(options, baseDir.getAbsolutePath());
db.put("안녕".getBytes(), "하세요".getBytes());
byte[] bytes = db.get("안녕".getBytes());
if (bytes != null) {
System.out.println(new String(bytes, StandardCharsets.UTF_8));
}
} catch(IOException | RocksDBException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
get
메소드에서 키 값에 해당 되는 값이 없을 경우 null
을 반환한다. 따라서 예시에 null
체크를 넣어주었다.