什么是 RPC 框架?
什么是 Goridge?
- 操作系统:Linux
- PHP版本:php7.2
- Golang版本:1.10
- PHP框架:TP5(直接composer加载就可以使用了)
1、spiral/goridge 需要环境开启openssl,否则会出现以下错误
composer require spiral/goridge [Composer\Exception\NoSslException]
The openssl extension is required for SSL/TLS protection but is not available. If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the 'disable-tls' option to true.
2、TP5框架直接使用composer安装,以下表示安装成功
composer require spiral/goridge
Using version ^2.0 for spiral/goridge
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Installing spiral/goridge (v2.0.3): Downloading (100%)
Package tecnick.com/tcpdf is abandoned, you should avoid using it. Use tecnickcom/tcpdf instead.
Writing lock file
Generating autoload files
3、Golang 直接安装,使用以下命令
go get "github.com/spiral/goridge"
注意:以上安装必须配置好GOPATH环境变量。
4、在src目录新建文件夹test,编写 rpc-test.go 文件,内容如下所示
package main import (
"fmt"
"github.com/spiral/goridge"
"net"
"net/rpc"
) type App struct{} func (s *App) Hi(name string, r *string) error {
*r = fmt.Sprintf("Hello, %s!", name)
return nil
} func main() {
ln, err := net.Listen("tcp", ":6001")
if err != nil {
panic(err)
} rpc.Register(new(App)) for {
conn, err := ln.Accept()
if err != nil {
continue
}
go rpc.ServeCodec(goridge.NewCodec(conn))
}
}
5、Golang最终为文件结构目录
├── bin
│ ├── bee
│ └── webcodec
├── pkg
│ └── linux_amd64
│ └── github.com
└── src
├── github.com
│ ├── astaxie
│ ├── beego
│ ├── spiral
│ └── Tinywan
└── test
├── prc-test.go
└── server.go
6、进入test项目目录,运行prc-test.go
go run prc-test.go
注意:这里一直是等待状态,暂时没有任何输出
7、编写php服务端,在TP5中新建一个控制器GolangController以及一个test方法,文件内容如下所示:
class GoLangController
{
public function test(){
$rpc1 = new Goridge\RPC(new Goridge\SocketRelay("127.0.0.1", 6001));
echo $rpc1->call("App.Hi", "Tinywan RPC");
}
}
8、通过浏览器访问测试结果如下所示
9、总结
Golang是直接使用官方RPC库: net/rpc,golang的rpc支持三个级别的RPC:TCP、HTTP、JSONRPC。但Go的RPC包是独一无二的RPC,它和传统的RPC系统不同,它只支持Go开发的服务器与客户端之间的交互,因为在内部,它们采用了Gob来编码。
PHP客户端是如何条用golang中的action的,我们首先在PHP端实例化一个socket链接(TCP通信),当然了这个类是第三方已经封装好了,在这里使用new 一个实例就可以了。
该实例直接调用一个Golang脚本中的 APP.Hi方法(APP结构体这里你可以认为是一个类即可),Hi就是类下面的一个方法喽。这也就达到了RPC的要求(一个应用部署在A服务器上,想要调用B服务器上应用提供的函数/方法,由于不在一个内存空间,不能直接调用,需要通过网络来表达调用的语义和传达调用的数据。)。在这里我们是直接使用PHP调用到Golang中的方法。O(∩_∩)O哈哈~~
所以嘛!Golang要继续加油学习喽!
参考