Server
You can implements services in Server side.
The type of services is not important. You can use customized type to keep states or use or int
simplely.
You should start a TCP or UDP server to serve services.
And you can aslo set some plugins to add features to the server.
As service providers, you should define some service first.Currently rpcx only support exported methods
as functions of service.And the exported method must satisfy the below rules:
- exported method of exported type
- three arguments, the first is of context.Context, both of exported type for three arguments
- the third argument is a pointer
- one return value, of type error
you can useRegisterName
to register methods ofrcvr
and name of this service isname
.If you useRegister
, the generated service name is type name ofrcvr
.You can add meta data of this service in registry, that can be used by clients or service manager, for example,weight
、geolocation
、metrics
.
There is an example that implements a Mul
method:
import "context"
type Args struct {
A int
B int
}
type Reply struct {
C int
}
func (t *Arith) Mul(ctx context.Context, args *Args, reply *Reply) error {
reply.C = args.A * args.B
return nil
}
And you can define args
as Args
, this service aslo works.
Server
After you define services, you should want to explore to users. You should start a TCP server or UDP server to listen.
The server supports below approaches to start, serve and close:
First you use NewServer
to create a server instance with options. Second you can invokde Serve
or ServeHTTP
to serve.
The server contains some fields (and unexported fields):
type Server struct {
Plugins PluginContainer
// AuthFunc can be used to auth.
AuthFunc func(ctx context.Context, req *protocol.Message, token string) error
// contains filtered or unexported fields
}
Plugins
caontains all plugins in this server. We will introduce it in later chapters.
rpcx provides three OptionFn
to set options:
It can set readTimeout, writeTimeout and tls.Config.
ServeHTTP
uses a HTTP connection to serve services. It hijacks the connnection to communicate with clients.
uses TCP or UDP ptotocol to communicate with clients.
rpcx supports the below network
:
- tcp: recommended network
- http: hijack http connection
- unix: unix domain sockets
- reuseport: use
SO_REUSEPORT
socket option, only support Linux kernel 3.9+ - quic: support
- kcp: sopport kcp protocol
There is a server example:
package main
"flag"
example "github.com/rpcx-ecosystem/rpcx-examples3"
"github.com/smallnest/rpcx/server"
)
var (
addr = flag.String("addr", "localhost:8972", "server address")
)
func main() {
flag.Parse()
s := server.NewServer()
//s.RegisterName("Arith", new(example.Arith), "")
s.Register(new(example.Arith), "")
s.Serve("tcp", *addr)
By smallnest updated 2018-12-04 11:47:26