rpc服务框架thrift介绍(代码片段)

energy1010 energy1010     2023-03-09     306

关键词:

 

rpc服务框架目前主要有 thrift, grpc, dubbo, HSF等

这里主要介绍thrift框架

git地址  :https://github.com/apache/thrift/tree/0.9.1

1. 接口定义 tutorial.thrift

include "shared.thrift"

/**
 * Thrift files can namespace, package, or prefix their output in various
 * target languages.
 */

namespace cl tutorial
namespace cpp tutorial
namespace d tutorial
namespace dart tutorial
namespace java tutorial
namespace php tutorial
namespace perl tutorial
namespace haxe tutorial
namespace netcore tutorial
namespace netstd tutorial

/**
 * Thrift lets you do typedefs to get pretty names for your types. Standard
 * C style here.
 */
typedef i32 MyInteger

/**
 * Thrift also lets you define constants for use across languages. Complex
 * types and structs are specified using JSON notation.
 */
const i32 INT32CONSTANT = 9853
const map<string,string> MAPCONSTANT = ‘hello‘:‘world‘, ‘goodnight‘:‘moon‘

/**
 * You can define enums, which are just 32 bit integers. Values are optional
 * and start at 1 if not supplied, C style again.
 */
enum Operation 
  ADD = 1,
  SUBTRACT = 2,
  MULTIPLY = 3,
  DIVIDE = 4


/**
 * Structs are the basic complex data structures. They are comprised of fields
 * which each have an integer identifier, a type, a symbolic name, and an
 * optional default value.
 *
 * Fields can be declared "optional", which ensures they will not be included
 * in the serialized output if they aren‘t set.  Note that this requires some
 * manual management in some languages.
 */
struct Work 
  1: i32 num1 = 0,
  2: i32 num2,
  3: Operation op,
  4: optional string comment,


/**
 * Structs can also be exceptions, if they are nasty.
 */
exception InvalidOperation 
  1: i32 whatOp,
  2: string why


/**
 * Ahh, now onto the cool part, defining a service. Services just need a name
 * and can optionally inherit from another service using the extends keyword.
 */
service Calculator extends shared.SharedService 

  /**
   * A method definition looks like C code. It has a return type, arguments,
   * and optionally a list of exceptions that it may throw. Note that argument
   * lists and exception lists are specified using the exact same syntax as
   * field lists in struct or exception definitions.
   */

   void ping(),

   i32 add(1:i32 num1, 2:i32 num2),

   i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),

   /**
    * This method has a oneway modifier. That means the client only makes
    * a request and does not listen for any response at all. Oneway methods
    * must be void.
    */
   oneway void zip()


2. 根据接口定义文件生成相应的服务接口

thrift -r --gen py tutorial.thrift 根据thrift接口定义生成服务接口
执行完后会在当前目录生成 gen-py文件夹, 下面包含 tutorial shared两个子文件夹

技术图片

主要文件就是Calulator.py 定义了相应语言的接口协议

3. 根据接口,实现接口功能,提供服务

这步是最重要的,开始实现接口功能, 上面由接口定义文件service可知, 定义了4个功能: ping  add  caculate zip

这里用python实现上述接口, PythonServer.py

import glob
import sys
sys.path.append(‘gen-py‘)
sys.path.insert(0, glob.glob(‘../../lib/py/build/lib*‘)[0])

from tutorial import Calculator
from tutorial.ttypes import InvalidOperation, Operation

from shared.ttypes import SharedStruct

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer


class CalculatorHandler:
    def __init__(self):
        self.log = 

    def ping(self):
        print(‘ping()‘)

    def add(self, n1, n2):
        print(‘add(%d,%d)‘ % (n1, n2))
        return n1 + n2

    def calculate(self, logid, work):
        print(‘calculate(%d, %r)‘ % (logid, work))

        if work.op == Operation.ADD:
            val = work.num1 + work.num2
        elif work.op == Operation.SUBTRACT:
            val = work.num1 - work.num2
        elif work.op == Operation.MULTIPLY:
            val = work.num1 * work.num2
        elif work.op == Operation.DIVIDE:
            if work.num2 == 0:
                x = InvalidOperation()
                x.whatOp = work.op
                x.why = ‘Cannot divide by 0‘
                raise x
            val = work.num1 / work.num2
        else:
            x = InvalidOperation()
            x.whatOp = work.op
            x.why = ‘Invalid operation‘
            raise x

        log = SharedStruct()
        log.key = logid
        log.value = ‘%d‘ % (val)
        self.log[logid] = log

        return val

    def getStruct(self, key):
        print(‘getStruct(%d)‘ % (key))
        return self.log[key]

    def zip(self):
        print(‘zip()‘)


