go get github.com/golang/protobuf/protoc-gen-go
go get github.com/golang/protobuf/proto
- proto
syntax="proto3";
package prod;
message ProdRequest{
int32 prod_id=1; // 商品id
}
message ProdResponse{
int32 prod_stock=1; // 商品库存
}
命令protoc --go_out=. prodService.proto
生成go文件
- rpc server
package main
import (
"net"
"net/rpc"
"net/rpc/jsonrpc"
prod "think/pb"
)
type ProdService struct {
}
// GetStock 获取库存
// 随便模拟一下商品库存
func (s *ProdService) GetStock(req prod.ProdRequest,res *prod.ProdResponse) error{
if req.ProdId==1 {
res.ProdStock=10
}else {
res.ProdStock=0
}
return nil
}
func main() {
listener, _:=net.Listen("tcp",":30000")
rpc.Register(new(ProdService))
for {
conn,_:=listener.Accept()
jsonrpc.ServeConn(conn)
}
}
- rpc client
package main
import (
"fmt"
"net/rpc/jsonrpc"
prod "think/pb"
)
func main() {
client,err :=jsonrpc.Dial("tcp","127.0.0.1:30000")
if err!=nil {
fmt.Println(err)
return
}
res:=prod.ProdResponse{}
err=client.Call("ProdService.GetStock",prod.ProdRequest{ProdId:10},&res)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res.ProdStock)
}
- php调用
$fp = stream_socket_client('tcp://127.0.0.1:30000',$errno,$msg,3);
if (!$fp) {
echo "$msg ($errno)<br>\n";
return;
}
fwrite($fp, json_encode([
'method' => 'ProdService.GetStock',
'params' => [['prod_id' => 1]],
'id' => 0
])."\n");
echo fgets($fp);
fclose($fp);
返回
{"id":0,"result":{"prod_stock":5},"error":null}
有疑问加站长微信联系(非本文作者)