使用Thrift RPC编写程序(服务端和客户端)

1. Thrift类介绍
Thrift代码包(位于thrift-0.6.1/lib/cpp/src)有以下几个目录:

concurrency:并发和时钟管理方面的库
processor:Processor相关类
protocal:Protocal相关类
transport:transport相关类
server:server相关类

1.1 Transport类(how is transmitted?)
负责数据传输,有以下几个可用类:
TFileTransport:文件(日志)传输类,允许client将文件传给server,允许server将收到的数据写到文件中;
THttpTransport:采用Http传输协议进行数据传输;
TSocket:采用TCP Socket进行数据传输;
TZlibTransport:压缩后对数据进行传输,或者将收到的数据解压。

下面几个类主要是对上面几个类地装饰(采用了装饰模式),以提高传输效率。
TBufferedTransport:对某个Transport对象操作的数据进行buffer,即从buffer中读取数据进行传输,或者将数据直接写入buffer;
TFramedTransport:同TBufferedTransport类似,也会对相关数据进行buffer,同时,它支持定长数据发送和接收;
TMemoryBuffer:从一个缓冲区中读写数据。
1.2 Protocol类(what is transmitted?)
负责数据编码,主要有以下几个可用类:
TBinaryProtocol:二进制编码
TJSONProtocol:JSON编码
TCompactProtocol:密集二进制编码
TDebugProtocol:以用户易读的方式组织数据

1.3 Server类(providing service for clients)
TSimpleServer:简单的单线程服务器,主要用于测试
TThreadPoolServer:使用标准阻塞式IO的多线程服务器
TNonblockingServer:使用非阻塞式IO的多线程服务器,TFramedTransport必须使用该类型的server
1.5 对象序列化和反序列化 Thrift中的Protocol负责对数据进行编码,因而可使用Protocol相关对象进行序列化和反序列化。

2.编写client和server

2.1 client端代码编写
Client编写的方法分为以下几个步骤:
(1) 定义TTransport,为你的client设置传输方式(如socket, http等)。
(2) 定义Protocal,使用装饰模式(Decorator设计模式)封装TTransport,为你的数据设置编码格式(如二进制格式,JSON格式等)
(3) 实例化client对象,调用服务接口。
说明:如果用户在thrift文件中定义了一个叫${server_name}的service,则会生成一个叫${server_name}Client的对象。

2.2 Server端代码编写
(1) 定义一个TProcess,这个是thrift根据用户定义的thrift文件自动生成的类
(2) 使用TServerTransport获得一个TTransport
(3) 使用TTransportFactory,可选地将原始传输转换为一个适合的应用传输(典型的是使用TBufferedTransportFactory)
(4) 使用TProtocolFactory,为TTransport创建一个输入和输出
(5) 创建TServer对象(单线程,可以使用TSimpleServer;对于多线程,用户可使用TThreadPoolServer或者TNonblockingServer),调用它的server()函数。
说明:thrift会为每一个带service的thrift文件生成一个简单的server代码(桩),

3.示例:

1. thrift生成代码

创建Thrift文件:G:\test\thrift\demoHello.thrift ,内容如下:

 
namespace java com.micmiu.thrift.demo

service  HelloWorldService {

string sayHello(1:string username)

}

thrift-0.8.0.exe 是官网提供的windows下编译工具,运用这个工具生成相关代码:

thrift-0.8.0.exe -r -gen java ./demoHello.thrift

将生成的HelloWorldService.java 文件copy到自己测试的工程中,我的工程是用maven构建的,故在pom.xml中增加如下内容:

<dependency>
     <groupId>org.apache.thrift</groupId>
     <artifactId>libthrift</artifactId>
     <version>0.8.0</version>
</dependency>
<dependency>
     <groupId>org.slf4j</groupId>
     <artifactId>slf4j-log4j12</artifactId>
     <version>1.5.8</version>
</dependency>

2. 实现接口Iface

java代码:HelloWorldImpl.java

package com.micmiu.thrift.demo;
import org.apache.thrift.TException;

