How to implement RPC interface using Go

PHPz
Release: 2023-06-05 10:01:48
Original
1761 people have browsed it

In recent years, with the rapid development of Internet technology and the rise of cloud computing, remote procedure call (RPC) has attracted more and more attention from developers. The Go language itself is lightweight, and with rich library and framework support, RPC services can be easily implemented. In this article, we will introduce how to implement RPC interfaces using Go.

1. Overview of RPC

RPC (Remote Procedure Call) is a protocol that allows different processes or computers to communicate with each other to call other processes or computers. A function or method on the machine. The basic principle of RPC is to encapsulate the call of a function or method into a network communication process, so that the consumer (caller) can call services on the remote machine like a local call.

Currently, common RPC frameworks include gRPC, Thrift, Dubbo, etc. Among them, gRPC is a high-performance RPC framework based on HTTP/2 open sourced by Google and supports multiple programming languages, including C, Java, Python, Go, etc. gRPC uses Protocol Buffers as the serialization protocol, which can be used to build high-performance, scalable distributed applications such as distributed systems and microservices.

2. Use Go to implement the RPC interface

  1. Installation and download dependencies

Before using Go to implement the RPC interface, we need to install Go first Development environment and RPC framework support. Here we choose to use the gRPC framework.

First, we need to install gRPC's Go language plug-in and protobuf tool:

$ go get -u google.golang.org/grpc
$ go get -u github.com/golang/protobuf/protoc-gen-go
Copy after login

After the installation is complete, we can use protobuf2.0 or above to write a .proto file to describe the service and message structure. For example, we write a simple .proto file:

syntax = "proto3";

package helloworld;

// 定义 HelloService
service HelloService {
  // 定义 SayHello 方法
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

// 定义入参结构体: HelloRequest
message HelloRequest {
  string name = 1;
}

// 定义出参结构体: HelloResponse
message HelloResponse {
  string message = 1;
}
Copy after login
  1. Generate code

We can use the following command to generate Go code based on the .proto file:

$ protoc --go_out=plugins=grpc:. *.proto
Copy after login

After executing the above command, we can get the corresponding Go code file, for example:

syntax = "proto3";

package helloworld;

// 定义 HelloService
service HelloService {
  // 定义 SayHello 方法
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

// 定义入参结构体: HelloRequest
message HelloRequest {
  string name = 1;
}

// 定义出参结构体: HelloResponse
message HelloResponse {
  string message = 1;
}
Copy after login
  1. Implementing the server

Next, we need to implement a service end. First, we need to define a HelloServiceImpl structure to implement the above HelloService interface:

package main

import (
  "context"
  pb "github.com/user/helloworld"
)

type HelloServiceImpl struct {
}

func (s *HelloServiceImpl) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
  return &pb.HelloResponse{Message: "Hello, " + req.Name + "!"}, nil
}
Copy after login

In the above code, we define a HelloServiceImpl structure and implement the SayHello method in the HelloService interface. This method receives a context object and HelloRequest object as parameters, and returns a HelloResponse object as the result. Among them, ctx is the context object used to control the request process. req is a HelloRequest object, containing the request parameters when calling the SayHello method.

Next, we need to create a gRPC server and register the HelloServiceImpl object to the server:

package main

import (
  "log"
  "net"
  pb "github.com/user/helloworld"
  "google.golang.org/grpc"
)

func main() {
  listenPort, err := net.Listen("tcp", ":4300")
  if err != nil {
    log.Fatalf("failed to listen: %v", err)
  }

  grpcServer := grpc.NewServer()

  // 注册服务实现
  pb.RegisterHelloServiceServer(grpcServer, &HelloServiceImpl{})

  // 启动服务
  if err := grpcServer.Serve(listenPort); err != nil {
    log.Fatalf("failed to serve: %v", err)
  }
}
Copy after login

In the above code, we first define a listening port, and then create a gRPC server And register the HelloServiceImpl object to the server. Finally, we start the gRPC service and listen for HTTP2 requests.

  1. Implementing the client

Now that we have implemented a gRPC server, we need to implement a gRPC client. In Go, we can access the gRPC server by calling the corresponding client method. For example, we can create a client file named main and implement the following code:

package main

import (
  "context"
  "log"
  "os"
  "time"

  pb "github.com/user/helloworld"
  "google.golang.org/grpc"
)

func main() {
  // 连接服务器
  conn, err := grpc.Dial(":4300", grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  if err != nil {
    log.Fatalf("Failed to connect: %v", err)
  }
  defer conn.Close()

  // 创建客户端
  c := pb.NewHelloServiceClient(conn)

  // 组装请求参数
  name := "go grpc"
  req := &pb.HelloRequest{Name: name}

  // 调用 SayHello 方法
  resp, err := c.SayHello(context.Background(), req)
  if err != nil {
    log.Fatalf("[ERROR] SayHello err: %v
", err)
    os.Exit(1)
  }
  log.Printf("[INFO] SayHello resp: %s
", resp.Message)
}
Copy after login

In the above code, we first create a gRPC connection and connect to the server, then create a HelloServiceClient object, and Assemble request parameters. Finally, we call the SayHello method and output the response. After the above code is executed, we can see the output result:

INFO: SayHello resp: "Hello, go grpc!"
Copy after login
  1. Run the service

Finally, we need to compile the server and client codes, and then Start the service. You can follow the following steps:

$ cd $GOPATH/src/github.com/user/helloworld
$ go run serve/main.go  // 启动gRPC服务端
$ go run client/main.go  // 启动gRPC客户端
Copy after login

If everything is normal, we can see the client output: "Hello, go grpc!".

3. Summary

In this article, we introduced how to use Go to implement the RPC interface. Among them, we used the classic gRPC framework and implemented a simple Hello World example. It is worth mentioning that in addition to gRPC, Go also has many other RPC frameworks, including Thrift, Dubbo and JSON-RPC, etc., and developers can flexibly choose according to actual needs.

When using the RPC framework, we need to choose the appropriate serialization protocol and transmission protocol based on actual needs. Normally, we recommend using Protocol Buffers and the HTTP/2 protocol to implement efficient RPC calls to meet the needs of large-scale distributed systems.

The above is the detailed content of How to implement RPC interface using Go. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!