if __name__ == ‘__main__‘:
    handler = CalculatorHandler()
    processor = Calculator.Processor(handler)
    transport = TSocket.TServerSocket(host=‘127.0.0.1‘, port=9090)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

 python PythonServer.py 然后可以看到rpc对外开始提供服务, 这里注意host, port

技术图片

 

 

4.实现客户端,连接rpc服务接口

PythonClient.py

import sys
import glob
sys.path.append(‘gen-py‘)
sys.path.insert(0, glob.glob(‘../../lib/py/build/lib*‘)[0])

from tutorial import Calculator
from tutorial.ttypes import InvalidOperation, Operation, Work

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol


def main():
    # Make socket
    transport = TSocket.TSocket(‘localhost‘, 9090)

    # Buffering is critical. Raw sockets are very slow
    transport = TTransport.TBufferedTransport(transport)

    # Wrap in a protocol
    protocol = TBinaryProtocol.TBinaryProtocol(transport)

    # Create a client to use the protocol encoder
    client = Calculator.Client(protocol)

    # Connect!
    transport.open()

    client.ping()
    print(‘ping()‘)

    sum_ = client.add(1, 1)
    print(‘1+1=%d‘ % sum_)

    work = Work()

    work.op = Operation.DIVIDE
    work.num1 = 1
    work.num2 = 0

    try:
        quotient = client.calculate(1, work)
        print(‘Whoa? You know how to divide by zero?‘)
        print(‘FYI the answer is %d‘ % quotient)
    except InvalidOperation as e:
        print(‘InvalidOperation: %r‘ % e)

    work.op = Operation.SUBTRACT
    work.num1 = 15
    work.num2 = 10

    diff = client.calculate(1, work)
    print(‘15-10=%d‘ % diff)

    log = client.getStruct(1)
    print(‘Check log: %s‘ % log.value)

    # Close!
    transport.close()

 启动客户端,连接rpc服务

技术图片

 

可以看到,已经能get到结果了,通过rpc,可以实现,接口实现与使用的分离, 使用不同语言,而且效率远比restful接口高效

 

 

 

 

 

thrift介绍(代码片段)

...谅解。)    Apachethrift框架,旨在处理扩语言的开发服务,它结合代码生产引擎的软件栈,构建高效地和无缝地运行在C++,Java,Python,PHP,Ruby,Erlang,Perl,Haskell,C#,Cocoa,JavaScript,Node.js,Smalltalk,OCaml和Delphi等语言中的服务。 二 文... 查看详情

apachethrift-使用,内部实现及构建一个可扩展的rpc框架

...个常见的SOA实践。Thrift介绍ApacheThrift是Facebook开发的远程服务调用框架,它采用接口描述语言(IDL)定义并创建服务,支 查看详情

消息总线扩展之集成thrift-rpc(代码片段)

...线同时为SOA提供基础设施。Thrift简介Thrift是一个跨语言的服务部署框架,最 查看详情

thrift基础教程安装篇

...rift简单介绍Thrift是一款由Fackbook开发的可伸缩、跨语言的服务开发框架,该框架已经开源而且增加的Apache项目。Thrift主要功能是:通过自己定义的Interface Definition Language(IDL)。能够创建基于RPC的client和服务端的服务代码。... 查看详情

rpc简介与thrift框架

...ocesscall,远程过程调用,简单来讲就是调用部署在另一台服务器上的服务或者被部署在另一台服务器上的服务调用。由于各服务部署在不同机器,服务间的调用免不了网络通信过程,服务消费方每调用一个服务都要写一坨网络通... 查看详情

