RPC(一):thrift 框架 go语言开发

1、写 thrift 文件定义好 service :方法、入参出参
2、生成 代码并发包
3、编写 server 端实现
4、本地启动server端,进行测试
5、打包启动 rpc 服务

具体实现:
1、写 thrift 文件定义好 service 以及 入参出参的 struct
namespace 定义生成的文件目录和名称。

namespace py test_thrift.action_card
namespace go test_thrift.action_card
namespace java test_thrift.action_card

enum ResouceCode {
    ALPHA = 1,
    BETA = 2
}

序号:类型 名称
struct BannerParams {
    1: i64 member_id;
    2: i32 num;
}

service MemberService {
    Banner get_banner(1: BannerParams params)
}

生成 py 或者 go 代码,并发布镜像
gen:
thrift -r –gen go:package_prefix=github.com/serenity/gen-go/ ./thrift_files/test/test.thrift

2、编写 server 端实现

package service

import (
   "github.com/serenity/gen-go/test_thrift/member"
   "github.com/serenity/golang/pkg/action_card/controller"
   "github.com/serenity/golang/pkg/common/model"
)

func GetMemberServiceProcessor(msgChan chan model.Message) *member.MemberServiceProcessor {
   // service - api
   memberService := controller.NewMemberService()

   // processor
   return member.NewMemberServiceProcessor(memberService)
}

3、客户端调用测试

var memberClient = member_service.NewMemberServiceClient(tc.New("MemberService", tc.Timeout(500*time.Millisecond), tc.TargetName("member")))
params := memberClient.BannerParams{0,0}
banner := memberClient.GetBanner(params)
fmt.Println(banner)

4、打包启动 rpc 服务

servicesMap := map[string]thrift.TProcessor{
   "MemberService":        memberService.GetMemberServiceProcessor(),
}
server.New(
   servicesMap,
   server.SentryDSN(conf.EnvConfig.SentryDSN),
   server.Tracing(conf.EnvConfig.ChoosedClusterAddrs),
   server.Slowlog(500*time.Millisecond),
).Run("0.0.0.0:10000")

5、git 上线

    原文作者:yinanserenity
    原文地址: https://segmentfault.com/a/1190000019570527
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