English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java RocksDB 설치 및 사용

rocksDB는 하나의내장 가능의, 영구적인 key-value 저장.

다음은 rocksDB 중국어 공식 웹사이트에서 소개되었습니다. 

https://rocksdb.org.cn/

다음은 네 가지 특징입니다

1 고성능 RocksDB는 로그 구조 데이터베이스 엔진을 사용하며, 더 나은 성능을 위해 이 엔진은 C로 작성되었습니다.++로 작성되었습니다. Key와 value는 임의의 크기의 바이트 스트림입니다.

2 빠른 저장을 최적화하여 RocksDB는 빠르고 저지연의 저장 장치(예: SSD 또는 고속 하드디스크)를 특별히 최적화하여 처리합니다. RocksDB는 SSD와 RAM의 높은 성능을 최대한 활용합니다.

3 적응성 RocksDB는 다양한 작업 유형에 적합합니다. MyRocks와 같은 데이터 저장 엔진에서부터 애플리케이션 데이터 캐시, 심지어 일부 내장 작업에도 잘 맞습니다. RocksDB는 다양한 데이터 작업 요구에 맞춰서 잘 대응합니다.

4 기본 및 고급 데이터베이스 작업 RocksDB는 열개와 닫기와 같은 기본 작업을 제공합니다. 합성과 압축 필터와 같은 고급 작업에 대해서도 읽기와 쓰기 지원을 제공합니다.

;8203;8203;8203;8203;8203;8203;RockDB 설치 및 사용

rocksDB 설치에는 여러 가지 방법이 있습니다. 공식 웹사이트에서 해당 플랫폼의 바이너리 라이브러리를 제공하지 않기 때문에, 직접 컴파일하여 사용해야 합니다.

rocksDB 설치는 간단하지만 rocksDB에 대한 시각을 바꿔야 합니다. 이는 중량적인 데이터베이스가 아니라, 내장된 key-value 저장. 이는 Maven 프로젝트에 rocksDB 의 의존성을 추가하여 개발 환경에서 스스로 시도할 수 있다는 것을 의미합니다. 이 점을 이해하지 못하면 아래와 같은 두 가지 추천하지 않는 설치 방법에 빠질 수 있습니다.

방법 1 rocksDB 공식 웹사이트를 확인하여 C를 쓰도록 안내합니다.++ 프로그램(추천하지 않음)

#include <assert>
#include "rocksdb/db.h
rocksdb::DB* db;
rocksdb::Options options;
options.create_if_missing = true;
rocksdb::Status status =
 rocksdb::DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());

데이터베이스를 생성하려고 합니다.??? 그렇다면 이전에 사용한 mysql이나 mongo와 어떻게 다를까요? 왜 start.sh나 start.bat과 같은 스크립트가 없습니까? 저는 쓰기로 했습니다. 쓰고 나서 컴파일해보니 rocksDB 라이브러리와 연결하는 방법을 몰라요, 어떻게 하나요, 저는 C++모두 잊어버렸습니다.

방법 2 pyrocksDB 사용 (추천하지 않음)

http://pyrocksdb.readthedocs.io/en/latest/installation.html

자세한 설치 문서는 pyrocksDB 공식 웹사이트 설치 문서를 참조하세요.

위 두 가지 방법은 C를 잘 아는 개발자에게는 매우 유용합니다.++ Python 개발자에게는 매우 친숙하지만, Java 개발자에게는 너무 친숙하지 않습니다.

그래서 다음은 제3가지 방법을 소개합니다.

제3의 방법 사용 (추천)

Maven 프로젝트를 생성하고, pom.xml 의 의존성을 수정하여 추가하면 됩니다

<dependency>
 <groupId>org.rocksdb</groupId>
 <artifactId>rocksdbjni</artifactId>
 <version>5.8.6</version>
</dependency>

좋아하는 버전을 선택할 수 있습니다.

그런 다음 Maven의 언어 레벨을 더 높이고, 저는 전체적으로 설정했습니다1.8

