• RocksDB Java Example


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

    • 高性能: RocksDB使用日志结构的数据库引擎,完全用C++编写,以获得最大的性能。 键和值是任意大小的字节流。
    • 为快速存储而优化: RocksDB针对快速、低延迟的存储(如闪存驱动器和高速磁盘驱动器)进行了优化。RocksDB充分利用了flash或RAM提供的高读/写速率的潜力。
    • 适应性强: RocksDB 可以适应不同的工作负载。 从 MyRocks 等数据库存储引擎到应用程序数据缓存到嵌入式工作负载,RocksDB 可以用于满足各种数据需求。
    • 基础和高级数据库操作: 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("
    testCertainColumnFamily 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();
        }
    
    }
    
  • 相关阅读:
    C# 中的栈和堆
    C# 中的基本数值类型
    多个 .NET 框架
    简单介绍托管执行和 CLI
    C# 控制台输入和输出
    在 C# 中使用变量
    C# 语法基础
    LeetCode 1482. 制作 m 束花所需的最少天数
    C# 基础(更新中)
    圆形靶内的最大飞镖数量
  • 原文地址:https://www.cnblogs.com/sxpujs/p/12486823.html
Copyright © 2020-2023  润新知