半小时入门Thrift

      当一个单体软件产品体量达到必定程序,都会想到拆分为不一样的模块(当今这么流行微服务)。拆分后必定会存在进程之间的交互(简称:PRC),那么thrift就是facebook推出一款开源的rpc框架,且还跨语言。此文章就是来打开thrift的打开(固然此次仍是基于.net)。 示例代码下载:https://gitee.com/samtest-project/thrift-test.gitgit

1、准备工做

下载地址:http://archive.apache.org/dist/thrift(能够选择可以使用的版本),其中须要下载以下两个文件包:apache

  • thrift-*.*.exe:此程序是在windows上用的,用于将thrift文件转换为对应语言的代码文件工具
  • thrift-0.11.0.tar.gz:供各语言使用的基类库,c#要编译出对应的dll

1.1 生成Thrift.dll

此点要注意,他分为.net35和.net45两个版本,能够根据须要进行相应的生成c#

2、生成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文件夹windows

gen-csharp文件夹中包含的就是咱们须要的c#代码。框架

3、创建项目

项目结构以下微服务

其引用关系为以下:工具

  • 全部项目都必须引用在在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();
        }
    }

4、测试

相关文章
相关标签/搜索