Thrift-简单的使用
citgpt 2024-09-26 11:27 7 浏览 0 评论
简介
The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.
Apache Thrift是一个软件框架,用来进行可扩展跨语言的服务开发,结合了软件堆栈和代码生成引擎,用来构建C++,Java,Python…等语言,使之它们之间无缝结合、高效服务。
安装
brew install thrift
作用
跨语言调用,打破不同语言之间的隔阂。 跨项目调用,微服务的么么哒。
示例
前提
thrift版本:
Go的版本、Php版本、Python版本:
说明
该示例包含python,php,go三种语言。(java暂无)
新建HelloThrift.thrift
进入目录
cd /Users/birjemin/Developer/Php/study-php
编写HelloThrift.thrift
vim HelloThrift.thrift
内容如下:
namespace php HelloThrift { string SayHello(1:string username) }
Php测试
加载thrift-php库
composer require apache/thrift
生成php版本的thrift相关文件
cd /Users/birjemin/Developer/Php/study-php thrift -r --gen php:server HelloThrift.thrift
这时目录中生成了一个叫做
gen-php
的目录。建立
Server.php
文件
<?php /** * Created by PhpStorm. * User: birjemin * Date: 22/02/2018 * Time: 3:59 PM */ namespace HelloThrift\php; require_once 'vendor/autoload.php'; use Thrift\ClassLoader\ThriftClassLoader; use Thrift\Protocol\TBinaryProtocol; use Thrift\Transport\TPhpStream; use Thrift\Transport\TBufferedTransport; $GEN_DIR = realpath(dirname(__FILE__)).'/gen-php'; $loader = new ThriftClassLoader(); $loader->registerDefinition('HelloThrift',$GEN_DIR); $loader->register(); class HelloHandler implements \HelloThrift\HelloServiceIf { public function SayHello($username) { return "Php-Server: " . $username; } } $handler = new HelloHandler(); $processor = new \HelloThrift\HelloServiceProcessor($handler); $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W)); $protocol = new TBinaryProtocol($transport,true,true); $transport->open(); $processor->process($protocol,$protocol); $transport->close();
建立
Client.php
文件
<?php /** * Created by PhpStorm. * User: birjemin * Date: 22/02/2018 * Time: 4:00 PM */ namespace HelloThrift\php; require_once 'vendor/autoload.php'; use Thrift\ClassLoader\ThriftClassLoader; use Thrift\Protocol\TBinaryProtocol; use Thrift\Transport\TSocket; use Thrift\Transport\THttpClient; use Thrift\Transport\TBufferedTransport; use Thrift\Exception\TException; $GEN_DIR = realpath(dirname(__FILE__)).'/gen-php'; $loader = new ThriftClassLoader(); $loader->registerDefinition('HelloThrift', $GEN_DIR); $loader->register(); if (array_search('--http',$argv)) { $socket = new THttpClient('local.study-php.com', 80,'/Server.php'); } else { $host = explode(":", $argv[1]); $socket = new TSocket($host[0], $host[1]); } $transport = new TBufferedTransport($socket,1024,1024); $protocol = new TBinaryProtocol($transport); $client = new \HelloThrift\HelloServiceClient($protocol); $transport->open(); echo $client->SayHello("Php-Client"); $transport->close();
测试
php Client.php --http
Python测试
加载thrift-python3模块(只测试python3,python2就不测试了)
pip3 install thrift
生成python3版本的thrift相关文件
thrift -r --gen py HelloThrift.thrift
这时目录中生成了一个叫做
gen-py
的目录。建立
Server.py
文件
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import sys sys.path.append('./gen-py') from HelloThrift import HelloService from HelloThrift.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServerclass HelloWorldHandler: def __init__(self): self.log = {} def SayHello(self, user_name = ""): return "Python-Server: " + user_name handler = HelloWorldHandler() processor = HelloService.Processor(handler) transport = TSocket.TServerSocket('localhost', 9091) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) server.serve()
建立
Client.py
文件
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import sys sys.path.append('./gen-py') from HelloThrift import HelloService from HelloThrift.ttypes import * from HelloThrift.constants import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol host = sys.argv[1].split(':') transport = TSocket.TSocket(host[0], host[1]) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = HelloService.Client(protocol) transport.open() msg = client.SayHello('Python-Client') print(msg) transport.close()
测试 开一个新窗口,运行下面命令:
python3 Server.php
Go测试
加载go的thrift模块
go get git.apache.org/thrift.git/lib/go/thrift
生成go版本的thrift相关文件
thrift -r --gen go HelloThrift.thrift
生成
Server.go
文件
package main import ( "./gen-go/hellothrift" "git.apache.org/thrift.git/lib/go/thrift" "context" ) const ( NET_WORK_ADDR = "localhost:9092" ) type HelloServiceTmpl struct {} func (this *HelloServiceTmpl) SayHello(ctx context.Context, str string) (s string, err error) { return "Go-Server:" + str, nil } func main() { transportFactory := thrift.NewTTransportFactory() protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() transportFactory = thrift.NewTBufferedTransportFactory(8192) transport, _ := thrift.NewTServerSocket(NET_WORK_ADDR) handler := &HelloServiceTmpl{} processor := hellothrift.NewHelloServiceProcessor(handler) server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory) server.Serve() }
生成
Client.go
文件
package main import ( "./gen-go/hellothrift" "git.apache.org/thrift.git/lib/go/thrift" "fmt" "context" "os") func main() { var transport thrift.TTransport args := os.Args protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() transport, _ = thrift.NewTSocket(args[1]) transportFactory := thrift.NewTBufferedTransportFactory(8192) transport, _ = transportFactory.GetTransport(transport) //defer transport.Close() transport.Open() client := hellothrift.NewHelloServiceClientFactory(transport, protocolFactory) str, _ := client.SayHello(context.Background(), "Go-Client") fmt.Println(str) }
测试 开一个新窗口,运行下面命令:
go run Server.go
综合测试
开启两个窗口,保证server开启
go run Server.go # localhost:9092 python3 Server.py # localhost:9091
php调用go-server、py-server
php Client.php localhost:9091 php Client.php localhost:9092
python3调用go-server、py-server
python3 Client.py localhost:9091 python3 Client.py localhost:9092
go调用go-server、py-server
go run Client.go localhost:9091 go run Client.go localhost:9092
备注
没有测试php的socket,go、python3的http,可以花时间做一下
代码纯属组装,没有深刻了解其中原理,后期打算写一篇理论篇和封装类库篇
参考
https://studygolang.com/articles/1120
https://www.cnblogs.com/qufo/p/5607653.html
https://www.cnblogs.com/lovemdx/archive/2012/11/22/2782180.html
https://github.com/yuxel/thrift-examples
http://thrift.apache.org/
- 上一篇:php 判断用户是否登录
- 下一篇:什么是文件包含漏洞?手把手入门白帽子(七)
相关推荐
- js中arguments详解
-
一、简介了解arguments这个对象之前先来认识一下javascript的一些功能:其实Javascript并没有重载函数的功能,但是Arguments对象能够模拟重载。Javascrip中每个函数...
- firewall-cmd 常用命令
-
目录firewalldzone说明firewallzone内容说明firewall-cmd常用参数firewall-cmd常用命令常用命令 回到顶部firewalldzone...
- epel-release 是什么
-
EPEL-release(ExtraPackagesforEnterpriseLinux)是一个软件仓库,它为企业级Linux发行版(如CentOS、RHEL等)提供额外的软件包。以下是关于E...
- FullGC详解 什么是 JVM 的 GC
-
前言:背景:一、什么是JVM的GC?JVM(JavaVirtualMachine)。JVM是Java程序的虚拟机,是一种实现Java语言的解...
-
2024-10-26 08:50 citgpt
- 跨域(CrossOrigin)
-
1.介绍 1)跨域问题:跨域问题是在网络中,当一个网络的运行脚本(通常时JavaScript)试图访问另一个网络的资源时,如果这两个网络的端口、协议和域名不一致时就会出现跨域问题。 通俗讲...
- 微服务架构和分布式架构的区别
-
1、含义不同微服务架构:微服务架构风格是一种将一个单一应用程序开发为一组小型服务的方法,每个服务运行在自己的进程中,服务间通信采用轻量级通信机制(通常用HTTP资源API)。这些服务围绕业务能力构建并...
- 深入理解与应用CSS clip-path 属性
-
clip-pathclip-path是什么clip-path 是一个CSS属性,允许开发者创建一个剪切区域,从而决定元素的哪些部分可见,哪些部分会被隐...
-
2024-10-25 11:51 citgpt
- Request.ServerVariables 大全
-
Request.ServerVariables("Url")返回服务器地址Request.ServerVariables("Path_Info")客户端提供的路...
- python操作Kafka
-
目录一、python操作kafka1.python使用kafka生产者2.python使用kafka消费者3.使用docker中的kafka二、python操作kafka细...
- Runtime.getRuntime().exec详解
-
Runtime.getRuntime().exec详解概述Runtime.getRuntime().exec用于调用外部可执行程序或系统命令,并重定向外部程序的标准输入、标准输出和标准错误到缓冲池。...
- promise.all详解 promise.all是干什么的
-
promise.all详解promise.all中所有的请求成功了,走.then(),在.then()中能得到一个数组,数组中是每个请求resolve抛出的结果...
-
2024-10-24 16:21 citgpt
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- oracleclient (56)
- springbatch (59)
- oracle恢复数据 (56)
- 简单工厂模式 (68)
- 函数指针 (72)
- fill_parent (135)
- java配置环境变量 (140)
- linux文件系统 (56)
- 计算机操作系统教程 (60)
- 静态ip (63)
- notifyicon (55)
- 线程同步 (58)
- xcode 4 5 (60)
- 调试器 (60)
- c0000005 (63)
- html代码大全 (61)
- header utf 8 (61)
- 多线程多进程 (65)
- require_once (60)
- 百度网盘下载速度慢破解方法 (72)
- 谷歌浏览器免费入口 (72)
- npm list (64)
- 网站打开速度检测 (59)
- 网站建设流程图 (58)
- this关键字 (67)