Categorygithub.com/hslam/rpc
modulepackage
0.0.4
Repository: https://github.com/hslam/rpc.git
Documentation: pkg.go.dev

# README

rpc

PkgGoDev Build Status codecov Go Report Card LICENSE

Package rpc implements a remote procedure call over TCP, UNIX, HTTP and WS. The rpc improves throughput and reduces latency. Up to 4 times faster than net/rpc.

Feature

  • More throughput and less latency.
  • Netpoll epoll/kqueue/net
  • Network tcp/unix/http/ws
  • Codec json/code/pb
  • Multiplexing/Pipelining
  • Auto batching
  • Call/Go/RoundTrip/Ping/Watch/CallWithContext
  • Server push
  • Conn/Transport/Client
  • TLS

Comparison to other packages

Packagenetrpcjsonrpcrpcgrpcrpcx
Epoll/KqueueNoNoYesNoNo
MultiplexingYesYesYesYesYes
PipeliningNoNoYesNoNo
Auto BatchingNoNoYesNoNo
TransportNoNoYesNoNo
Server PushNoNoYesYesYes

Benchmark

Low Concurrency

rpcrpc

High Concurrency

rpcrpc

Get started

Install

go get github.com/hslam/rpc

Import

import "github.com/hslam/rpc"

Usage

Examples

arith.proto

syntax = "proto3";
package service;

message ArithRequest {
    int32 a = 1;
    int32 b = 2;
}

message ArithResponse {
    int32 pro = 1;
}

GoGo Protobuf

protoc ./arith.proto --gogofaster_out=./

arith.go

package service

type Arith struct{}

func (a *Arith) Multiply(req *ArithRequest, res *ArithResponse) error {
	res.Pro = req.A * req.B
	return nil
}

server.go

package main

import (
	"github.com/hslam/rpc"
	"github.com/hslam/rpc/examples/codec/pb/service"
)

func main() {
	rpc.Register(new(service.Arith))
	rpc.Listen("tcp", ":9999", "pb")
}

conn.go

package main

import (
	"fmt"
	"github.com/hslam/rpc"
	"github.com/hslam/rpc/examples/codec/pb/service"
)

func main() {
	conn, err := rpc.Dial("tcp", ":9999", "pb")
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	req := &service.ArithRequest{A: 9, B: 2}
	var res service.ArithResponse
	if err = conn.Call("Arith.Multiply", req, &res); err != nil {
		panic(err)
	}
	fmt.Printf("%d * %d = %d\n", req.A, req.B, res.Pro)
}

transport.go

package main

import (
	"fmt"
	"github.com/hslam/rpc"
	"github.com/hslam/rpc/examples/codec/pb/service"
)

func main() {
	trans := &rpc.Transport{
		MaxConnsPerHost:     1,
		MaxIdleConnsPerHost: 1,
		Options:             &rpc.Options{Network: "tcp", Codec: "pb"},
	}
	defer trans.Close()
	req := &service.ArithRequest{A: 9, B: 2}
	var res service.ArithResponse
	if err := trans.Call(":9999", "Arith.Multiply", req, &res); err != nil {
		panic(err)
	}
	fmt.Printf("%d * %d = %d\n", req.A, req.B, res.Pro)
}

client.go

package main

import (
	"fmt"
	"github.com/hslam/rpc"
	"github.com/hslam/rpc/examples/codec/pb/service"
)

func main() {
	opts := &rpc.Options{Network: "tcp", Codec: "pb"}
	client := rpc.NewClient(opts, ":9997", ":9998", ":9999")
	client.Scheduling = rpc.LeastTimeScheduling
	defer client.Close()
	req := &service.ArithRequest{A: 9, B: 2}
	var res service.ArithResponse
	if err := client.Call("Arith.Multiply", req, &res); err != nil {
		panic(err)
	}
	fmt.Printf("%d * %d = %d\n", req.A, req.B, res.Pro)
}

context.go

package main

import (
	"context"
	"fmt"
	"github.com/hslam/rpc"
	"github.com/hslam/rpc/examples/codec/pb/service"
	"time"
)

func main() {
	conn, err := rpc.Dial("tcp", ":9999", "pb")
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	req := &service.ArithRequest{A: 9, B: 2}
	var res service.ArithResponse
	emptyCtx := context.Background()
	valueCtx := context.WithValue(emptyCtx, rpc.BufferContextKey, make([]byte, 64))
	ctx, cancel := context.WithTimeout(valueCtx, time.Minute)
	defer cancel()
	err = conn.CallWithContext(ctx, "Arith.Multiply", req, &res)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%d * %d = %d\n", req.A, req.B, res.Pro)
}

Output

9 * 2 = 18

License

This package is licensed under a MIT license (Copyright (c) 2019 Meng Huang)

Author

rpc was written by Meng Huang.

# Packages

No description provided by the author
No description provided by the author

# Functions

