littlebot
Published on 2025-04-09 / 4 Visits
0

【源码】基于Go语言和RPCX框架的问候服务系统

项目简介

本项目是基于Go语言和RPCX框架构建的问候服务系统。借助protobuf作为通信协议,通过protoc编译器和相关插件,能将proto文件编译成Go代码,从而实现服务端和客户端的远程过程调用。项目包含简单的打招呼RPC服务示例,可展示服务端和客户端代码的构建方法。

项目的主要特性和功能

  1. 跨语言通信:采用protobuf作为通信协议,支持跨语言、跨平台的远程过程调用。
  2. 代码自动生成:利用protoc编译器和插件,可依据proto文件自动生成服务端和客户端的代码骨架。
  3. 服务端实现:提供服务端代码骨架,便于开发者实现具体业务逻辑,还能配置注册中心和其他插件。
  4. 客户端友好:客户端生成的代码包装了XClient对象,提供符合人工美学的方法调用格式,且支持服务治理设置。

安装使用步骤(假设用户已经下载了本项目的源码文件)

安装依赖

  1. 安装golang官方protoc-gen-go插件或gogo protoc-gen-gofast插件,任选其一。
  2. 编译rpcx插件。

编译proto文件

  • 若使用protobuf官方库(若未设置GOPATH,请去掉-I${GOPATH}/src或者设置GOPATH): sh protoc -I. -I${GOPATH}/src \ --go_out=. \ --rpcx_out=. --rpcx_opt=paths=source_relative helloworld.proto
  • 若使用gogo库(若未设置GOPATH,请去掉-I${GOPATH}/src或者设置GOPATH): sh protoc -I. -I${GOPATH}/src \ --gofast_out=. --gofast_opt=paths=source_relative \ --rpcx_out=. --rpcx_opt=paths=source_relative *.proto

运行服务端和客户端

  • 服务端:运行服务端代码,实现具体业务逻辑,如打招呼示例: ```go package main

import ( context "context" "fmt"

)

func main() { s := server.NewServer() s.RegisterName("Greeter", new(GreeterImpl), "") err := s.Serve("tcp", ":8972") if err!= nil { panic(err) } }

type GreeterImpl struct{}

// SayHello is server rpc method as defined func (s GreeterImpl) SayHello(ctx context.Context, args helloworld.HelloRequest, reply helloworld.HelloReply) (err error) { reply = helloworld.HelloReply{ Message: fmt.Sprintf("hello %s!", args.Name), } return nil } - **客户端**:运行客户端代码,调用服务端服务:go package main

import ( "context" "fmt"

)

func main() { xclient := helloworld.NewXClientForGreeter("127.0.0.1:8972") client := helloworld.NewGreeterClient(xclient)

args := &helloworld.HelloRequest{
    Name: "rpcx",
}

reply, err := client.SayHello(context.Background(), args)
if err!= nil {
    panic(err)
}

fmt.Println("reply: ", reply.Message)

} ```

下载地址

点击下载 【提取码: 4003】【解压密码: www.makuang.net】