<profiles>
 <profile>
 <id>jdk18</id>
 <activation>
  <activeByDefault>true</activeByDefault>
  <jdk>1.8</jdk>
 </activation>
 <properties>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
  <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
 </properties>
 </profile>
</profiles>

이제 여기까지 왔으니, 환경이 설치되었는지 아닌지 다시 익숙한 Java 세계로 돌아왔는지 궁금합니다.

그런 다음 소스 코드 패키지 아래의 하나의 클래스를 복사하고, IDE에서 실행 설정을 수정하여 프로그램 실행 중 데이터베이스 저장 경로를 추가하면 테스트를 실행할 수 있습니다. 저는 이 클래스를 기사 마지막에 제공할 것입니다.

컨솔에서 로그가 출력되고, 파일에도 새로운 파일이 생성됩니다.

rockDB 개발 API에 대한 더 많은 소개와 생산 환경에서의 사용에 대해 나중에 업데이트할 예정입니다. 모두들이 관심을 가지길 바랍니다.

// 저작권 (c) 2011-현재, Facebook, Inc. 모든 권리 보유.
// 이 소스 코드는 GPLv2 라이선스 하에 배포됩니다2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
import org.rocksdb.*;
import org.rocksdb.util.SizeUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class RocksDBSample {
 static {
 RocksDB.loadLibrary();
 }
 public static void main(final String[] args) {
 if (args.length < 1) {
 System.out.println("usage: RocksDBSample db_path");
 System.exit(-1);
 }
 final String db_path = args[0];
 final String db_path_not_found = db_path + "_not_found";
 System.out.println("RocksDBSample");
 try (final Options options = new Options();
  final Filter bloomFilter = new BloomFilter(10);
  final ReadOptions readOptions = new ReadOptions()
  .setFillCache(false);
  final Statistics stats = new Statistics();
  final RateLimiter rateLimiter = new RateLimiter(10000000,10000, 10)) {
 try (final RocksDB db = RocksDB.open(options, db_path_not_found)) {
 assert (false);
 }
 System.out.format("Caught the expected exception"} -- %s\n", e);
 }
 try {
 options.setCreateIfMissing(true)
  .setStatistics(stats)
  .setWriteBufferSize(8 * SizeUnit.KB)
  .setMaxWriteBufferNumber(3)
  .setMaxBackgroundCompactions(10)
  .setCompressionType(CompressionType.SNAPPY_COMPRESSION)
  .setCompactionStyle(CompactionStyle.UNIVERSAL);
 } catch (final IllegalArgumentException e) {
 assert (false);
 }
 assert (options.createIfMissing() == true);
 assert (options.writeBufferSize() == 8 * SizeUnit.KB);
 assert (options.maxWriteBufferNumber() == 3);
 assert (options.maxBackgroundCompactions() == 10);
 assert (options.compressionType() == CompressionType.SNAPPY_COMPRESSION);
 assert (options.compactionStyle() == CompactionStyle.UNIVERSAL);
 assert (options.memTableFactoryName().equals("SkipListFactory"));
 options.setMemTableConfig(
  new HashSkipListMemTableConfig()
  .setHeight(4)
  .setBranchingFactor(4)
  .setBucketCount(2000000));
 assert (options.memTableFactoryName().equals("HashSkipListRepFactory"));
 options.setMemTableConfig(
  new HashLinkedListMemTableConfig()
  .setBucketCount(100000));
 assert (options.memTableFactoryName().equals("HashLinkedListRepFactory"));
 options.setMemTableConfig(
  new VectorMemTableConfig().setReservedSize(10000));
 assert (options.memTableFactoryName().equals("VectorRepFactory"));
 options.setMemTableConfig(new SkipListMemTableConfig());
 assert (options.memTableFactoryName().equals("SkipListFactory"));
 options.setTableFormatConfig(new PlainTableConfig());
 // Plain-Table requires mmap read
 options.setAllowMmapReads(true);
 assert (options.tableFactoryName().equals("PlainTable"));
 options.setRateLimiter(rateLimiter);
 final BlockBasedTableConfig table_options = new BlockBasedTableConfig();
 table_options.setBlockCacheSize(64 * SizeUnit.KB)
  .setFilter(bloomFilter)
  .setCacheNumShardBits(6)
  .setBlockSizeDeviation(5)
  .setBlockRestartInterval(10)
  .setCacheIndexAndFilterBlocks(true)
  .setHashIndexAllowCollision(false)
  .setBlockCacheCompressedSize(64 * SizeUnit.KB)
  .setBlockCacheCompressedNumShardBits(10);
 assert (table_options.blockCacheSize() == 64 * SizeUnit.KB);
 assert (table_options.cacheNumShardBits() == 6);
 assert (table_options.blockSizeDeviation() == 5);
 assert (table_options.blockRestartInterval() ==) 10);
 assert (table_options.cacheIndexAndFilterBlocks() == true);
 assert (table_options.hashIndexAllowCollision() == false);
 assert (table_options.blockCacheCompressedSize() == 64 * SizeUnit.KB);
 assert (table_options.blockCacheCompressedNumShardBits() == 10);
 options.setTableFormatConfig(table_options);
 assert (options.tableFactoryName().equals("BlockBasedTable"));
 try (final RocksDB db = RocksDB.open(options, db_path)) {
 db.put("hello".getBytes(), "world".getBytes());
 final byte[] value = db.get("hello".getBytes());
 assert ("world".equals(new String(value)));
 final String str = db.getProperty("rocksdb.stats");
 assert (str != null && !str.equals(""));
 }
 System.out.format("[ERROR] caught the unexpected exception -- %s\n", e);
 assert (false);
 }
 try (final RocksDB db = RocksDB.open(options, db_path)) {
 db.put("hello".getBytes(), "world".getBytes());
 byte[] value = db.get("hello".getBytes());
 System.out.format("Get('hello') = %s\n",
  new String(value));
 for (int i = 1; i <= 9; ++i) {
  for (int j = 1; j <= 9; ++j) {
  db.put(String.format("%dx%d", i, j).getBytes(),
  String.format("%d", i * j).getBytes());
  }
 }
 for (int i = 1; i <= 9; ++i) {
  for (int j = 1; j <= 9; ++j) {
  System.out.format("%s ", new String(db.get(
  String.format("%dx%d", i, j).getBytes())));
  }
  System.out.println("");
 }
 // write batch test
 try (final WriteOptions writeOpt = new WriteOptions()) {
  for (int i = 10; i <= 19; ++i) {
  try (final WriteBatch batch = new WriteBatch()) {
  for (int j = 10; j <= 19; ++j) {
  batch.put(String.format("%dx%d", i, j).getBytes(),
   String.format("%d", i * j).getBytes());
  }
  db.write(writeOpt, batch);
  }
  }
 }
 for (int i = 10; i <= 19; ++i) {
  for (int j = 10; j <= 19; ++j) {
  assert (new String(
  db.get(String.format("%dx%d", i, j).getBytes())).equals(
  String.format("%d", i * j)));
  System.out.format("%s ", new String(db.get(
  String.format("%dx%d", i, j).getBytes())));
  }
  System.out.println("");
 }
 value = db.get("1x1".getBytes());
 assert (value != null);
 value = db.get("world".getBytes());
 assert (value == null);
 value = db.get(readOptions, "world".getBytes());
 assert (value == null);
 final byte[] testKey = "asdf".getBytes();
 final byte[] testValue =
  "asdfghjkl;'?><MNBVCXZQWERTYUIOP{+_)_(*&^%$#@".getBytes();
 db.put(testKey, testValue);
 byte[] testResult = db.get(testKey);
 assert (testResult != null);
 assert (Arrays.equals(testValue, testResult));
 assert (new String(testValue).equals(new String(testResult)));
 testResult = db.get(readOptions, testKey);
 assert (testResult != null);
 assert (Arrays.equals(testValue, testResult));
 assert (new String(testValue).equals(new String(testResult)));
 final byte[] insufficientArray = new byte[10];
 final byte[] enoughArray = new byte[50];
 int len;
 len = db.get(testKey, insufficientArray);
 assert (len > insufficientArray.length);
 len = db.get("asdfjkl;".getBytes(), enoughArray);
 assert (len == RocksDB.NOT_FOUND);
 len = db.get(testKey, enoughArray);
 assert (len == testValue.length);
 len = db.get(readOptions, testKey, insufficientArray);
 assert (len > insufficientArray.length);
 len = db.get(readOptions, "asdfjkl;".getBytes(), enoughArray);
 assert (len == RocksDB.NOT_FOUND);
 len = db.get(readOptions, testKey, enoughArray);
 assert (len == testValue.length);
 db.remove(testKey);
 len = db.get(testKey, enoughArray);
 assert (len == RocksDB.NOT_FOUND);
 // repeat the test with WriteOptions
 try (final WriteOptions writeOpts = new WriteOptions()) {
  writeOpts.setSync(true);
  writeOpts.setDisableWAL(true);
  db.put(writeOpts, testKey, testValue);
  len = db.get(testKey, enoughArray);
  assert (len == testValue.length);
  assert (new String(testValue).equals(
  new String(enoughArray, 0, len)));
 }
 try {
  for (final TickerType statsType : TickerType.values()) {
  if (statsType != TickerType.TICKER_ENUM_MAX) {
  stats.getTickerCount(statsType);
  }
  }
  System.out.println("getTickerCount() passed.");
 } catch (final Exception e) {
  System.out.println("Failed in call to getTickerCount()");
  assert (false); //Should never reach here.
 }
 try {
  for (final HistogramType histogramType : HistogramType.values()) {
  if (histogramType != HistogramType.HISTOGRAM_ENUM_MAX) {
  HistogramData data = stats.getHistogramData(histogramType);
  }
  }
  System.out.println("getHistogramData() passed.");
 } catch (final Exception e) {
  System.out.println("Failed in call to getHistogramData()");
  assert (false); //Should never reach here.
 }
 try (final RocksIterator iterator = db.newIterator()) {
  boolean seekToFirstPassed = false;
  for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) {
  iterator.status();
  assert (iterator.key() != null);
  assert (iterator.value() != null);
  seekToFirstPassed = true;
  }
  if (seekToFirstPassed) {
  System.out.println("iterator seekToFirst tests passed.");
  }
  boolean seekToLastPassed = false;
  for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) {
  iterator.status();
  assert (iterator.key() != null);
  assert (iterator.value() != null);
  seekToLastPassed = true;
  }
  if (seekToLastPassed) {
  System.out.println("iterator seekToLastPassed tests passed.");
  }
  iterator.seekToFirst();
  iterator.seek(iterator.key());
  assert (iterator.key() != null);
  assert (iterator.value() != null);
  System.out.println("iterator seek test passed.");
 }
 System.out.println("iterator tests passed.");
 final List<byte[]> keys = new ArrayList<>();
 try (final RocksIterator iterator = db.newIterator()) {
  for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) {
  keys.add(iterator.key());
  }
 }
 Map<byte[], byte[]> values = db.multiGet(keys);
 assert (values.size() == keys.size());
 for (final byte[] value1 : values.values()) {
  assert (value1 != null);
 }
 values = db.multiGet(new ReadOptions(), keys);
 assert (values.size() == keys.size());
 for (final byte[] value1 : values.values()) {
  assert (value1 != null);
 }
 }
 System.err.println(e);
 }
 }
 }
}

이번에 소개해 드린 Java의 RocksDB 설치와 사용에 대한 모든 내용이 다到此为止입니다. 학습 중에 모든 의문이 있으시면 아래의 댓글 영역에서 논의해 주세요. 나락 교본에 대한 지원에 감사합니다.

추천 합니다