本文基于Thrift-0.10,使用Python实现服务器端,使用Java实现客户端,演示了Thrift RPC调用示例。Java客户端提供两个字符串参数,Python服务器端计算这两个字符串的相似度,并返回相似度结果(double类型,范围[0, 1],0表示不相似,1表示完全相同)

一,环境安装

开发环境:Windows10,PyCharm2016,Anaconda3,Python3.6

首先安装python 的thrift包:windows打开Anaconda prompt,输入:conda install -c anaconda thrift   安装thrift包。

输入:conda list 可查看系统中已经安装了哪些包,及包的版本,如下图所示:我们安装的是:thrift-0.10.0

在写代码之前,需要先定义一个 .thrift文件,然后使用Thrift Compiler生成相应的Thrift服务需要依赖的“文件”

①定义.thrift文件

namespace py similarityservice
namespace java similarityservice service ChatSimilarityService{
double similarity(1:string chat1, 2:string chat2),
}

namespace提供了一种组织代码的方式。其实就是,生成的文件放在:similarityservice这个文件夹下。

由于前面的Python安装的thrift-0.10,因此在官网上下载:thrift-0.10.exe,将它放在与 .thrift相同的目录下,cmd切换到该目录下,执行命令:

.\thrift-0.10.0.exe --gen py chat_similarity.thrift

生成的文件如下,将它们放在合适的python包下,即可供python 服务端程序 import 了。

二,Python服务端实现

pycharm thrift插件支持

可以去pycharm插件官网下载一个thrift插件,安装好之后,编写 .thrift 文件能够自动补全提示。

服务端的实现 主要有以下五方面:(个人理解,可能有错)

①Handler

服务端业务处理逻辑。这里就是业务代码,比如 计算两个字符串 相似度

②Processor

从Thrift框架 转移到 业务处理逻辑。因此是RPC调用,客户端要把 参数发送给服务端,而这一切由Thrift封装起来了,由Processor将收到的“数据”转交给业务逻辑去处理

③Protocol

数据的序列化与反序列化。客户端提供的是“字符串”,而数据传输是一个个的字节,因此会用到序列化与反序列化。

④Transport

传输层的数据传输。

⑤TServer

服务端的类型。服务器以何种方式来处理客户端请求,比如,一次Client请求创建一个新线程呢?还是使用线程池?……可参考:阻塞通信之Socket编程

TSimpleServer —— 单线程服务器端使用标准的阻塞式 I/O

TThreadPoolServer —— 多线程服务器端使用标准的阻塞式 I/O

TNonblockingServer —— 多线程服务器端使用非阻塞式 I/O

把上面生成的thrift文件复制到 thrift_service包下,如下图:

整个python 服务端的完整代码如下:

 from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TSocket, TTransport from text.thrift_service.similarityservice import ChatSimilarityService from difflib import SequenceMatcher
from pypinyin import pinyin
import zhon
import pypinyin
from zhon.hanzi import punctuation
import re __HOST = '127.0.0.1'
__PORT = 9090 def similar_num(list1, list2):
return len(set(list1).intersection(list2)) def similar_ration(str1, str2):
return SequenceMatcher(lambda x: x == ' ', str1, str2).ratio() class SimilarityHandler(ChatSimilarityService.Iface):
def __init__(self):
self.log={}
def ping(selfs):
print('ping') def similarity(self, chat1, chat2):
#去掉中文字符串中的特殊标点符号
list1 = re.findall('[^{}]'.format(zhon.hanzi.punctuation), chat1)
list2 = re.findall('[^{}]'.format(zhon.hanzi.punctuation), chat2) #将标点符号转换成拼音
pinyin1 = pinyin(list1, style=pypinyin.STYLE_NORMAL)
pinyin2 = pinyin(list2, style=pypinyin.STYLE_NORMAL) #将所有的拼音统一保存到 单个list 中
pinyin_list1 = [word[0] for word in pinyin1]
pinyin_list2 = [word[0] for word in pinyin2] #计算 list 中元素相同的个数
result1 = similar_num(pinyin_list1, pinyin_list2) #list convert to string
str1_pinyin = ''.join(pinyin_list1)
str2_pinyin = ''.join(pinyin_list2)
#计算字符串的相似度
result2 = similar_ration(str1_pinyin, str2_pinyin) print('ratio:{}, nums:{}'.format(result2, result1))
return result2 if __name__ == '__main__':
handler = SimilarityHandler()
processor = ChatSimilarityService.Processor(handler)
transport = TSocket.TServerSocket(host=__HOST, port=__PORT)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) print('Starting the server')
server.serve()
print('done')

这里简单地介绍下实现思路:

①使用python 的 zhon 包过滤掉中文中出现的标点符号等特殊字符

②python的 pypinyin 包 将中文转换成字符串(其实也可以直接比较中文字符串的相似度,但我这里转换成了拼音,就相当于比较英文字符串了)

③使用python 的 difflib 包中的SequenceMatcher 类来计算两个字符串之间的相似度

三,Java客户端实现

①在maven工程的pom.xml中添加thrift依赖。这里的libthrift版本、windows10下载的thrift compiler版本(thrift-0.10.0.exe),还有 python的 thrift包的版本 最好保持一致。

        <!-- https://mvnrepository.com/artifact/org.apache.thrift/libthrift -->
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>

②cmd命令行执行:.\thrift-0.10.0.exe --gen java chat_similarity.thrift  生成 ChatSimilarityService.java 文件,Java 客户端代码需要依赖它。