vip_osp--基于thrift的rpc框架的基本原理

...ApacheThrift远程调用框架二次开发的高性能、高可扩展的、服务治理的RPC框架。服务端使用IDL进行服务的定义,客户端集成服务的SDK即可调用服务端的服务,开发简单,大部分的公共功能都在Proxy代理层工作,减轻了开发者的负担... 查看详情

thrift架构介绍

 Thrift是一个跨语言的服务部署框架,最初由Facebook于2007年开发,2008年进入Apache开源项目。Thrift通过一个中间语言(IDL,接口定义语言)来定义RPC的接口和数据类型,然后通过一个编译器生成不同语言的代码(目前支持C++,Java,Pytho... 查看详情

基于thrift的跨语言高可用高性能轻量级的rpc框架

...信负载均衡和容灾处理方便的实现任务的分布式处理支持服务的水平扩展,自动发现新的服务节点能够兼容各种异常情况,如节点的异常down机可视化管理通过服务管理系统可以方便查看服务状态和统计信息与原生thrift通信支持... 查看详情

thrift单向通道服务的局限性

thrift作为RPC调用的开源框架介绍,网上已经有不少的介绍,在此不赘述,而是讨论thrift的简单应用下的问题测试代码 shortsThriftPort=0; std::stringstrThriftIP; CSystemConfig::GetInstance().GetThriftServiceInfo(strThriftIP,sThriftPort); boost::shared_ptr& 查看详情

rpc框架之thrift分析(转)

一、简介1、Thrift是Facebook开发的跨语言的RPC服务框架。随后贡献给Apache开源组织。成为RPC服务的主流框架。 2、特点: 优点:     跨语言,支持java、c/c++、python等多种编程语言     IDL... 查看详情

thrift写rpc接口

Thrift总结(二)创建RPC服务 前面介绍了thrift基础的东西,怎么写thrift 语法规范编写脚本,如何生成相关的语言的接口。不清楚的可以看这个《Thrift总结(一)介绍》。做好之前的准备工作以后,下面就开始如何用Thrift写RPC接口... 查看详情

[linux]以匹配系统为例入门thrift框架(代码片段)

...行编程速成什么是ThriftThrift是一个轻量级、跨语言的远程服务调用框架。它通过自身的IDL中间语言,并借助代码生成引擎 查看详情

thrift

Thrift公司的一些平台服务框架底层封装了thrift提供服务,最近项目不是很紧,于是研究了一下,刚刚入门,理解得不深,写这篇博文来整理一下思路.什么是thrift?  简单来说,是Facebook公布的一款开源跨语言的RPC框架.  那么问题来了.... 查看详情

qt中调用thrift(代码片段)

...PC(RemoteProcedureCall)框架,让不同语言构建的服务可以做到远程调用无缝对接。thrift库分两部分:libthrift-核心库文件,需要依赖OpenSSL、boostlibthriftnb-包含thrift非阻塞服务器,需要libevent编译环境 查看详情

消息总线扩展之集成thrift-rpc(代码片段)

...线同时为SOA提供基础设施。Thrift简介Thrift是一个跨语言的服务部署框架,最初由Facebook于2007年开发,2008年进入Apache开源项目。Thrift通过一个中间语言(IDL,接口定义语言)来定义RPC的接口和数据类型,然后通过一个编译... 查看详情

rpc框架-thrift客户端

   -------客户端程序------下载   下载thrift源代码包   下载thrift的bin包准备描述文件(使用源代码包的示例文件)    hrift-0.10.0 utorialshared.thrift    hrift-0 查看详情

thriftrpc框架的安装和使用(代码片段)

...为RemoteProcedureCall,意为远程过程调用.    假设有两台服务器A,B.A服务器上部署着一个应用a,B服务器上部署着一个应用b,现在a 查看详情

rpc框架之thrift架构及源码解读

...件以”*.thrift”命名。代码生成完,被调用方要编写服务端代码2.Thrift为什么可以跨语言?客户端与服务端一致遵循Thrift传输协议3.Thrift架构最上层用户自行实现的业务逻辑代码第二层,thrift编译自动生成的代码,... 查看详情