RocksDB Java Example

2020-03-13 16:03:56来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

RocksDB Java Example

RocksDB属于嵌入式数据库,没有网络交互接口,必须和服务部署在同一台服务器。RocksDB是Facebook公司在LevelDB基础之上开发的一个嵌入式KV系统,在很多方面对LevelDB做了优化和增强,更像是一个完整的产品。有如下特征:

  • 高性能: RocksDB使用日志结构的数据库引擎,完全用C++编写,以获得最大的性能。 键和值是任意大小的字节流。
  • 为快速存储而优化: RocksDB针对快速、低延迟的存储(如闪存驱动器和高速磁盘驱动器)进行了优化。RocksDB充分利用了flash或RAM提供的高读/写速率的潜力。
  • 适应性强: RocksDB 可以适应不同的工作负载。 从 MyRocks 等数据库存储引擎到应用程序数据缓存到嵌入式工作负载,RocksDB 可以用于满足各种数据需求。
  • 基础和高级数据库操作: RocksDB提供了一些基本操作,比如打开和关闭数据库,读与写,合并和压缩过滤器等高级操作。

参考了如下文档:

  • RocksJava Basics
  • Java RocksDB简单入门

Maven依赖(pom.xml)

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

完整代码示例,可参考:https://github.com/sxpujs/java-example/blob/master/src/main/java/com/demo/rocksdb/RocksDBExample.java

import org.rocksdb.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class RocksDBExample {

    private static final String dbPath   = "./rocksdb-data/";
    private static final String cfdbPath = "./rocksdb-data-cf/";

    static {
        RocksDB.loadLibrary();
    }

    //  RocksDB.DEFAULT_COLUMN_FAMILY
    public void testDefaultColumnFamily() {
        System.out.println("testDefaultColumnFamily begin...");
        // 文件不存在,则先创建文件
        try (final Options options = new Options().setCreateIfMissing(true)) {
            try (final RocksDB rocksDB = RocksDB.open(options, dbPath)) {
                // 简单key-value
                byte[] key = "Hello".getBytes();
                rocksDB.put(key, "World".getBytes());

                System.out.println(new String(rocksDB.get(key)));

                rocksDB.put("SecondKey".getBytes(), "SecondValue".getBytes());

                // 通过List做主键查询
                List<byte[]> keys = Arrays.asList(key, "SecondKey".getBytes(), "missKey".getBytes());
                List<byte[]> values = rocksDB.multiGetAsList(keys);
                for (int i = 0; i < keys.size(); i++) {
                    System.out.println("multiGet " + new String(keys.get(i)) + ":" + (values.get(i) != null ? new String(values.get(i)) : null));
                }

                // 打印全部[key - value]
                RocksIterator iter = rocksDB.newIterator();
                for (iter.seekToFirst(); iter.isValid(); iter.next()) {
                    System.out.println("iterator key:" + new String(iter.key()) + ", iter value:" + new String(iter.value()));
                }

                // 删除一个key
                rocksDB.delete(key);
                System.out.println("after remove key:" + new String(key));

                iter = rocksDB.newIterator();
                for (iter.seekToFirst(); iter.isValid(); iter.next()) {
                    System.out.println("iterator key:" + new String(iter.key()) + ", iter value:" + new String(iter.value()));
                }
            }
        } catch (RocksDBException e) {
            e.printStackTrace();
        }
    }

    // 使用特定的列族打开数据库,可以把列族理解为关系型数据库中的表(table)
    public void testCertainColumnFamily() {
        System.out.println("\ntestCertainColumnFamily begin...");
        try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions().optimizeUniversalStyleCompaction()) {
            String cfName = "my-first-columnfamily";
            // list of column family descriptors, first entry must always be default column family
            final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
                    new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts),
                    new ColumnFamilyDescriptor(cfName.getBytes(), cfOpts)
            );

            List<ColumnFamilyHandle> cfHandles = new ArrayList<>();
            try (final DBOptions dbOptions = new DBOptions().setCreateIfMissing(true).setCreateMissingColumnFamilies(true);
                 final RocksDB rocksDB = RocksDB.open(dbOptions, cfdbPath, cfDescriptors, cfHandles)) {
                ColumnFamilyHandle cfHandle = cfHandles.stream().filter(x -> {
                    try {
                        return (new String(x.getName())).equals(cfName);
                    } catch (RocksDBException e) {
                        return false;
                    }
                }).collect(Collectors.toList()).get(0);

                // 写入key/value
                String key = "FirstKey";
                rocksDB.put(cfHandle, key.getBytes(), "FirstValue".getBytes());
                // 查询单key
                byte[] getValue = rocksDB.get(cfHandle, key.getBytes());
                System.out.println("get Value : " + new String(getValue));
                // 写入第2个key/value
                rocksDB.put(cfHandle, "SecondKey".getBytes(), "SecondValue".getBytes());

                List<byte[]> keys = Arrays.asList(key.getBytes(), "SecondKey".getBytes());
                List<ColumnFamilyHandle> cfHandleList = Arrays.asList(cfHandle, cfHandle);
                // 查询多个key
                List<byte[]> values = rocksDB.multiGetAsList(cfHandleList, keys);
                for (int i = 0; i < keys.size(); i++) {
                    System.out.println("multiGet:" + new String(keys.get(i)) + "--" + (values.get(i) == null ? null : new String(values.get(i))));
                }

                // 删除单key
                rocksDB.delete(cfHandle, key.getBytes());

                RocksIterator iter = rocksDB.newIterator(cfHandle);
                for (iter.seekToFirst(); iter.isValid(); iter.next()) {
                    System.out.println("iterator:" + new String(iter.key()) + ":" + new String(iter.value()));
                }
            } finally {
                // NOTE frees the column family handles before freeing the db
                for (final ColumnFamilyHandle cfHandle : cfHandles) {
                    cfHandle.close();
                }
            }
        } catch (RocksDBException e) {
            e.printStackTrace();
        } // frees the column family options
    }

    public static void main(String[] args) throws Exception {
        RocksDBExample test = new RocksDBExample();
        test.testDefaultColumnFamily();
        test.testCertainColumnFamily();
    }

}

原文链接:https://www.cnblogs.com/sxpujs/p/12486823.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java虚拟机(JVM)面试题(2020最新版)

下一篇:Java中接口和抽象类的区别?