使用 GoFrame2搭建 jsonrpc2 解决 php + go jsonrpc 通讯问题

使用 GoFrame2实现 jsonrpc2 解决 php 与 go 的服务互相访问

前言 重构公司项目选择了 php 的 hyperf 框架,golang 的 GoFrame (gf女朋友) 框架,开发模式也由曾经的单体架构迁移到微服务模式,hyperf 集成了 jsonrpc 但和 goalng 官方库的 rpc 库不太兼容,所以才有了自己基于理解进行封装的 jsonrpc2服务出来支持 http 与 tpc 两种协议,项目已经上传到 github 欢迎一块交流

服务端
// 服务结构体
type IntRpc struct{}
// 参数
type Params struct {
   A int `json:"a"`
  B int `json:"b"`
}

type Result = g.Map // 返回结果

// 服务下的方法
func (i *IntRpc) Add(params *Params, result *Result) error {
   a := response.Success(g.Map{"value": params.A * params.B}, "请求成功")

   *result = interface{}(a).(Result)
   return nil
}

s, _ := jsonrpc.NewServer("http", "127.0.0.1", "8101") 建立连接
s.Register(new(IntRpc)) // 注册服务
s.Start() // 启动服务
客户端
c, _ := jsonrpc.NewClient("tcp", "127.0.0.1", "8101")
param := Params{2, 5}
result := new(Result) // 服务返回结果
err := c.Call("intRpc/add", &param, result, false) // 方法支持大驼峰,小驼峰,下划线
if err != nil {
return
}
g.Dump(*result)

欢迎大家一块交流

本作品采用《CC 协议》,转载必须注明作者和本文链接
994914376
讨论数量: 1

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!