thrift 教程。windows
. 官网
https://thrift.apache.org/ 查看安装教程
. 使用
1 接口文件
HelloWorldService.thrift
namespace java com.com.sjq.thrift.demo
/**
* @TypeDoc(
* description = "测试typedoc"
* )
**/
struct TUser {
/**
* @FieldDoc(
* description = "用户主键id",
* example = {1}
* )
*/
1: i64 id;
/**
* @FieldDoc(
* description = "用户姓名",
* example = {test}
* )
*/
2: string name;
}
/**
* @TypeDoc(
* description = "HelloWorldService 项目 thrift 异常"
* )
*/
exception THelloWordServiceException {
/**
* @FieldDoc(
* description = "错误码",
* example = "0"
* )
*/
1: i32 code
/**
* @FieldDoc(
* description = "错误消息",
* example = "成功"
* )
*/
2: string message
}
/**
* @InterfaceDoc(
* displayName = "HelloWordService displayName",
* type = "octo.thrift",
* scenarios = "",
* description = ""
* )
*/
service HelloWorldTService{
/**
* @MethodDoc(
* displayName = "sayHello displayName",
* description = "sayHello description",
* parameters = {
* @ParamDoc( name = "userName", description = "用户名", example = {[1]})
* },
* returnValueDescription = "返回name和age",
* exceptions = {
* @ExceptionDoc( name = "e", description = "异常")
* }
* )
*/
string sayHello(1:string userName, 2:i32 age) throws (1:THelloWordServiceException e)
}
2 生成不同平台的代码
1 java
thrift.exe -gen java HelloWorldService.thrift
2 python
thrift.exe -gen py HelloWorldService.thrift
1 javascript
thrift.exe -gen js HelloWorldService.thrift
3 生成服务端、客户端
把第二步骤生层的代码放在工程目录下
1 java
https://github.com/sunupo/JavaStudy/tree/main/src/main/java/com/java/sjq/thrift
2 python
客户端
from thrift.Thrift import TException
from thrift.protocol import TBinaryProtocol
from thrift.transport import TSocket, TTransport
from src.HelloWorldService import HelloWorldTService
def client():
# Make socket
transport = TSocket.TSocket('localhost', 9099)
# transport = TSocket.TSocket('10.27.110.111', 9099)
# transport = TSocket.TSocket('127.0.0.1', 9099)
# Buffering is critical. Raw sockets are very slow
transport = TTransport.TFramedTransport(transport)
# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)
# Create a client to use the protocol encoder
client = HelloWorldTService.Client(protocol)
# Connect!
transport.open()
hello = client.sayHello("zhangsan", 99)
print('ping--'+hello)
# sum_ = client.add(1, 1)
if __name__ == '__main__':
try:
client()
# 捕获异常
except TException as ex:
print("%s" % (ex.message))
pass
服务端
from HelloWorldService import HelloWorldTService
from HelloWorldService.ttypes import TUser
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class MyServiceHandler:
def sayHello(self, userName, age):
data = TUser()
data.id = age
data.name = userName
return userName
if __name__ == '__main__':
handler = MyServiceHandler()
processor = HelloWorldTService.Processor(handler)
transport = TSocket.TServerSocket(host="10.27.110.111", port=9099)
# transport = TSocket.TServerSocket(host="10.27.110.111", port=9099)
tfactory = TTransport.TFramedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print("Starting the server...")
server.serve()
print("done.")
js
举例
以下是步骤:
- 安装 thrift
您需要先安装 thrift,可以通过以下命令在终端中进行安装:
npm install -g thrift
- 编写 thrift 文件
在本例中,我们假设已经有一个 thrift 文件 example.thrift
,其内容如下:
namespace js example
struct Person {
1: required string name,
2: required i32 age,
}
service PersonService {
Person getPerson(1: string name),
}
- 生成 JavaScript 客户端代码
使用以下命令生成 JavaScript 客户端代码:
thrift --gen js:node example.thrift
这将在当前目录下生成一个 gen-js
文件夹,其中包含生成的 JavaScript 代码。
- 编写客户端代码
在 gen-js
文件夹中,找到 example_types.js
和 example_constants.js
,将其复制到您的项目中。
然后,编写以下 JavaScript 代码,用于调用 thrift 服务:
const thrift = require('thrift');
const PersonService = require('./gen-js/example').PersonService;
const connection = thrift.createConnection('localhost', 9090, {
transport: thrift.TBufferedTransport,
protocol: thrift.TBinaryProtocol,
});
connection.on('error', function (err) {
console.error(err);
});
const client = thrift.createClient(PersonService, connection);
client.getPerson('Alice', function (err, response) {
if (err) {
console.error(err);
} else {
console.log(response);
}
});
- 运行客户端代码
确保 thrift 服务正在运行,并在终端中运行以下命令:
node client.js
您应该能够看到从 thrift 服务返回的响应。
以下是一个简单的JSONP示例解决跨域:
// HTML页面中的代码
<script>
function handleResponse(response) {
console.log(response);
}
const script = document.createElement('script');
script.src = 'https://example.com/api?callback=handleResponse';
document.body.appendChild(script);
</script>
// 服务器返回的数据
handleResponse({"name": "John", "age": 30});
在这个示例中,我们向服务器发送一个GET请求,请求的URL是 https://example.com/api?callback=handleResponse
。callback
参数告诉服务器我们希望用一个名为 handleResponse
的函数来处理服务器返回的数据。
服务器返回的数据是一个JSON对象,但是它被包裹在一个函数调用中,即 handleResponse({"name": "John", "age": 30})
。这样做的目的是让浏览器将返回的数据当做JavaScript代码来执行,从而让我们在页面中可以访问到这些数据。
当浏览器接收到服务器返回的数据时,它会自动调用名为 handleResponse
的函数,并将返回的数据作为参数传递给它。在这个示例中,我们在 handleResponse
函数中简单地将返回的数据输出到控制台中。