什么是 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要繼續加油學習嘍!
參考