Thrift_02——实践:搭建Golang、PHP间的远程服务调用RPC

一、简述

下面我将通过thrift框架实现以Golang为服务端,PHP为客户端的RPC调用,实现的功能为:
GetSumAndTime–即实现对指定整型入参a、b完成求和操作并返回其运算的开始计算的、计算结束的毫秒级时间戳。

二、实现步骤

1、安装thrift工具包,见Thrift_01——简介:远程过程调用协议

2、构建IDL数据定义文件(.thrift),使用thrift工具生成Golang和PHP的接口代码
(1)编写calSum.thrift:


struct Result{
    1:i64 beginTime;
    2:i64 endTime;
    3:i32 result;
}

service GetSumAndTime{

   Result DoGetSumAndTime(1:i32 arg1 , 2:i32 arg2);

}

(2)使用thrift的命令构建Golang 的thrift接口代码:

thrift -r --gen go calSum.thrift

生成了gen-go的目录:
Thrift_02——实践:搭建Golang、PHP间的远程服务调用RPC_第1张图片
3、使用Golang构建RPC服务端侧服务程序:
(1)获取go的thrift依赖(使用go get):

go get git.apache.org/thrift.git/lib/go/thrift

(2)编写代码:

package main

import (
	"context"
	"fmt"
	"for_test_project/thrift_test/src/calsum"
	"github.com/apache/thrift/lib/go/thrift"
	"time"

	"net"
	"os"
)

//定义对象并实现calSum.go中的GetSumAndTime接口
type MyHandler struct{}

func (m MyHandler) DoGetSumAndTime(ctx context.Context, arg1 int32, arg2 int32) (r *calsum.Result_, err error) {

	fmt.Println("got data from client :", arg1, arg2)
	sum := arg1 + arg2
	beginTime := time.Now().UnixNano() / 1e6
	endTime := time.Now().UnixNano() / 1e6

	res := calsum.Result_{
		BeginTime: beginTime,
		EndTime:   endTime,
		Result_:   sum,
	}

	return &res, nil
}

func main() {
	// 创建服务器
	serverTransport, err := thrift.NewTServerSocket(net.JoinHostPort("127.0.0.1", "9090"))
	if err != nil {
		fmt.Println("Error!", err)
		os.Exit(1)
	}

	// 创建二进制协议
	protocolFactory := thrift.NewTCompactProtocolFactory() //thrift.NewTBinaryProtocolFactoryDefault()
	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())

	// 创建Processor,用一个端口处理多个服务
	multiProcessor := thrift.NewTMultiplexedProcessor()
	sumProcessor := calsum.NewGetSumAndTimeProcessor(MyHandler{})

	// 给每个service起一个名字
	multiProcessor.RegisterProcessor("getSum", sumProcessor)

	server := thrift.NewTSimpleServer4(multiProcessor, serverTransport, transportFactory, protocolFactory)

	fmt.Println("start")
	if err := server.Serve(); err != nil {
		panic(err)
	}

	// 退出时停止服务器
	defer server.Stop()
}

4、编写PHP客户端的测试程序
(1)编写composer.json文件:

{
  "require": {
    "apache/thrift": "*"
  }
}

(2)使用composer install命令(composer是php的包管理,可以自行百度,这里不再赘述)获取php的thrift依赖文件
注意!一定要使用install命令,才能获得autoload.php文件,后面会用到这个文件

(3)使用thrift命令利用开始的thrift文件获取php 的接口代码:

thrift -r --gen php calSum.thrift

(4)编写PHP的代码:



error_reporting(E_ALL);

require_once __DIR__ . '/vendor/autoload.php';

use Thrift\ClassLoader\ThriftClassLoader;

$GEN_DIR = realpath(dirname(__FILE__)) . '/../gen-php';

$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift', __DIR__ . '/../../lib/php/lib');
$loader->registerNamespace('shared', $GEN_DIR);
$loader->registerNamespace('tutorial', $GEN_DIR);
$loader->register();

use Thrift\Protocol\TBinaryProtocol;
use Thrift\Protocol\TMultiplexedProtocol;
use Thrift\Transport\TSocket;
use Thrift\Transport\TFramedTransport;
use Thrift\Exception\TException;

include "gen-php/GetSumAndTimeClient.php";
include "gen-php/Result.php";


try {
    $socket = new TSocket('127.0.0.1', 9090);
    $transport = new TFramedTransport($socket);
    $protocol = new \Thrift\Protocol\TCompactProtocol($transport);
    $loginProtocol = new TMultiplexedProtocol($protocol, 'getSum');
    $sumService = new GetSumAndTimeClient($loginProtocol);
    $transport->open();
    $result = $sumService->DoGetSumAndTime(11, 299);
    var_dump($result);
    echo '
'
; $transport->close(); } catch (TException $tx) { print 'Exception: ' . $tx->getCode() . ' message:' . $tx->getMessage() . "\n"; }

【待续】
因为我初学PHP,对包引用不太熟,所以我将thrift 生成的几个文件的代码均放在了一个主文件中,因为总会提示引用问题。

最后的实现效果:

object(Result)#10 (3) {
  ["beginTime"]=>
  int(1594523277030)
  ["endTime"]=>
  int(1594523277030)
  ["result"]=>
  int(310)
}
<br/>
Process finished with exit code 0

你可能感兴趣的:(PHP,服务端,微服务)