Golang 实现一个简单的 RPC 服务

分享一个简单的 rpc 服务框架

一、服务端实现

Go 复制代码
package main

import (
	"log"
	"net"
	"net/rpc"
)

const HelloServiceName = "main.HelloService"

type HelloServiceInterface interface {
	Hello(request string, replay *string) error
}

func RegisterHelloService(svc HelloServiceInterface) error {
	//todo 其中 rpc.Register 函数调用会将对象类型中所有满足 RPC 规则的对象方法注册为 RPC 函数,所有注册的方法会放在 "HelloService" 服务空间之下。
	return rpc.RegisterName(HelloServiceName, svc)
}

type HelloService struct{}

//todo RPC方法需要满足的规则:只能有两个可序列化的参数,第二个参数表reply是指针类型,函数返回error类型,函数需要大写进行公开

func (p *HelloService) Hello(request string, reply *string) error {
	*reply = "hello:" + request
	return nil
}

func main() {
	//rpc.RegisterName("HelloService", new(HelloService))
	RegisterHelloService(new(HelloService))

	//todo 然后我们建立一个唯一的 TCP 连接,并且通过 rpc.ServeConn 函数在该 TCP 连接上为对方提供 RPC 服务。
	listener, err := net.Listen("tcp", ":1234")
	if err != nil {
		log.Fatal("ListenTCP error:", err)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Fatal("Accept error:", err)
		}

		//todo 启动协程去处理每个tcp请求
		go rpc.ServeConn(conn)
	}
}

二、客户端实现

Go 复制代码
package main

import (
	"fmt"
	"log"
	"net/rpc"
)

const HelloServiceName = "main.HelloService"

type HelloServiceInterface interface {
	Hello(request string, replay *string) error
}

type HelloServiceClient struct {
	*rpc.Client
}

// todo 在编译阶段检查 HelloServiceClient 类型是否实现了 HelloServiceInterface 接口。
// TODO 这里将 nil 转换为 *HelloServiceClient 类型并赋值给 _(匿名变量),编译器会自动检查 HelloServiceClient 是否实现了接口 HelloServiceInterface 中声明的所有方法。
// TODO 如果 HelloServiceClient 没有实现接口中的所有方法,这段代码会导致编译失败,从而在编码阶段就能发现潜在的问题。
var _ HelloServiceInterface = (*HelloServiceClient)(nil)

func DialHelloService(network, address string) (*HelloServiceClient, error) {
	c, err := rpc.Dial(network, address)
	if err != nil {
		return nil, err
	}

	return &HelloServiceClient{Client: c}, nil
}

func (p *HelloServiceClient) Hello(request string, reply *string) error {
	return p.Client.Call(HelloServiceName+".Hello", request, reply)
}

func main() {
	client, err := DialHelloService("tcp", "localhost:1234")

	if err != nil {
		log.Fatal("dialing:", err)
	}

	var reply string
	err = client.Hello("world", &reply)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(reply)
}
相关推荐
C++、Java和Python的菜鸟15 分钟前
第9章 后端Web进阶(AOP)
java·开发语言·前端
软萌萌的120 分钟前
Python零基础从入门到精通详细教程-数据类型
开发语言·windows·python
姓蔡小朋友29 分钟前
Java线程并发
java·开发语言·python
程序员cxuan40 分钟前
DeepSeek-V4-Flash 正式版来了!这次提升有点夸张。
人工智能·后端·程序员
我星期八休息1 小时前
扩展— TCP 全连接队列与 tcpdump 抓包
linux·服务器·开发语言·前端·网络·tcp/ip·tcpdump
小小代码狗1 小时前
PHP 常用函数与变量参考文档
开发语言·安全·php
编程阿峰2 小时前
Python 环境配置(二)安装jupyter、matplotlib、numpy库
开发语言·python·jupyter·numpy·matplotlib
磁爆步兵2 小时前
内存分区:程序运行的核心秘密
java·开发语言·jvm
此生决int2 小时前
深入理解C++系列(06)——模版初阶与STL
开发语言·c++
swany3 小时前
同步数据中,只需要几秒钟 & milvus向量数据库不可用 dify1.16.1 升级后踩坑记录
开发语言·python·numpy