public class HelloWorldImpl implements HelloWorldService.Iface {
     public HelloWorldImpl() {
     }
     @Override
     public String sayHello(String username) throws TException {
          return "Hi," + username + " welcome to my blog www.micmiu.com";
     }
}

3.TSimpleServer服务端

简单的单线程服务模型,一般用于测试。

编写服务端server代码:HelloServerDemo.java

package com.micmiu.thrift.demo;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;

public class HelloServerDemo {
     public static final int SERVER_PORT = 8090;
     public void startServer() {
          try {
               System.out.println("HelloWorld TSimpleServer start ....");
               TProcessor tprocessor = new HelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(
                         new HelloWorldImpl());
               // HelloWorldService.Processor&lt;HelloWorldService.Iface&gt; tprocessor =
               // new HelloWorldService.Processor&lt;HelloWorldService.Iface&gt;(
               // new HelloWorldImpl());
               // 简单的单线程服务模型,一般用于测试
               TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
               TServer.Args tArgs = new TServer.Args(serverTransport);
               tArgs.processor(tprocessor);
               tArgs.protocolFactory(new TBinaryProtocol.Factory());
               // tArgs.protocolFactory(new TCompactProtocol.Factory());
               // tArgs.protocolFactory(new TJSONProtocol.Factory());
               TServer server = new TSimpleServer(tArgs);
               server.serve();
          } catch (Exception e) {
               System.out.println("Server start error!!!");
               e.printStackTrace();
          }
     }
     /**
     * @param args
     */
     public static void main(String[] args) {
          HelloServerDemo server = new HelloServerDemo();
          server.startServer();
     }
}

编写客户端Client代码:HelloClientDemo.java

package com.micmiu.thrift.demo;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

public class HelloClientDemo {
     public static final String SERVER_IP = "localhost";
     public static final int SERVER_PORT = 8090;
     public static final int TIMEOUT = 30000;
     /**
     *
     * @param userName
     */
     public void startClient(String userName) {
          TTransport transport = null;
          try {
               transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
               // 协议要和服务端一致
               TProtocol protocol = new TBinaryProtocol(transport);
               // TProtocol protocol = new TCompactProtocol(transport);
               // TProtocol protocol = new TJSONProtocol(transport);
               HelloWorldService.Client client = new HelloWorldService.Client(
                         protocol);
               transport.open();
               String result = client.sayHello(userName);
               System.out.println("Thrify client result =: " + result);
          } catch (TTransportException e) {
               e.printStackTrace();
          } catch (TException e) {
               e.printStackTrace();
          } finally {
               if (null != transport) {
                    transport.close();
               }
          }
     }
     /**
     * @param args
     */
     public static void main(String[] args) {
          HelloClientDemo client = new HelloClientDemo();
          client.startClient("Michael");
     }
}

先运行服务端程序,日志如下:

 
HelloWorld TSimpleServer start ....

再运行客户端调用程序,日志如下:

 
Thrify client result =: Hi,Michael welcome to my blog www.micmiu.com

测试成功,和预期的返回信息一致。

总结:Server端和client端编码基本步骤

1.服务端编码基本步骤:

  • 实现服务处理接口impl
  • 创建TProcessor
  • 创建TServerTransport
  • 创建TProtocol
  • 创建TServer
  • 启动Server

2.客户端编码基本步骤:

  • 创建Transport
  • 创建TProtocol
  • 基于TTransport和TProtocol创建 Client
  • 调用Client的相应方法

参考资料:http://www.micmiu.com/soa/rpc/thrift-sample/
               http://dongxicheng.org/search-engine/thrift-rpc/

时间: 2024-12-28 23:27:30

使用Thrift RPC编写程序(服务端和客户端)的相关文章

php编写TCP服务端和客户端程序

From: http://blog.csdn.net/anda0109/article/details/46655301 1.修改php.ini,打开extension=php_sockets.dll 2.服务端程序SocketServer.php [php] view plaincopyprint? <?php //确保在连接客户端时不会超时 set_time_limit(0); //设置IP和端口号 $address = "127.0.0.1"; $port = 3046;

C# 编写WCF简单的服务端与客户端

http://www.wxzzz.com/1860.html Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台.整合了原有的windows通讯的 .net Remoting,WebService,Socket的机制,并融合有HTTP和FTP的相关技术.是Windows平台上开发分布式应用最佳的实践方式. 今天带如何一步一步实现WCF服务端与客户端的开发及基础讲解. 一.在Visual

纯正商业级应用-Node.js Koa2开发微信小程序服务端

第1章 前言.导学与node.js如何理解Node.js?前端到底要不要学习Node.js?本课程能让你学到什么? 第2章 Koa2的那点事儿与异步编程模型Koa非常的精简,基本上,没有经过二次开发的Koa根本“不能”用.本章我们讲解Koa的重要特性,理解什么是洋葱模型?以及在KOA中如何进行异步编程?很多同学都了解以上知识点,但听完本章,你会有一些不一样的理解,比如:为什么要有洋葱模型?没有会怎样?Koa中间件一定是异步的吗? ... 第3章 路由系统的改造Koa-router需要进行一些改造

Thrift操作(Python服务端和Nodejs客户端)

目录 前言 python服务端 nodejs客户端 win10运行thrift 测试 前言 操作系统win10 时间2019年02月 Thrift版本:Thrift version 0.11.0 Python版本: Python 3.5.2 Nodejs版本: node v8.9.3 参考网址1 python服务端 安装thrift python install thrift server.py # -*- coding: utf-8 -*- import json # 调用python安装的t

[C语言]一个很实用的服务端和客户端进行TCP通信的实例

本文给出一个很实用的服务端和客户端进行TCP通信的小例子.具体实现上非常简单,只是平时编写类似程序,具体步骤经常忘记,还要总是查,暂且将其记下来,方便以后参考. (1)客户端程序,编写一个文件client.c,内容如下: #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <

基于SignalR的服务端和客户端通讯处理

SignalR是一个.NET Core/.NET Framework的实时通讯的框架,一般应用在ASP.NET上,当然也可以应用在Winform上实现服务端和客户端的消息通讯,本篇随笔主要基于SignalR的构建一个基于Winform的服务端和客户端的通讯处理案例,介绍其中的处理过程. 1.SignalR基础知识 SignalR是一个.NET Core/.NET Framework的开源实时框架. SignalR的可使用Web Socket, Server Sent Events 和 Long

用Java实现HTTP Multipart的服务端和客户端

今天简单介绍一下如何用Java支持HTTP Multipart的request和response. 整个项目的代码可以在https://github.com/mcai4gl2/multi下载. 在这个程序里,我们的业务场景很简单.在服务端有一个随机数生成器,可以生成随机的Integer和Guid,客户端通过服务,可以请求一个或多个随机数.同时,客户端可以向服务端发送一个或多个随机数,这些随机数会被加入到一个队列中,被其他的客户端通过请求获得.以下是我们的随机数Bean的定义: [java] vi

SVN1.6服务端和客户端安装配置指导

本节向大家描述SVN1.6服务端和客户端安装配置步骤,随着SVN的快速发展,版本也进行了升级更新,本节就和大家一起学习一下SVN1.6服务端和客户端安装配置步骤,欢迎大家一起来学习.下面是具体介绍.1.软件下载下载SVN1.6服务器程序.http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91[注意]如果之前已经安装了TortoiseSVN客户端,必须选择与之配套的SVN服务端版本,否则会出现各种问题,可以从Tor

grpc(3):使用 golang 开发 grpc 服务端和客户端

1,关于grpc-go golang 可以可以做grpc的服务端和客户端. 官网的文档: http://www.grpc.io/docs/quickstart/go.html https://github.com/grpc/grpc-go 和之前写的java的grpc客户端调用相同.也需要使用protobuf的配置文件. 但是golang下面的类库非常的简单,而且golang的性能也很强悍呢. 有些简单的业务逻辑真的可以使用golang进行开发. 性能强悍而且,消耗的资源也很小.java感觉上已