整个Java Client的代码如下:

 import thrift.similarityservice.ChatSimilarityService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport; /**
* Created by Administrator on 2017/12/20.
*/
public class SimilarityThriftClient { public static void main(String[] args) {
try {
TTransport transport;
transport = new TSocket("127.0.0.1", 9090);
transport.open(); TProtocol protocol = new TBinaryProtocol(transport);
ChatSimilarityService.Client client = new ChatSimilarityService.Client(protocol);
perform(client);
transport.close(); } catch (TException e) {
e.printStackTrace();
}
}
private static void perform(ChatSimilarityService.Client client)throws TException {
String chat1 = "您好。";
String chat2 = "你好";
double ratio = client.similarity(chat1, chat2);
System.out.println(ratio);
}
}

四,总结

本文介绍了一个简单的 Python Server、Java Client的Thrift服务调用示例。关于Thrift可参考:

Thrift Tutorial

Apache Thrift - 可伸缩的跨语言服务开发框架

Thrift 安装及使用

原文:Python Thrift 简单示例

Python Thrift 简单示例的更多相关文章

  1. python psutil简单示例

    python psutil简单示例 利用psutil编写简单的检测小脚本 0.安装psutil模块                                                    ...

  2. Websocket - Websocket原理(握手、解密、加密)、基于Python实现简单示例

    一.Websocket原理(握手.解密.加密) WebSocket协议是基于TCP的一种新的协议.WebSocket最初在HTML5规范中被引用为TCP连接,作为基于TCP的套接字API的占位符.它实 ...

  3. thrift简单示例 (go语言)

    这个thrift的简单示例来自于官网 (http://thrift.apache.org/tutorial/go), 因为官方提供的例子简单易懂, 所以没有必要额外考虑新的例子. 关于安装的教程, 可 ...

  4. thrift简单示例 (基于C++)

    这个thrift的简单示例, 来源于官网 (http://thrift.apache.org/tutorial/cpp), 因为我觉得官网的例子已经很简单了, 所以没有写新的示例, 关于安装的教程, ...

  5. python gRPC简单示例

    Ubuntu18.04安装gRPC protobuf-compiler-grpc安装 sudo apt-get install protobuf-compiler-grpc protobuf-comp ...

  6. C#调用Python脚本的简单示例

    C#调用Python脚本的简单示例 分类:Python (2311)  (0)  举报  收藏 IronPython是一种在 .NET及 Mono上的 Python实现,由微软的 Jim Huguni ...

  7. Python自定义线程类简单示例

    Python自定义线程类简单示例 这篇文章主要介绍了Python自定义线程类,结合简单实例形式分析Python线程的定义与调用相关操作技巧,需要的朋友可以参考下.具体如下: 一. 代码     # - ...

  8. python thrift使用实例

    前言 Apache Thrift 是 Facebook 实现的一种高效的.支持多种编程语言的远程服务调用的框架.本文将从 Python开发人员角度简单介绍 Apache Thrift 的架构.开发和使 ...

  9. robot framework环境搭建和简单示例

    环境搭建 因为我的本机已经安装了python.selenium.pip等,所以还需安装以下程序 1.安装wxPythonhttp://downloads.sourceforge.net/wxpytho ...

随机推荐

  1. 扩展资源服务器解决oauth2 性能瓶颈

    OAuth用户携带token 请求资源服务器资源服务器拦截器 携带token 去认证服务器 调用tokenstore 对token 合法性校验资源服务器拿到token,默认只会含有用户名信息通过用户名 ...

  2. 【BZOJ5318】[JSOI2018]扫地机器人(动态规划)

    [BZOJ5318][JSOI2018]扫地机器人(动态规划) 题面 BZOJ 洛谷 题解 神仙题.不会.... 先考虑如果一个点走向了其下方的点,那么其右侧的点因为要被访问到,所以必定只能从其右上方 ...

  3. Entity Framework 问题集锦

    作者:疯吻IT 出处:http://fengwenit.cnblogs.com 1. No Entity Framework provider found for the ADO.NET provid ...

  4. NOI2018d1t1 归程 (dijkstra+kruskal重构树)

    题意:给一张无向联通图,每条边有长度和高度,每次询问在高度大于p的边,从v点能到达的所有点到1号点的最短距离(强制在线) 首先dijkstra求出每个点到1号点的距离 易知:如果我按高度从高到低给边排 ...

  5. A1113. Integer Set Partition

    Given a set of N (> 1) positive integers, you are supposed to partition them into two disjoint se ...

  6. canvas的api小结

    HTML <canvas id="canvas"></canvas> Javascript var canvas=document.getElementBy ...

  7. HTTP请求头和响应头的格式

    请求头: 请求头肯定带着客户端信息,比如host主机名,User-Agent用户代理信息,Cookie等等  响应头: 响应头带有服务端信息:Server服务器信息,Last-Modified最后修改 ...

  8. windows远程桌面无法粘贴复制的问题解决方法

    这两天遇到一个困扰我很久的问题,每次通过winodws远程桌面,本地的数据无法通过复制粘贴到远程服务器上.现把我找到的解决方案记录下来分享给大家 一般出现问题可能性比较大的原因就是rdpclip.ex ...

  9. FFT的一种迭代实现

    struct Complex { double x,y; Complex(double x1=0.0 ,double y1=0.0) { x=x1; y=y1; } Complex operator ...

  10. QImage与cv::Mat转换;

    QImage主要格式有QImage::Format_RGB32, QImage::Format_RGB888, QImage::Format_Index8, 不同的格式有不同的排布: 格式部分可以参考 ...