#rpc-client #json-rpc-client #rpc #client #json #http

bma-jrpc

Rust的JSON RPC客户端

1 个不稳定版本

0.1.0 2023年4月7日

#332 in HTTP客户端

MIT 许可证

13KB
236 代码行

bma-jrpc - Rust的JSON RPC客户端 crates.io页面 docs.rs页面

为什么还需要另一个JSON-RPC客户端,已经有了很多吗?

目标是构建一个小的客户端库,可以用几行代码构建高或低级RPC客户端。

库非常适合编写测试JSON-RPC服务器的代码片段,也可以用于生产应用程序。

高级客户端使用示例

use bma_jrpc::{http_client, rpc_client};
use serde::Deserialize;
use std::time::Duration;

// Define a trait to map all RPC methods
#[rpc_client]
trait My {
    // the method returns null and has no params
    fn test(&self);
    // the method returns a structure
    fn login(&self, user: &str, password: &str) -> LoginResponse;
    // the method is mapped to RPC method "login"
    // it returns a structure but "result_field" attribute argument
    // automatically extracts "token" field only
    #[rpc(name = "login", result_field = "token")]
    fn authenticate(&self, user: &str, password: &str) -> String;
}

// The structure MyClient is automatically created for the above trait with a method "new"

// the response structure for the full "login" method output
#[derive(Deserialize, Debug)]
struct LoginResponse {
    api_version: u16,
    token: String,
}

// create a low-level HTTP RPC client
let http_client = http_client("http://127.0.0.1:7727").timeout(Duration::from_secs(2));
// create the high-level client
let client = MyClient::new(http_client);
let token = client.authenticate("admin", "xxx").unwrap();
dbg!(token);
let result: LoginResponse = client.login("admin", "xxx").unwrap();
dbg!(result);

低级客户端使用示例

use bma_jrpc::{http_client, Rpc};
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Deserialize, Debug)]
struct LoginResponse {
    api_version: u16,
    token: String,
}

#[derive(Serialize)]
struct LoginPayload<'a> {
    user: &'a str,
    password: &'a str,
}


// create a low-level HTTP RPC client
let http_client = http_client("http://127.0.0.1:7727").timeout(Duration::from_secs(2));
// use it directly. the params can be any which implements Serialize, the
// repsonse can be any which implements Deserialize
let result: LoginResponse = http_client.call(
    "login",
    LoginPayload {
        user: "admin",
        password: "xxx",
    },
).unwrap();

支持MessagePack

通过"msgpack" crate功能,可选启用MessagePack RPC的序列化和反序列化。

use bma_jrpc::{HttpClient, MsgPack};

// create a low-level HTTP RPC client
let http_client = HttpClient::<MsgPack>::new("http://127.0.0.1:7727");
// it can be used as a transport for high-level clients as well
// let client = MyClient::new(http_client);

不支持的功能(目前尚未支持)

  • 批量RPC请求

  • 不需要回复的RPC请求(没有ID)

  • 高级客户端中的异步操作

依赖项

~12–21MB
~352K SLoC