6个稳定版本

1.3.7 2023年1月3日
1.3.4 2022年1月1日
1.3.2 2021年4月3日
1.3.1 2019年9月25日
0.1.6 2019年1月27日

#105 in 算法


dmslite中使用

MIT许可协议

54KB
829

Licence Version dependency status Download pipeline docs.rs

ids_service

允许生成唯一ID的库。它尝试使用后台线程填充缓存以保持缓存充满。如果缓存为空(请求数量过高),则实时计算ID。这将减慢获取ID的速度,但缓存为空时没有错误。为了生成唯一ID,库使用来自随机数生成器的字节数组和自1970年1月1日UTC以来的纳秒时间戳作为值,最后从这两个数据创建哈希。

该库由两个具有类似API但不同哈希算法的模块组成

crypto_hash

哈希算法可以是sha3中的任何一个。

rust_hash

哈希算法是Rust标准库中的std::collections::hash_map::DefaultHasher


根据您的需求,您可以选择您需要的模块。使用crypto_hash的负面影响是运行服务的性能和资源。ids/sec的吞吐量约为rust DefaultHasher的一半。

  • 使用sha512时,在Intel i7上的指示性吞吐量超过2'000'000 ids/sec
  • 使用Rust Hash时,吞吐量超过3'300'000 ids/sec

随机块的大小等于2 * sha512的哈希大小 = 128字节。使用sha512计算唯一ID的数据块大小为128字节随机+8字节的时间戳。

ID可以编码为

  • 十六进制小写字符串
  • Base64字符串
  • Base32字符串
  • Json

快速入门

默认加密哈希的使用

extern crate ids_service;

use crate::ids_service::crypto_hash::*;
use crate::ids_service::common::*;

fn main() {

    /*
     * Create an ids service with:
     * Cache size = 100'000
     * hash algo. = sha256
     * A pool of 20 threads
     */
    let mut ids = IdsService::default();
    ids.start();
    // Optional: Wait cache is filled at 10%
    let _ = ids.filled_at_percent_event(10).recv().is_ok();
    println!("Get an id: {}", ids.get_id().as_hex());
    println!("Get another id: {}", ids.get_id().as_base64());
    println!("Get an id from cache: {}", ids.get_id_from_cache().expect("Expect an id").as_hex());
    println!("Current numbers of items in cache: {}", ids.get_cache_len());
    // Graceful Shutdown and Cleanup
    ids.stop();
}

rust哈希器的使用

extern crate ids_service;
extern crate simplelog;

use crate::ids_service::rust_hash::*;
use crate::ids_service::common::*;
use crate::simplelog::*;
use sha3::Digest;


fn main() {

    let _ = SimpleLogger::init(LevelFilter::Info, Config::default());

    /*
     * Create an ids service with:
     * Cache size = 100'000
     * hash algo. = rust SipHasher
     * A pool of 20 threads
     */
    let mut ids = IdsService::default();
    ids.start();
    // Optional: Wait cache is filled at 10%
    let _ = ids.filled_at_percent_event(10).recv().is_ok();
    println!("Get an id: {}", ids.get_id());
    println!("Get an id from cache: {}", ids.get_id_from_cache().expect("Expect an id"));
    println!("Current numbers of items in cache: {}", ids.get_cache_len());
    // Graceful Shutdown and Cleanup
    ids.stop();
}

运行示例

以_rh结尾的示例使用rust哈希器

cargo run --example examples;
cargo run --example examples_rh;
cargo run --example iterator_example;
cargo run --example iterator_example_rh;
cargo run --example quickstart;
cargo run --example quickstart_rh;
cargo run --example quickstart2;
cargo run --example quickstart2_rh;

创建一千万个ID(sha512)并读取所有内容。i7、linux、16个CPU的吞吐量> 2'000'000 ids/s

cargo run --release --example ten_million;
cargo run --release --example ten_million_rh;

平台

该库已编译并经过测试

  1. x86_64 GNU/Linux(开发+测试)
  2. FreeBSD(测试)
  3. Windows 10(测试)
  4. aarch64 GNU/Linux(测试)

依赖关系

~2.3–10MB
~75K SLoC