DefaultEncoder returns a default header Encoder.
DefaultOptions returns a default options.
Dial connects to an RPC server at the specified network address.
DialTLS connects to an RPC server at the specified network address with tls.Config.
DialWithOptions connects to an RPC server at the specified network address with Options.
FreeContextBuffer frees the context buffer to the pool.
GetBuffer gets a buffer from the pool.
GetCall gets a call from the callPool.
GetContextBuffer gets a buffer from the context.
GetLogLevel returns log's level.
Listen announces on the local network address.
ListenTLS announces on the local network address with tls.Config.
ListenWithOptions announces on the local network address with Options.
NewClient returns a new RPC Client.
NewClientCodec returns a new ClientCodec.
NewCodec returns a new Codec.
NewCODECodec returns the instance of Codec.
NewCODEEncoder returns a header Encoder.
NewCODERequest returns the instance of codeRequest.
NewCODEResponse returns the instance of codeResponse.
NewConn returns a new Conn to handle requests to the set of services at the other end of the connection.
NewConnWithCodec is like NewConn but uses the specified codec to encode requests and decode responses.
NewEncoder returns the instance of Encoder.
NewHeaderEncoder returns a new header Encoder.
NewJSONCodec returns the instance of Codec.
NewJSONEncoder returns a header Encoder.
NewJSONRequest returns the instance of jsonRequest.
NewJSONResponse returns the instance of jsonResponse.
NewPBCodec returns the instance of Codec.
NewPBEncoder returns a header Encoder.
NewPBRequest returns the instance of pbRequest.
NewPBResponse returns the instance of pbResponse.
NewServer returns a new Server.
NewServerCodec returns a new ServerCodec.
NewSocket returns a new Socket by network.
Push triggers the waiting clients with the watch key value.
PushFunc sets a WatchFunc.
PutBuffer puts a buffer to the pool.
PutCall puts a call to the callPool.
Register publishes the receiver's methods in the DefaultServer.
RegisterCodec registers a codec.
RegisterHeaderEncoder registers a header Encoder.
RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.
RegisterSocket registers a network socket.
ResetDone resets the done.
ServeCodec uses the specified codec to decode requests and encode responses.
Services returns registered services.
SetBufferSize sets buffer size.
SetContextBuffer sets shared buffer.
SetLogLevel sets log's level.
SetNoBatch disables the Server to use batch writer.
SetNoCopy reuses a buffer from the pool for minimizing memory allocations.
SetPipelining enables the Server to use pipelining.
SetPoll enables the Server to use netpoll based on epoll/kqueue.

# Constants

AllLogLevel defines the lowest level in production environments.
DebugLogLevel defines the level of debug in test environments.
DefaultIdleConnTimeout is the default value of Transport's IdleConnTimeout.
DefaultKeepAlive is the default value of Transport's KeepAlive.
DefaultMaxConnsPerHost is the default value of Transport's MaxConnsPerHost.
DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.
ErrorLogLevel defines the level of error.
FatalLogLevel defines the level of fatal.
InfoLogLevel defines the level of info.
LeastTimeScheduling selects the target server with the lowest latency.
NoticeLogLevel defines the level of notice.
OffLogLevel defines the level of no log.
PanicLogLevel defines the level of panic.
RandomScheduling randomly selects the target server.
RoundRobinScheduling uses the Round Robin algorithm to load balance traffic.
TraceLogLevel defines the level of trace in test environments.
WarnLogLevel defines the level of warn.

# Variables

BufferContextKey is a context key.
DefaultServer is the default instance of *Server.
DefaultTransport is a default RPC transport.
ErrDial is returned when dial failed.
ErrorCODE is the error that v is not Code.
ErrorGOGOPB is the error that v is not GoGoProtobuf.
ErrorMSGP is the error that v is not MSGP.
ErrShutdown is returned when the connection is shut down.
ErrTimeout is returned after the timeout,.
ErrWatch is returned when the watch is existed.
ErrWatcherShutdown is returned when the watcher is shut down.
IdleConnTimeout specifies the maximum amount of time keeping the idle connections in the Transport's idleConns.
KeepAlive specifies the maximum amount of time keeping the active connections in the Transport's conns.
MaxConnsPerHost optionally limits the total number of connections per host, including connections in the dialing, active, and idle states.
MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections to keep per-host.

# Structs

BYTESCodec struct.
Call represents an active RPC.
Client is an RPC client.
CODECodec struct.
Conn represents an RPC Conn.
Context is an RPC context for codec.
Encoder defines the struct of Encoder.
GOGOPBCodec struct.
JSONCodec struct.
MSGPCodec struct.
Options defines the struct of options.
Server represents an RPC Server.
Transport defines the struct of transport.
XMLCodec struct.

# Interfaces

ClientCodec implements writing of RPC requests and reading of RPC responses for the client side of an RPC session.
Code defines the interface for code.
Codec defines the interface for encoding/decoding.
GoGoProtobuf defines the interface for gogo's protobuf.
MsgPack defines the interface for msgp.
Request defines the interface of request.
Response defines the interface of response.
RoundTripper is an interface representing the ability to execute a single RPC transaction, obtaining the Response for a given Request.
ServerCodec implements reading of RPC requests and writing of RPC responses for the server side of an RPC session.
Watcher represents a watcher.

# Type aliases

LogLevel defines the level for log.
NewClientCodecFunc is the function to make a new ClientCodec by socket.Messages.
NewServerCodecFunc is the function making a new ServerCodec by socket.Messages.
Scheduling represents the scheduling algorithms.
WatchFunc is the function getting value by key.