Try using RocksDB in Java

What is RocksDB

A database that holds a key-value data format (byte array). It is written in C ++ and can be used with JNI from Java. However, Java's API has not caught up with C ++'s API.

Wiki https://ja.wikipedia.org/wiki/RocksDB

How to use

The simple usage is described below. See the official documentation for details.

https://github.com/facebook/rocksdb/wiki/RocksJava-Basics

Maven Use the following libraries. If you use only RocksDb, you only need rocksdbjni. Kryo is added for serialization and deserialization.

		<dependency>
			<groupId>org.rocksdb</groupId>
			<artifactId>rocksdbjni</artifactId>
			<version>6.0.1</version>
		</dependency>
		<dependency>
            <groupId>com.esotericsoftware</groupId>
            <artifactId>kryo</artifactId>
            <version>3.0.1</version>
        </dependency>

Open / Close

There is also a method for closing, but we recommend using try-with-resources, so let's follow it. It is necessary to specify the path of the DB save destination for open. If you specify as follows, a folder for DB will be created directly under the project.

		try (RocksDB rocksDb = RocksDB.open("sample")) {
                   //Write the process here
        }

Read, write, delete

This is a basic API usage example. Read is get, write is put, and delete is delete. In addition, usage examples of all acquisition (newIterator), range deletion (deleteRange), and multiple acquisition (multiGetAsList) are described.

	public void execute() {

		//Open RocksDB. Specify the DB save destination for open (created directly under the project if the following is specified)
		try (RocksDB rocksDb = RocksDB.open("sample")) {

			//Serialize using Kryo
			byte[] binaryKey = serialize("key");
			byte[] binaryValue = serialize("Value");

			//Specify Key and Value and put to RocksDB (API#put)
			//Even if you register a duplicate Key, no error will occur, just overwrite it
			rocksDb.put(binaryKey, binaryValue);
			rocksDb.put(binaryKey, binaryValue);

			//Obtained from RocksDB using serialized Key (API#get)
			try (Input input = new Input(rocksDb.get(binaryKey))) {
				System.out.println(kryo.readObject(input, String.class));
			}

			//Delete from RockDB by specifying Key (API#delete)
			rocksDb.delete(binaryKey);
			if (null == rocksDb.get(binaryKey)) {
				System.out.println("Can't get");
			}

			for (int i = 0; i < 10; i++) {
				//Serialize using Kryo
				byte[] tempBinaryKey = serialize("key" + String.valueOf(i));
				byte[] tempBinaryValue = serialize("Value"+ String.valueOf(i));

				//Specify Key and Value and put to RocksDB
				rocksDb.put(tempBinaryKey, tempBinaryValue);
			}

			//Get all the data in RocksDB (API#newIterator)
			System.out.println("Get all entries");
			RocksIterator iterator = rocksDb.newIterator();
			iterator.seekToFirst();
			while (iterator.isValid()) {
				try (Input input = new Input(iterator.key())) {
					System.out.println(kryo.readObject(input, String.class));
				}
				iterator.next();
			}

			//Delete in RocksDB by specifying a key range(API#deleteRange)
			//Specified in beginKey ~ Immediately before EndKey is deleted
			rocksDb.deleteRange(serialize("key0"), serialize("key8"));
			System.out.println("Range deletion key0-key7");
			RocksIterator iterator2 = rocksDb.newIterator();
			iterator2.seekToFirst();
			while (iterator2.isValid()) {
				try (Input input = new Input(iterator2.value())) {
					System.out.println(kryo.readObject(input, String.class));
				}
				iterator2.next();
			}

			//Get multiple in RocksDB(#multiGetAsList)
			System.out.println("Get multiple");
			List<byte[]> binaryKeyList = new ArrayList<>();
			binaryKeyList.add(serialize("key8"));
			binaryKeyList.add(serialize("key9"));
			List<byte[]> binaryValueList = rocksDb.multiGetAsList(binaryKeyList);
			for (byte[] binary:binaryValueList) {
				try (Input input = new Input(binary)) {
					System.out.println(kryo.readObject(input, String.class));
				}
			}

		} catch (RocksDBException e) {
			throw new RuntimeException(e);
		}
	}

	private byte[] serialize(String str) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try (Output output = new Output(baos)) {
			kryo.writeObject(output, str);
		}
		return baos.toByteArray();
	}

When do you use it?

You can use it just by installing the library, so you don't even have to use RDB, I think it will be useful in situations where data persistence is required.

reference

https://github.com/EsotericSoftware/kryo https://github.com/facebook/rocksdb/wiki/RocksJava-Basics

Recommended Posts

Try using RocksDB in Java
Try using the Stream API in Java
Try using JSON format API in Java
Try using Sourcetrail (win version) in Java code
Try using GCP's Cloud Vision API in Java
Try using Sourcetrail (macOS version) in Java code
Try using the COTOHA API parsing in Java
Try scraping using java [Notes]
Try calling JavaScript in Java
Try developing Spresense in Java (1)
Try functional type in Java! ①
Try using gRPC in Ruby
Try global hooking in Java using the JNativeHook library
Try implementing Android Hilt in Java
Try implementing GraphQL server in Java
Encrypt using RSA cryptography in Java
Try running Selenuim 3.141.59 in eclipse (java)
Try using Redis with Java (jar)
Try an If expression in Java
[Java] Try to implement using generics
HTTPS connection using tls1.2 in Java 6
I tried using JWT in Java
Try running AWS X-Ray in Java
Try to implement Yubaba in Java
Try using IBM Java method tracing
Try using Hyperledger Iroha's Java SDK
[Java] Where did you try using java?
Implement Thread in Java and try using anonymous class, lambda
Try using libGDX
Try using Java framework Nablarch [Web application]
I tried using Elasticsearch API in Java
Try to solve Project Euler in Java
Try using Maven
Try using powermock-mockito2-2.0.2
Partization in Java
Try using GraalVM
Try to implement n-ary addition in Java
Try Java 8 Stream
Map without using an array in java
Try using jmockit 1.48
Try using sql-migrate
Changes in Java 11
Study Java Try using Scanner or Map
Using JavaScript from Java in Rhino 2021 version
ERRORCODE = -4471 occurs in Java application using Db2.
Rock-paper-scissors in Java
Try calling the CORBA service in Java 11+
Try using SwiftLint
Try using Log4j 2.0
Read Felica using RC-S380 (PaSoRi) in Java
Try making a calculator app in Java
Try using JobScheduler's REST-API --Java RestClient implementation--
Pi in Java
Roughly try Java 9
Try using the Wii remote with Java
FizzBuzz in Java
NLP4J [002] Try parsing Japanese using Yahoo! Developer Network Japanese Parsing Analysis (V1) in Java
Try using Firebase Cloud Functions on Android (Java)
Try using JobScheduler's REST-API --Java RestClient Test class-
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse