Preface
Solve the problem: understand what is rpc?? Write rpc with code...
One, what is rpc
Remote Procedure Call (Remote Procedure Call, abbreviated as RPC) is a computer communication protocol. This protocol allows programs running on one computer to call subroutines of another computer without the programmer needing to program this interaction. If the software involved uses object-oriented programming, then remote procedure call can also be called remote call or remote method call.
Simple Application Server
USD1.00 New User Coupon
* Only 3,000 coupons available.
* Each new user can only get one coupon(except users from distributors).
* The coupon is valid for 30 days from the date of receipt.
RPC is a technical idea rather than a specification or protocol
Common RPC technologies and frameworks are:
Application-level service framework: Ali's Dubbo/Dubbox, Google gRPC, Spring Boot/Spring Cloud.
Remote communication protocol: RMI, Socket, SOAP (HTTP XML), REST (HTTP JSON).
Communication framework: MINA and Netty
rpc process
2. Implementation of rpc (native)
1.
Server (single parameter version, if you need to use multiple parameters, you can directly replace the req and resp types)
All codes
package main
import (
"math"
"net"
"net/http"
"net/rpc"
)
type MathUtil struct {
}
//req is a function parameter, resp is the return value
func (mu *MathUtil) CalculateCircleArea(req float32,resp *float32) error{
*resp=math.Pi*req*req
return nil
}
func main(){
mathUtil:=new(MathUtil)
//Registration Service
err:=rpc.Register(mathUtil);if err!=nil{
panic(err.Error())
}
rpc.HandleHTTP()
//Create service, port number 8001
listen,err:=net.Listen("tcp",":8001");if err!=nil{
panic(err.Error())
}
http.Serve(listen,nil)
}
2. Client
Synchronous call
err=client.Call("MathUtil.CalculateCircleArea",req,&resp);if err!=nil{
panic(err.Error())
}
Asynchronous call
var respSync *float32
syncCall:=client.Go("MathUtil.CalculateCircleArea",req,&respSync,nil)
replayDone:=<-syncCall.Done
fmt.Println(replayDone)
fmt.Println(*respSync)
All codes
package main
import (
"fmt"
"net/rpc"
)
func main(){
//Define the incoming value and return value
var req float32
//Connect to the server
client,err:=rpc.DialHTTP("tcp","localhost:8001");if err!=nil{
panic(err.Error())
}
req=6.15
//Call remote service
//Asynchronous
var respSync *float32
syncCall:=client.Go("MathUtil.CalculateCircleArea",req,&respSync,nil)
replayDone:=<-syncCall.Done
fmt.Println(replayDone)
fmt.Println(*respSync)
To
//Synchronize
//var resp *float32
//err=client.Call("MathUtil.CalculateCircleArea",req,&resp);if err!=nil{
// panic(err.Error())
//}
//fmt.Println(*resp)
}