php 通过 JSON RPC 与 golang 通讯
此方法为解决php处理计算密集型需求。
go 服务
package main
import (
"fmt"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
type Calc struct{}
type Args struct {
A float64 `json:"a"`
B float64 `json:"b"`
Op string `json:"op"`
}
type Reply struct {
Msg string `json:"msg"`
Data float64 `json:"data"`
}
// 第一个是参数是获取客户端传来的数据,第二个参数是返回的数据
func (c *Calc) Compute(args Args, reply *Reply) error {
var (
msg string = "ok"
)
switch args.Op {
case "+":
reply.Data = args.A + args.B
case "-":
reply.Data = args.A - args.B
case "*":
reply.Data = args.A * args.B
case "/":
if args.B == 0 {
msg = "in divide op, B can't be zero"
} else {
reply.Data = args.A / args.B
}
default:
msg = fmt.Sprintf("unsupported op:%s", args.Op)
}
reply.Msg = msg
if reply.Msg == "ok" {
return nil
}
return fmt.Errorf(msg)
}
// 启动server端
func main() {
err := rpc.Register(new(Calc))
if err != nil {
panic(err)
}
listener, err := net.Listen("tcp", "0.0.0.0:8181")
if err != nil {
panic(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
continue
}
go jsonrpc.ServeConn(conn)
}
}
php 客户端
public function Call($method, $params) {
$this->conn = fsockopen('127.0.0.1', 8181, $errno, $errstr, 3);
if (!$this->conn) {
return false;
}
$err = fwrite($this->conn, json_encode(array(
'method' => $method,
'params' => array($params),
'id' => 12345,
))."\n");
if ($err === false)
return false;
stream_set_timeout($this->conn, 0, 3000);
$line = fgets($this->conn);
if ($line === false) {
return NULL;
}
return json_decode($line,true);
}
public function Test() {
//访问结构体 Calc 下 Compute 方法
$res = $this->Call("Calc.Compute",array('A'=>1,'B'=>2,'Op'=>'+'));
return $res;
}
返回结果
{
"id": 12345,
"result": {
"msg": "ok",
"data": 3
},
"error": null
}
转载的,欢迎留言交流~
PHP pfsockopen 网络函数
一文搞懂RPC,So Easy
原文链接:blog.csdn.net/weixin_41112414/arti...
本作品采用《CC 协议》,转载必须注明作者和本文链接
有一个更加完善的php 客户端包,名字忘了,在laravel news上
:+1: :+1:
:+1: :+1:
:+1: :+1:
我写过一个多路复用的,可以试试
github.com/hyperf/roc
:+1: :+1: