我在Elixir中尝试使用Thrift的简易服务器Riffed.Server

在以前的发布中,我用Elixir定义了thrift的结构体。

在那个时候,我尝试使用了库riffed提供的以下三个功能中的最后一个。

    1. 提供了一个Mix任务[mix compile.thrift],可以从thrift代码自动生成erlang代码的功能。

 

    1. 通过使用Riffed.Struct,可以提供能够从Elixir中访问thrift定义并由erlang生成的结构体的功能。

 

    通过提供Riffed.Server和Riffed.Client,可以简单地构建一个使用生成的代码进行数据通信的简易服务器的功能。

样本仓库如下所示。

    https://github.com/letusfly85/use_elixir_thrift

1. 准备 thrift 结构体

我准备了下面的结构体。

struct MyChatMessage
{
  1: i32 senderId,
  2: i32 recieverId,
  3: string message
}

service MyChatService
{
  void sendMessage(1: i32 senderId, 2: i32 recieverId, 3: string message);
  void recieveMessage(1: i32 senderId, 2: i32 recieverId, 3: string message);
}

2. 通过mix compile.thrift生成Erlang代码。

这里是标题一样的地方。
在项目的根目录下,将创建一个src文件夹。

实现具有Server、Client、Handler和Model四个角色的ex文件。

我在参考riffed的例子文件夹的同时进行了实现。

    • https://github.com/letusfly85/use_elixir_thrift/blob/qiita/lib/my_chat_server.ex

 

    • https://github.com/letusfly85/use_elixir_thrift/blob/qiita/lib/my_chat_client.ex

 

    • https://github.com/letusfly85/use_elixir_thrift/blob/qiita/lib/my_chat_handler.ex

 

    https://github.com/letusfly85/use_elixir_thrift/blob/qiita/lib/my_chat_message.ex

尝试移动

我要打开两个终端。

    terminal1

启动服务器和处理程序。
现在开始在2112端口等待连接。

iex(1)> UseElixirThrift.MyChatServer.start_link
11:08:25.795 [info]  thrift service listening on port 2112
{:ok, #PID<0.191.0>}

iex(2)> UseElixirThrift.MyChatHandler.start_link
{:ok, #PID<0.200.0>}
    terminal2

启动客户端

iex(1)> UseElixirThrift.MyChatClient.start_link
{:ok, #PID<0.195.0>}

我从终端2中尝试调用sendMessage方法。

iex(2)>UseElixirThrift.MyChatClient.sendMessage(1, 2, "test")
:ok

然后终端1会输出以下内容。

"got a message: test"

考虑使用案例

我打算利用这个东西来探索以下可能的用途。

    • Cassandraにレコード登録できるかどうか

 

    • Zipkin操作できるか

 

    他言語のThrift Server/Clientとの併用が可能か

今日就到这里吧。

bannerAds