Rust 常用依赖库

介绍常用的依赖库,持续更新

  1. async_trait: 异步支持
  2. once_cell: OnceCellLazy
  3. clap: 命令行支持
  4. axum: http 服务
  5. tokio: 异步运行时
  6. serde: 序列化
  7. serde_json: json 序列化
  8. log: 日志门面
  9. env_logger: 日志实现
  10. anyhow: Result
  11. chrono: 日期和时间
  12. quick-xml: 读写 xml
  13. sqlx: 异步 sql 访问
  14. dotenvy: 支持加载 .env 文件
  15. cargo-watch: 热加载代码,二进制程序
  16. cargo-expand: 展开宏代码,二进制程序
  17. evalexpr: 解析表达式
  18. reqwest: http 客户端
  19. tower: 请求和响应抽象层
  20. tower-http: http 中间件实现

09 ConcurrentHashMap

jdk 基于 8 版本

在平时的开发中,我们经常会用到 ConcurrentHashMap, 是并发安全的。

使用方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class ConcurrentHashMapTest {

    @Test
    void test() {
        Map<String, String> map = new ConcurrentHashMap<>();
        map.put("1", "1");
        assertThat(map.get("1")).isEqualTo("1");
        map.remove("1");
        assertThat(map.size()).isEqualTo(0);
    }
}

put

添加元素。

08 CopyOnWriteArrayList

jdk 基于 8 版本

在平时的开发中,我们经常会用到 CopyOnWriteArrayList, 利用写时复制的机制来保证并发安全, 适合多读少写的场景。

使用方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class CopyOnWriteArrayListTest {

    @Test
    public void test() {
        List<String> data = new CopyOnWriteArrayList<>();
        data.add("1");
        assertThat(data.get(0)).isEqualTo("1");
        data.remove("1");
        assertThat(data.isEmpty()).isEqualTo(true);
    }
}

add

添加元素,写时复制

07 ThreadPoolExecutor

jdk 基于 8 版本

在平时的开发中,我们经常会用到 ThreadPoolExecutor, 需要了解源码

使用方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class ThreadPoolTest {

    @Test
    void test() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                10,
                60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                new CustomizableThreadFactory("test-"),
                new ThreadPoolExecutor.CallerRunsPolicy());
        executor.submit(() -> {
            System.out.println("xxxx");
        });
        executor.shutdown();
    }
}

new

创建线程池。