- 使用Composer安装Thrift扩展后,把go的扩展包拷贝到GOPATH中(或建立软连接)。
ln -s /your/path/to/thrift-go-phalcon-project/vendor/apache/thrift/lib/go/thrift thrift
- 编译Go服务 使用 thrift -r --gen go:thrift_import=thrift App.thrift
- 编译Php服务 使用 thrift -r --gen php:server,psr4 App.thrift
- Go thrift/gen-go/main.go
# RPC服务注册方法
server.RegisterProcessor("app", service.NewAppProcessor(&impl.App{}));
- Swoole app/tasks/Thrift/Service.php
$handler = new AppHandler();
$processor->registerProcessor('app', new AppProcessor($handler));
- Swoole app/thrift/Services/AppHandle.php
<?php
namespace App\Thrift\Services;
use MicroService\AppIf;
class AppHandler extends Handler implements AppIf
{
public function version()
{
return $this->config->version;
}
}
配合注册中心一起使用 app/tasks/Thrift/ServiceTask.php
protected function beforeServerStart(swoole_server $server)
{
parent::beforeServerStart($server); // TODO: Change the autogenerated stub
// 增加服务注册心跳进程
$worker = new swoole_process(function (swoole_process $worker) {
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect(env('REGISTRY_IP'), env('REGISTRY_PORT'), -1)) {
exit("connect failed. Error: {$client->errCode}\n");
}
swoole_timer_tick(5000, function () use ($client) {
$service = env('REGISTRY_SERVICE', 'github');
$data = [
'service' => $service,
'ip' => env('SERVICE_IP'),
'port' => env('SERVICE_PORT'),
'nonce' => time(),
'register' => true,
'sign' => 'xxx',
];
$client->send(json_encode($data));
$result = $client->recv();
$result = json_decode($result, true);
if ($result['success']) {
foreach ($result['services'] as $key => $item) {
Redis::hset($service, $key, json_encode($item));
}
}
});
});
$server->addProcess($worker);
}
- 基本类型(括号内为对应的Java类型):
bool(boolean): 布尔类型(TRUE or FALSE)
byte(byte): 8位带符号整数
i16(short): 16位带符号整数
i32(int): 32位带符号整数
i64(long): 64位带符号整数
double(double): 64位浮点数
string(String): 采用UTF-8编码的字符串
- 特殊类型(括号内为对应的Java类型)
binary(ByteBuffer):未经过编码的字节流
- Structs(结构):
struct UserProfile {
1: i32 uid,
2: string name,
3: string blurb
}
struct UserProfile {
1: i32 uid = 1,
2: string name = "User1",
3: string blurb
}
- 容器,除了上面提到的基本数据类型,Thrift还支持以下容器类型:
list(java.util.ArrayList) set(java.util.HashSet) map(java.util.HashMap)
struct Node {
1: i32 id,
2: string name,
3: list<i32> subNodeList,
4: map<i32,string> subNodeMap,
5: set<i32> subNodeSet
}
struct SubNode {
1: i32 uid,
2: string name,
3: i32 pid
}
struct Node {
1: i32 uid,
2: string name,
3: list<subNode> subNodes
}
- 服务
service UserStorage {
void store(1: UserProfile user),
UserProfile retrieve(1: i32 uid)
}