rpc服务框架thrift介绍

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接口高效



原文地址:https://www.cnblogs.com/energy1010/p/10381215.html

时间: 2024-08-07 01:39:36

rpc服务框架thrift介绍的相关文章

Thrift 个人实战--Thrift RPC服务框架日志的优化

前言: Thrift作为Facebook开源的RPC框架, 通过IDL中间语言, 并借助代码生成引擎生成各种主流语言的rpc框架服务端/客户端代码. 不过Thrift的实现, 简单使用离实际生产环境还是有一定距离, 本系列将对Thrift作代码解读和框架扩充, 使得它更加贴近生产环境. 本文讲述RPC服务框架中, 日志的重要性, 以及logid的引入. 日志不仅包含丰富的数据(就看是否会挖掘), 而且还是线上服务问题追踪和排查错误最好的方式. 日志级别 采用大家喜闻乐见的log4j作为该RPC服

RPC服务框架探索之Thrift

前言架构服务化后,需要实现一套方便调用各服务的框架,现在开源如日中天,优先会寻找开源实现,如果没有合适自家公司业务的,才会考虑从零开发,尤其是一切以KPI为准绳的公司,谁会跟钱过不去?N个月之前,公司大神就开始调研了,最后选中了Thrift这个RPC服务框架.使用不熟悉的技术,我会感到很恐惧,它就相当于一个黑盒,我对它一无所知,它是如何运转的?出了问题该如何解决?带着一丝不安,查阅了相关技术文档. RPC很早之前听说过soap,restful api,rpc之类的服务协议,一直都没有机会深入实践

基于netty轻量的高性能分布式RPC服务框架forest&lt;下篇&gt;

基于netty轻量的高性能分布式RPC服务框架forest<上篇> 文章已经简单介绍了forest的快速入门,本文旨在介绍forest用户指南. 基本介绍 Forest是一套基于java开发的RPC框架,除了常规的点对点调用外,Motan还提供服务治理功能,包括服务节点的自动发现.摘除.高可用和负载均衡等. 架构概述 Forest中分为服务提供方(RPC Server),服务调用方(RPC Client)和服务注册中心(Registry)三个角色. Server提供服务,向Registry注册

RSF 分布式 RPC 服务框架的分层设计

RSF 是个什么东西? 一个高可用.高性能.轻量级的分布式服务框架.支持容灾.负载均衡.集群.一个典型的应用场景是,将同一个服务部署在多个Server上提供 request.response 消息通知.使用RSF可以点对点调用,也可以分布式调用.部署方式上:可以搭配注册中心,也可以独立使用. 渊源 RSF 的核心思想参考了淘宝HSF.Dubbo 等优秀框架.功能上大体相似,但是实现逻辑完全不同.因此没有什么历史包袱.总的来说对比淘宝HSF少了历史包袱,相比Dubbo更加轻量化.而且还支持了虚拟机

RPC通信框架——RCF介绍(替换COM)

阅读目录 RPC通信框架 为什么选择RCF 简单的性能测试 参考资料 总结 现有的软件中用了大量的COM接口,导致无法跨平台,当然由于与Windows结合的太紧密,还有很多无法跨平台的地方.那么为了实现跨平台,支持Linux系统,以及后续的分布式,首要任务是去除COM接口. 在对大量框架进行调研后,决定使用RCF替换COM接口. 回到顶部 RPC通信框架 CORBA ICE Thrift zeromq dbus RCF YAMI4 TAO 回到顶部 为什么选择RCF 经过各项对比,认为: RCF

RPC通信框架&mdash;&mdash;RCF介绍

现有的软件中用了大量的COM接口,导致无法跨平台,当然由于与Windows结合的太紧密,还有很多无法跨平台的地方.那么为了实现跨平台,支持Linux系统,以及后续的分布式,首要任务是去除COM接口. 在对大量框架进行调研后,决定使用RCF替换COM接口. RPC通信框架 CORBA ICE Thrift zeromq dbus RCF YAMI4 TAO 为什么选择RCF 经过各项对比,认为: RCF的使用方式与现有的COM接口方式非常类似,在开发上可以更快速.更容易的替换COM,并且可以少犯错

唯品会RPC服务框架与容器化演进--转

原文地址:http://mp.weixin.qq.com/s?__biz=MzAwMDU1MTE1OQ==&mid=405781868&idx=1&sn=cbb10d37e25c76a1845f593a222da3c9&scene=0#wechat_redirect 编者按:本文是邱戈川在 3 月 27 日数人云"百万并发"活动的演讲,授权「高可用架构」首发.转载请注明来自高可用架构公众号「ArchNotes」.   邱戈川,唯品会分布式架构平台产品经理

基于开源Dubbo分布式RPC服务框架的部署整合

一.前言 Dubbo 作为SOA服务化治理方案的核心框架,用于提高业务逻辑的复用.整合.集中管理,具有极高的可靠性(HA)和伸缩性,被应用于阿里巴巴各成员站点,同时在包括JD.当当在内的众多互联网项目中有着广泛应用.dubbo 通过高性能 RPC 实现服务的输出和输入功能,框架基于 Spring Framework 进行无缝集成,使用过程中基本看不到 Dubbo API的直接调用,Dubbo服务支持RMI.Hessian.Dubbo.WebService等众多通信协议,同时提供了对服务的监控和管

【Rpc】基于开源Dubbo分布式RPC服务框架的部署整合

一.前言 Dubbo 作为SOA服务化治理方案的核心框架,用于提高业务逻辑的复用.整合.集中管理,具有极高的可靠性(HA)和伸缩性,被应用于阿里巴巴各成员站点,同时在包括JD.当当在内的众多互联网项目中有着广泛应用.dubbo 通过高性能 RPC 实现服务的输出和输入功能,框架基于 Spring Framework 进行无缝集成,使用过程中基本看不到 Dubbo API的直接调用,Dubbo服务支持RMI.Hessian.Dubbo.WebService等众多通信协议,同时提供了对服务的监控和管