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)
}
相关推荐
逐步前行20 分钟前
C标准库--C99--布尔型<stdbool.h>
c语言·开发语言
程序员爱钓鱼20 分钟前
Python编程实战 · 基础入门篇 | 元组(tuple)
后端·python·ipython
QX_hao20 分钟前
【Go】--闭包
开发语言·golang
程序员爱钓鱼21 分钟前
Python编程实战 · 基础入门篇 | 列表(list)
后端·python·ipython
林月明4 小时前
【VBA】自动设置excel目标列的左邻列格式
开发语言·excel·vba·格式
喜欢吃燃面4 小时前
数据结构算法题:list
开发语言·c++·学习·算法·1024程序员节
。TAT。4 小时前
C++ - 多态
开发语言·c++·学习·1024程序员节
掘金码甲哥4 小时前
两张大图一次性讲清楚k8s调度器工作原理
后端
武当豆豆4 小时前
C++编程学习(第42天)
开发语言·c++·学习
间彧5 小时前
Stream flatMap详解与应用实战
后端