半小時入門Thrift

      當一個單體軟件產品體量達到一定程序,都會想到拆分爲不同的模塊(當今這麼流行微服務)。拆分後一定會存在進程之間的交互(簡稱:PRC),那麼thrift就是facebook推出一款開源的rpc框架,且還跨語言。此文章就是來打開thrift的打開(當然這次還是基於.net)。 示例代碼下載:https://gitee.com/samtest-project/thrift-test.git

一、準備工作

下載地址:http://archive.apache.org/dist/thrift(可以選擇可使用的版本),其中需要下載如下兩個文件包:

  • thrift-*.*.exe:此程序是在windows上用的,用於將thrift文件轉換爲對應語言的代碼文件工具
  • thrift-0.11.0.tar.gz:供各語言使用的基類庫,c#要編譯出對應的dll

1.1 生成Thrift.dll

此點要注意,他分爲.net35和.net45兩個版本,可以根據需要進行相應的生成

二、生成rpc可使用的文件

2.1 創建hello.thrift文件,並輸入如下內容:

struct User{
    1:i32 id
    2:string name
}

service UserService{
    User GetUserById(1:i32 userId)
     list<User> GetAll()
    void add(1:User user)
}

2.2 運行命令進行csharp代碼的生成

生成成功後,會有一個gen-csharp文件夾

gen-csharp文件夾中包含的就是我們需要的c#代碼。

三、建立項目

項目結構如下

其引用關係爲如下:

  • 所有項目都必須引用在在1.1中編譯好的Thrift.dll文件
  • Client和Server項目都必須引用Thrift.Services項目
  • 在Server端做接口的實現,接口在對應的Service下
  • UserService的實現代碼如下:
public class UserServiceImp : UserService.Iface
    {
        private IList<User> users;

        public UserServiceImp()
        {
            this.users = new List<User>();
        }

        public void add(User user)
        {
            Console.WriteLine(user.Name);
            this.users.Add(user);
        }

        public List<User> GetAll()
        {
            return this.users.ToList();
        }

        public User GetUserById(int userId)
        {
            return this.users.Where(m => m.Id == userId).FirstOrDefault();
        }
    }

四、測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章