go学习 - rpc & grpc
1.rpc介绍
package example
import (
"fmt"
"log"
"net"
"net/rpc"
)
type Greeter struct {
}
func (self *Greeter) Greet(request string, response *string) error {
*response = "Hello: " + request
return nil
}
func Server() {
rpc.RegisterName("Greeter", new(Greeter))
listener, err := net.Listen("tcp", "0.0.0.0:30001")
fmt.Println("Server is running at localhost:30001...")
if err != nil {
log.Fatal("ListenTCP error:", err)
}
conn, err := listener.Accept()
if err != nil {
log.Fatal("Accept error", err)
}
rpc.ServeConn(conn)
}
func Client() {
client, err := rpc.Dial("tcp", "localhost:30001")
if err != nil {
log.Fatal("dialing: ", err)
}
var response string
//不难看出,此处为rpc调用
err = client.Call("Greeter.Greet", "magic", &response)
if err != nil {
log.Fatal(err)
}
fmt.Println(response)
}
2.grpc
gRPC是Google开源的通用高性能的RPC框架,支持使用Protocol Buffers 来编写Service定义,支持较多语言扩平台且拥有强大的二进制序列化框架;
Apache Thrift则为另一种通用的rpc框架