700

0

Hive

用纯 Dart 编写的轻量级快速键值数据库。

快速、愉快和安全的 NoSQL 数据库

GitHub 工作流状态(分支) 编解码器分支 酒馆版 GitHub

Hive 是一个用纯 Dart 编写的轻量级且超快的键值对数据库。受Bitcask启发。

文档和样本 📖

在你开始之前

考虑使用Isar,这是 Hive 作者的 Flutter 数据库,它在各方面都非常出色!

特征

  • 🚀跨平台:移动端、桌面端、浏览器
  • ⚡出色的性能(参见基准
  • ❤️简单、强大、直观的 API
  • 🔒内置强大的加密功能
  • 🎈 没有原生依赖
  • 🔋包括电池

入门

查看快速入门文档以开始使用。

用法

您可以像使用地图一样使用 Hive。没有必要等待 Futures

var box = Hive.box('myBox');

box.put('name', 'David');

var name = box.get('name');

print('Name: $name');

BoxCollections

BoxCollections是一组可以像普通盒子一样使用的盒子,除了它们显着提高了网络速度。它们支持一次打开和关闭集合的所有框,并更有效地将数据存储在网络上的索引数据库中。

此外,它们还公开了可用于加速 Web 上大量数据库事务的事务。

dart:io平台上,BoxCollections 或 Transactions 没有性能提升。只有 BoxCollections 可能对某些盒子层次结构和开发经验有用。

// Create a box collection
  final collection = await BoxCollection.open(
    'MyFirstFluffyBox', // Name of your database
    {'cats', 'dogs'}, // Names of your boxes
    path: './', // Path where to store your boxes (Only used in Flutter / Dart IO)
    key: HiveCipher(), // Key to encrypt your boxes (Only used in Flutter / Dart IO)
  );

  // Open your boxes. Optional: Give it a type.
  final catsBox = collection.openBox<Map>('cats');

  // Put something in
  await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4});
  await catsBox.put('loki', {'name': 'Loki', 'age': 2});

  // Get values of type (immutable) Map?
  final loki = await catsBox.get('loki');
  print('Loki is ${loki?['age']} years old.');

  // Returns a List of values
  final cats = await catsBox.getAll(['loki', 'fluffy']);
  print(cats);

  // Returns a List<String> of all keys
  final allCatKeys = await catsBox.getAllKeys();
  print(allCatKeys);

  // Returns a Map<String, Map> with all keys and entries
  final catMap = await catsBox.getAllValues();
  print(catMap);

  // delete one or more entries
  await catsBox.delete('loki');
  await catsBox.deleteAll(['loki', 'fluffy']);

  // ...or clear the whole box at once
  await catsBox.clear();

  // Speed up write actions with transactions
  await collection.transaction(
    () async {
      await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4});
      await catsBox.put('loki', {'name': 'Loki', 'age': 2});
      // ...
    },
    boxNames: ['cats'], // By default all boxes become blocked.
    readOnly: false,
  );

存储对象

Hive 不仅支持原语、列表和映射,还支持您喜欢的任何 Dart 对象。在存储对象之前,您需要生成一个类型适配器。

@HiveType(typeId: 0)
class Person extends HiveObject {

  @HiveField(0)
  String name;

  @HiveField(1)
  int age;
}

扩展 HiveObject是可选的,但它提供了方便的方法,例如 save()delete()

var box = await Hive.openBox('myBox');

var person = Person()
  ..name = 'Dave'
  ..age = 22;
box.add(person);

print(box.getAt(0)); // Dave - 22

person.age = 30;
person.save();

print(box.getAt(0)) // Dave - 30

Hive ❤️ Flutter

Hive 是在考虑 Flutter 的情况下编写的。如果您的应用需要一个轻量级的数据存储,它是一个完美的选择。添加所需的依赖项并初始化 Hive 后,您可以在项目中使用 Hive:

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

class SettingsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: Hive.box('settings').listenable(),
      builder: (context, box, widget) {
        return Switch(
          value: box.get('darkMode'),
          onChanged: (val) {
            box.put('darkMode', val);
          }
        );
      },
    );
  }
}

盒子是缓存的,因此速度足够快,可以直接在 build()Flutter 小部件的方法中使用。

本机 AES 加密实现

使用 Flutter 时,Hive 支持使用package:cryptography 和package:cryptography_flutter进行本机加密。

原生 AES 实现极大地加速了加密盒子的操作。

请按照以下步骤操作:

  1. 向 pubspec.yaml 添加依赖项
dependencies:
  cryptography_flutter: ^2.0.2
  1. 启用本机实现
import 'package:cryptography_flutter/cryptography_flutter.dart';

void main() {
  // Enable Flutter cryptography
  FlutterCryptography.enable();

  // ....
}

基准

1000 次读取迭代 1000 次写入迭代
SharedPreferences 在读取性能方面与 Hive 相当。SQLite 的表现要差得多。 在写入或删除方面,Hive 大大优于 SQLite 和 SharedPreferences。

基准测试是在装有 Android Q 的 Oneplus 6T 上执行的。您可以自己运行基准测试

*以一粒盐来衡量这个基准。很难客观地比较数据库,因为它们是为不同目的而制作的。

执照

Copyright 2019 Simon Leier

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.