rpcx: github.com/smallnest/rpcx/client Index | Files

package client

import "github.com/smallnest/rpcx/client"

Index

Package Files

circuit_breaker.go client.go connection.go connection_nonkcp.go connection_nonquic.go consul_discovery.go etcd_discovery.go etcdv3_discovery.go failmode_enumer.go geo_utils.go hash_utils.go inprocess_client.go inprocess_discovery.go mdns_discovery.go mode.go multiple_servers_discovery.go oneclient.go oneclient_pool.go opencensus.go opentracing.go peer2peer_discovery.go ping_excluded.go plugin.go redis_discovery.go selectmode_enumer.go selector.go smooth-weighted-round-robin.go xclient.go xclient_pool.go zookeeper_discovery.go

Constants

const (
    XVersion           = "X-RPCX-Version"
    XMessageType       = "X-RPCX-MesssageType"
    XHeartbeat         = "X-RPCX-Heartbeat"
    XOneway            = "X-RPCX-Oneway"
    XMessageStatusType = "X-RPCX-MessageStatusType"
    XSerializeType     = "X-RPCX-SerializeType"
    XMessageID         = "X-RPCX-MessageID"
    XServicePath       = "X-RPCX-ServicePath"
    XServiceMethod     = "X-RPCX-ServiceMethod"
    XMeta              = "X-RPCX-Meta"
    XErrorMessage      = "X-RPCX-ErrorMessage"
)
const (
    // ReaderBuffsize is used for bufio reader.
    ReaderBuffsize = 16 * 1024
    // WriterBuffsize is used for bufio writer.
    WriterBuffsize = 16 * 1024
)
const (
    FileTransferBufferSize = 1024
)

Variables

var (
    ErrBreakerOpen    = errors.New("breaker open")
    ErrBreakerTimeout = errors.New("breaker time out")
)
var (
    ErrShutdown         = errors.New("connection is shut down")
    ErrUnsupportedCodec = errors.New("unsupported codec")
)

ErrShutdown connection is closed.

var (
    // ErrXClientShutdown xclient is shutdown.
    ErrXClientShutdown = errors.New("xClient is shut down")
    // ErrXClientNoServer selector can't found one server.
    ErrXClientNoServer = errors.New("can not found any server")
    // ErrServerUnavailable selected server is unavailable.
    ErrServerUnavailable = errors.New("selected server is unavilable")
)
var DefaultOption = Option{
    Retries:        3,
    RPCPath:        share.DefaultRPCPath,
    ConnectTimeout: 10 * time.Second,
    SerializeType:  protocol.MsgPack,
    CompressType:   protocol.None,
    BackupLatency:  10 * time.Millisecond,
}

DefaultOption is a common option configuration for client.

var InprocessClient = &inprocessClient{
    services: make(map[string]interface{}),
    methods:  make(map[string]*reflect.Value),
}

InprocessClient is a in-process client for test.

func Hash Uses

func Hash(key uint64, buckets int32) int32

Hash consistently chooses a hash bucket number in the range [0, numBuckets) for the given key. numBuckets must be >= 1.

func HashString Uses

func HashString(s string) uint64

HashString get a hash value of a string

func JumpConsistentHash Uses

func JumpConsistentHash(len int, options ...interface{}) int

JumpConsistentHash selects a server by serviceMethod and args

type Breaker Uses

type Breaker interface {
    Call(func() error, time.Duration) error
    Fail()
    Success()
    Ready() bool
}

Breaker is a CircuitBreaker interface.

var CircuitBreaker Breaker = circuit.NewRateBreaker(0.95, 100)

CircuitBreaker is a default circuit breaker (RateBreaker(0.95, 100)).

type Call Uses

type Call struct {
    ServicePath   string            // The name of the service and method to call.
    ServiceMethod string            // The name of the service and method to call.
    Metadata      map[string]string //metadata
    ResMetadata   map[string]string
    Args          interface{} // The argument to the function (*struct).
    Reply         interface{} // The reply from the function (*struct).
    Error         error       // After completion, the error status.
    Done          chan *Call  // Strobes when call is complete.
    Raw           bool        // raw message or not
}

Call represents an active RPC.

type Client Uses

type Client struct {
    Conn net.Conn

    Plugins PluginContainer

    ServerMessageChan chan<- *protocol.Message
    // contains filtered or unexported fields
}

Client represents a RPC client.

func NewClient Uses

func NewClient(option Option) *Client

NewClient returns a new Client with the option.

func (*Client) Call Uses

func (client *Client) Call(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}) error

Call invokes the named function, waits for it to complete, and returns its error status.

func (*Client) Close Uses

func (client *Client) Close() error

Close calls the underlying connection's Close method. If the connection is already shutting down, ErrShutdown is returned.

func (*Client) Connect Uses

func (c *Client) Connect(network, address string) error

Connect connects the server via specified network.

func (*Client) Go Uses

func (client *Client) Go(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call

Go invokes the function asynchronously. It returns the Call structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash.

func (*Client) IsClosing Uses

func (client *Client) IsClosing() bool

IsClosing client is closing or not.

func (*Client) IsShutdown Uses

func (client *Client) IsShutdown() bool

IsShutdown client is shutdown or not.

func (*Client) RegisterServerMessageChan Uses

func (client *Client) RegisterServerMessageChan(ch chan<- *protocol.Message)

RegisterServerMessageChan registers the channel that receives server requests.

func (*Client) SendRaw Uses

func (client *Client) SendRaw(ctx context.Context, r *protocol.Message) (map[string]string, []byte, error)

SendRaw sends raw messages. You don't care args and replys.

func (*Client) UnregisterServerMessageChan Uses

func (client *Client) UnregisterServerMessageChan()

UnregisterServerMessageChan removes ServerMessageChan.

type ClientAfterDecodePlugin Uses

type ClientAfterDecodePlugin interface {
    ClientAfterDecode(*protocol.Message) error
}

ClientAfterDecodePlugin is invoked when the message is decoded.

type ClientBeforeEncodePlugin Uses

type ClientBeforeEncodePlugin interface {
    ClientBeforeEncode(*protocol.Message) error
}

ClientBeforeEncodePlugin is invoked when the message is encoded and sent.

type ClientConnectedPlugin Uses

type ClientConnectedPlugin interface {
    ClientConnected(net.Conn) (net.Conn, error)
}

ClientConnectedPlugin is invoked when the client has connected the server.

type ClientConnectionClosePlugin Uses

type ClientConnectionClosePlugin interface {
    ClientConnectionClose(net.Conn) error
}

ClientConnectionClosePlugin is invoked when the connection is closing.

type ConnCreatedPlugin Uses

type ConnCreatedPlugin interface {
    ConnCreated(net.Conn) (net.Conn, error)
}

ConnCreatedPlugin is invoked when the client connection has created.

type ConsecCircuitBreaker Uses

type ConsecCircuitBreaker struct {
    // contains filtered or unexported fields
}

ConsecCircuitBreaker is window sliding CircuitBreaker with failure threshold.

func NewConsecCircuitBreaker Uses

func NewConsecCircuitBreaker(failureThreshold uint64, window time.Duration) *ConsecCircuitBreaker

NewConsecCircuitBreaker returns a new ConsecCircuitBreaker.

func (*ConsecCircuitBreaker) Call Uses

func (cb *ConsecCircuitBreaker) Call(fn func() error, d time.Duration) error

Call Circuit function

func (*ConsecCircuitBreaker) Fail Uses

func (cb *ConsecCircuitBreaker) Fail()

func (*ConsecCircuitBreaker) Ready Uses

func (cb *ConsecCircuitBreaker) Ready() bool

func (*ConsecCircuitBreaker) Success Uses

func (cb *ConsecCircuitBreaker) Success()

type ConsistentAddrStrFunction Uses

type ConsistentAddrStrFunction func(options ...interface{}) string

ConsistentFunction define a hash function Return service address, like "tcp@127.0.0.1:8970"

type ConsulDiscovery Uses

type ConsulDiscovery struct {

    // -1 means it always retry to watch until zookeeper is ok, 0 means no retry.
    RetriesAfterWatchFailed int
    // contains filtered or unexported fields
}

ConsulDiscovery is a consul service discovery. It always returns the registered servers in consul.

func (ConsulDiscovery) Clone Uses

func (d ConsulDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*ConsulDiscovery) Close Uses

func (d *ConsulDiscovery) Close()

func (ConsulDiscovery) GetServices Uses

func (d ConsulDiscovery) GetServices() []*KVPair

GetServices returns the servers

func (*ConsulDiscovery) RemoveWatcher Uses

func (d *ConsulDiscovery) RemoveWatcher(ch chan []*KVPair)

func (ConsulDiscovery) SetFilter Uses

func (d ConsulDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (*ConsulDiscovery) WatchService Uses

func (d *ConsulDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type EtcdDiscovery Uses

type EtcdDiscovery struct {

    // -1 means it always retry to watch until zookeeper is ok, 0 means no retry.
    RetriesAfterWatchFailed int
    // contains filtered or unexported fields
}

EtcdDiscovery is a etcd service discovery. It always returns the registered servers in etcd.

func (EtcdDiscovery) Clone Uses

func (d EtcdDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*EtcdDiscovery) Close Uses

func (d *EtcdDiscovery) Close()

func (EtcdDiscovery) GetServices Uses

func (d EtcdDiscovery) GetServices() []*KVPair

GetServices returns the servers

func (*EtcdDiscovery) RemoveWatcher Uses

func (d *EtcdDiscovery) RemoveWatcher(ch chan []*KVPair)

func (EtcdDiscovery) SetFilter Uses

func (d EtcdDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (*EtcdDiscovery) WatchService Uses

func (d *EtcdDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type EtcdV3Discovery Uses

type EtcdV3Discovery struct {

    // -1 means it always retry to watch until zookeeper is ok, 0 means no retry.
    RetriesAfterWatchFailed int
    // contains filtered or unexported fields
}

EtcdV3Discovery is a etcd service discovery. It always returns the registered servers in etcd.

func (EtcdV3Discovery) Clone Uses

func (d EtcdV3Discovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*EtcdV3Discovery) Close Uses

func (d *EtcdV3Discovery) Close()

func (EtcdV3Discovery) GetServices Uses

func (d EtcdV3Discovery) GetServices() []*KVPair

GetServices returns the servers

func (*EtcdV3Discovery) RemoveWatcher Uses

func (d *EtcdV3Discovery) RemoveWatcher(ch chan []*KVPair)

func (EtcdV3Discovery) SetFilter Uses

func (d EtcdV3Discovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (*EtcdV3Discovery) WatchService Uses

func (d *EtcdV3Discovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type FailMode Uses

type FailMode int

FailMode decides how clients action when clients fail to invoke services

const (
    //Failover selects another server automaticaly
    Failover FailMode = iota
    //Failfast returns error immediately
    Failfast
    //Failtry use current client again
    Failtry
    //Failbackup select another server if the first server doesn't respon in specified time and use the fast response.
    Failbackup
)

func FailModeString Uses

func FailModeString(s string) (FailMode, error)

FailModeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func FailModeValues Uses

func FailModeValues() []FailMode

FailModeValues returns all values of the enum

func (FailMode) IsAFailMode Uses

func (i FailMode) IsAFailMode() bool

IsAFailMode returns "true" if the value is listed in the enum definition. "false" otherwise

func (FailMode) String Uses

func (i FailMode) String() string

type HashServiceAndArgs Uses

type HashServiceAndArgs func(len int, options ...interface{}) int

HashServiceAndArgs define a hash function

type InprocessDiscovery Uses

type InprocessDiscovery struct {
}

InprocessDiscovery is a in-process service discovery. Clients and servers are in one process and communicate without tcp/udp.

func (InprocessDiscovery) Clone Uses

func (d InprocessDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*InprocessDiscovery) Close Uses

func (d *InprocessDiscovery) Close()

func (InprocessDiscovery) GetServices Uses

func (d InprocessDiscovery) GetServices() []*KVPair

GetServices returns the static server

func (InprocessDiscovery) RemoveWatcher Uses

func (d InprocessDiscovery) RemoveWatcher(ch chan []*KVPair)

func (InprocessDiscovery) SetFilter Uses

func (d InprocessDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (InprocessDiscovery) WatchService Uses

func (d InprocessDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type KVPair Uses

type KVPair struct {
    Key   string
    Value string
}

KVPair contains a key and a string.

type MDNSDiscovery Uses

type MDNSDiscovery struct {
    Timeout       time.Duration
    WatchInterval time.Duration
    // contains filtered or unexported fields
}

MDNSDiscovery is a mdns service discovery. It always returns the registered servers in etcd.

func (MDNSDiscovery) Clone Uses

func (d MDNSDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*MDNSDiscovery) Close Uses

func (d *MDNSDiscovery) Close()

func (MDNSDiscovery) GetServices Uses

func (d MDNSDiscovery) GetServices() []*KVPair

GetServices returns the servers

func (*MDNSDiscovery) RemoveWatcher Uses

func (d *MDNSDiscovery) RemoveWatcher(ch chan []*KVPair)

func (MDNSDiscovery) SetFilter Uses

func (d MDNSDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (*MDNSDiscovery) WatchService Uses

func (d *MDNSDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type MultipleServersDiscovery Uses

type MultipleServersDiscovery struct {
    // contains filtered or unexported fields
}

MultipleServersDiscovery is a multiple servers service discovery. It always returns the current servers and uses can change servers dynamically.

func (MultipleServersDiscovery) Clone Uses

func (d MultipleServersDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*MultipleServersDiscovery) Close Uses

func (d *MultipleServersDiscovery) Close()

func (MultipleServersDiscovery) GetServices Uses

func (d MultipleServersDiscovery) GetServices() []*KVPair

GetServices returns the configured server

func (*MultipleServersDiscovery) RemoveWatcher Uses

func (d *MultipleServersDiscovery) RemoveWatcher(ch chan []*KVPair)

func (MultipleServersDiscovery) SetFilter Uses

func (d MultipleServersDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (*MultipleServersDiscovery) Update Uses

func (d *MultipleServersDiscovery) Update(pairs []*KVPair)

Update is used to update servers at runtime.

func (*MultipleServersDiscovery) WatchService Uses

func (d *MultipleServersDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type OneClient Uses

type OneClient struct {
    Plugins PluginContainer
    // contains filtered or unexported fields
}

OneClient wraps servicesPath and XClients.

func NewBidirectionalOneClient Uses

func NewBidirectionalOneClient(failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option, serverMessageChan chan<- *protocol.Message) *OneClient

NewBidirectionalOneClient creates a new xclient that can receive notifications from servers.

func NewOneClient Uses

func NewOneClient(failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option) *OneClient

NewOneClient creates a OneClient that supports service discovery and service governance.

func (*OneClient) Auth Uses

func (c *OneClient) Auth(auth string)

Auth sets s token for Authentication.

func (*OneClient) Broadcast Uses

func (c *OneClient) Broadcast(ctx context.Context, servicePath string, serviceMethod string, args interface{}, reply interface{}) error

Broadcast sends requests to all servers and Success only when all servers return OK. FailMode and SelectMode are meanless for this method. Please set timeout to avoid hanging.

func (*OneClient) Call Uses

func (c *OneClient) Call(ctx context.Context, servicePath string, serviceMethod string, args interface{}, reply interface{}) error

Call invokes the named function, waits for it to complete, and returns its error status. It handles errors base on FailMode.

func (*OneClient) Close Uses

func (c *OneClient) Close() error

Close closes all xclients and its underlying connnections to services.

func (*OneClient) ConfigGeoSelector Uses

func (c *OneClient) ConfigGeoSelector(latitude, longitude float64)

ConfigGeoSelector sets location of client's latitude and longitude, and use newGeoSelector.

func (*OneClient) DownloadFile Uses

func (c *OneClient) DownloadFile(ctx context.Context, requestFileName string, saveTo io.Writer) error

func (*OneClient) Fork Uses

func (c *OneClient) Fork(ctx context.Context, servicePath string, serviceMethod string, args interface{}, reply interface{}) error

Fork sends requests to all servers and Success once one server returns OK. FailMode and SelectMode are meanless for this method.

func (*OneClient) GetPlugins Uses

func (c *OneClient) GetPlugins() PluginContainer

func (*OneClient) Go Uses

func (c *OneClient) Go(ctx context.Context, servicePath string, serviceMethod string, args interface{}, reply interface{}, done chan *Call) (*Call, error)

Go invokes the function asynchronously. It returns the Call structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash. It does not use FailMode.

func (*OneClient) SendFile Uses

func (c *OneClient) SendFile(ctx context.Context, fileName string, rateInBytesPerSecond int64) error

func (*OneClient) SendRaw Uses

func (c *OneClient) SendRaw(ctx context.Context, r *protocol.Message) (map[string]string, []byte, error)

func (*OneClient) SetPlugins Uses

func (c *OneClient) SetPlugins(plugins PluginContainer)

SetPlugins sets client's plugins.

func (*OneClient) SetSelector Uses

func (c *OneClient) SetSelector(servicePath string, s Selector)

SetSelector sets customized selector by users.

type OneClientPool Uses

type OneClientPool struct {
    // contains filtered or unexported fields
}

OneClientPool is a oneclient pool with fixed size. It uses roundrobin algorithm to call its xclients. All oneclients share the same configurations such as ServiceDiscovery and serverMessageChan.

func NewBidirectionalOneClientPool Uses

func NewBidirectionalOneClientPool(count int, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option, serverMessageChan chan<- *protocol.Message) *OneClientPool

NewBidirectionalOneClientPool creates a BidirectionalOneClient pool with fixed size.

func NewOneClientPool Uses

func NewOneClientPool(count int, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option) *OneClientPool

NewOneClientPool creates a fixed size OneClient pool.

func (OneClientPool) Close Uses

func (p OneClientPool) Close()

Close this pool. Please make sure it won't be used any more.

func (OneClientPool) Get Uses

func (p OneClientPool) Get() *OneClient

Get returns a OneClient. It does not remove this OneClient from its cache so you don't need to put it back. Don't close this OneClient because maybe other goroutines are using this OneClient.

type OpenCensusPlugin Uses

type OpenCensusPlugin struct{}

func (*OpenCensusPlugin) DoPostCall Uses

func (p *OpenCensusPlugin) DoPostCall(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, err error) error

func (*OpenCensusPlugin) DoPreCall Uses

func (p *OpenCensusPlugin) DoPreCall(ctx context.Context, servicePath, serviceMethod string, args interface{}) error

type OpenTracingPlugin Uses

type OpenTracingPlugin struct{}

func (*OpenTracingPlugin) DoPostCall Uses

func (p *OpenTracingPlugin) DoPostCall(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, err error) error

func (*OpenTracingPlugin) DoPreCall Uses

func (p *OpenTracingPlugin) DoPreCall(ctx context.Context, servicePath, serviceMethod string, args interface{}) error

type Option Uses

type Option struct {
    // Group is used to select the services in the same group. Services set group info in their meta.
    // If it is empty, clients will ignore group.
    Group string

    // Retries retries to send
    Retries int

    // TLSConfig for tcp and quic
    TLSConfig *tls.Config
    // kcp.BlockCrypt
    Block interface{}
    // RPCPath for http connection
    RPCPath string
    //ConnectTimeout sets timeout for dialing
    ConnectTimeout time.Duration
    // ReadTimeout sets readdeadline for underlying net.Conns
    ReadTimeout time.Duration
    // WriteTimeout sets writedeadline for underlying net.Conns
    WriteTimeout time.Duration

    // BackupLatency is used for Failbackup mode. rpcx will sends another request if the first response doesn't return in BackupLatency time.
    BackupLatency time.Duration

    // Breaker is used to config CircuitBreaker
    GenBreaker func() Breaker

    SerializeType protocol.SerializeType
    CompressType  protocol.CompressType

    Heartbeat         bool
    HeartbeatInterval time.Duration
}

Option contains all options for creating clients.

type Peer2PeerDiscovery Uses

type Peer2PeerDiscovery struct {
    // contains filtered or unexported fields
}

Peer2PeerDiscovery is a peer-to-peer service discovery. It always returns the static server.

func (Peer2PeerDiscovery) Clone Uses

func (d Peer2PeerDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*Peer2PeerDiscovery) Close Uses

func (d *Peer2PeerDiscovery) Close()

func (Peer2PeerDiscovery) GetServices Uses

func (d Peer2PeerDiscovery) GetServices() []*KVPair

GetServices returns the static server

func (*Peer2PeerDiscovery) RemoveWatcher Uses

func (d *Peer2PeerDiscovery) RemoveWatcher(ch chan []*KVPair)

func (Peer2PeerDiscovery) SetFilter Uses

func (d Peer2PeerDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (Peer2PeerDiscovery) WatchService Uses

func (d Peer2PeerDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type Plugin Uses

type Plugin interface {
}

Plugin is the client plugin interface.

type PluginContainer Uses

type PluginContainer interface {
    Add(plugin Plugin)
    Remove(plugin Plugin)
    All() []Plugin

    DoConnCreated(net.Conn) (net.Conn, error)
    DoClientConnected(net.Conn) (net.Conn, error)
    DoClientConnectionClose(net.Conn) error

    DoPreCall(ctx context.Context, servicePath, serviceMethod string, args interface{}) error
    DoPostCall(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, err error) error

    DoClientBeforeEncode(*protocol.Message) error
    DoClientAfterDecode(*protocol.Message) error
}

PluginContainer represents a plugin container that defines all methods to manage plugins. And it also defines all extension points.

func NewPluginContainer Uses

func NewPluginContainer() PluginContainer

type PostCallPlugin Uses

type PostCallPlugin interface {
    DoPostCall(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, err error) error
}

PostCallPlugin is invoked after the client calls a server.

type PreCallPlugin Uses

type PreCallPlugin interface {
    DoPreCall(ctx context.Context, servicePath, serviceMethod string, args interface{}) error
}

PreCallPlugin is invoked before the client calls a server.

type RPCClient Uses

type RPCClient interface {
    Connect(network, address string) error
    Go(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call
    Call(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}) error
    SendRaw(ctx context.Context, r *protocol.Message) (map[string]string, []byte, error)
    Close() error

    RegisterServerMessageChan(ch chan<- *protocol.Message)
    UnregisterServerMessageChan()

    IsClosing() bool
    IsShutdown() bool
}

RPCClient is interface that defines one client to call one server.

type RedisDiscovery Uses

type RedisDiscovery struct {

    // -1 means it always retry to watch until zookeeper is ok, 0 means no retry.
    RetriesAfterWatchFailed int
    // contains filtered or unexported fields
}

RedisDiscovery is a etcd service discovery. It always returns the registered servers in etcd.

func (RedisDiscovery) Clone Uses

func (d RedisDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*RedisDiscovery) Close Uses

func (d *RedisDiscovery) Close()

func (RedisDiscovery) GetServices Uses

func (d RedisDiscovery) GetServices() []*KVPair

GetServices returns the servers

func (*RedisDiscovery) RemoveWatcher Uses

func (d *RedisDiscovery) RemoveWatcher(ch chan []*KVPair)

func (RedisDiscovery) SetFilter Uses

func (d RedisDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (*RedisDiscovery) WatchService Uses

func (d *RedisDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

type SelectMode Uses

type SelectMode int

SelectMode defines the algorithm of selecting a services from candidates.

const (
    //RandomSelect is selecting randomly
    RandomSelect SelectMode = iota
    //RoundRobin is selecting by round robin
    RoundRobin
    //WeightedRoundRobin is selecting by weighted round robin
    WeightedRoundRobin
    //WeightedICMP is selecting by weighted Ping time
    WeightedICMP
    //ConsistentHash is selecting by hashing
    ConsistentHash
    //Closest is selecting the closest server
    Closest

    // SelectByUser is selecting by implementation of users
    SelectByUser = 1000
)

func SelectModeString Uses

func SelectModeString(s string) (SelectMode, error)

SelectModeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func SelectModeValues Uses

func SelectModeValues() []SelectMode

SelectModeValues returns all values of the enum

func (SelectMode) IsASelectMode Uses

func (i SelectMode) IsASelectMode() bool

IsASelectMode returns "true" if the value is listed in the enum definition. "false" otherwise

func (SelectMode) String Uses

func (i SelectMode) String() string

type Selector Uses

type Selector interface {
    Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string
    UpdateServer(servers map[string]string)
}

Selector defines selector that selects one service from candidates.

type ServiceDiscovery Uses

type ServiceDiscovery interface {
    GetServices() []*KVPair
    WatchService() chan []*KVPair
    RemoveWatcher(ch chan []*KVPair)
    Clone(servicePath string) ServiceDiscovery
    SetFilter(ServiceDiscoveryFilter)
    Close()
}

ServiceDiscovery defines ServiceDiscovery of zookeeper, etcd and consul

func NewConsulDiscovery Uses

func NewConsulDiscovery(basePath, servicePath string, consulAddr []string, options *store.Config) ServiceDiscovery

NewConsulDiscovery returns a new ConsulDiscovery.

func NewConsulDiscoveryStore Uses

func NewConsulDiscoveryStore(basePath string, kv store.Store) ServiceDiscovery

NewConsulDiscoveryStore returns a new ConsulDiscovery with specified store.

func NewConsulDiscoveryTemplate Uses

func NewConsulDiscoveryTemplate(basePath string, consulAddr []string, options *store.Config) ServiceDiscovery

NewConsulDiscoveryTemplate returns a new ConsulDiscovery template.

func NewEtcdDiscovery Uses

func NewEtcdDiscovery(basePath string, servicePath string, etcdAddr []string, options *store.Config) ServiceDiscovery

NewEtcdDiscovery returns a new EtcdDiscovery.

func NewEtcdDiscoveryStore Uses

func NewEtcdDiscoveryStore(basePath string, kv store.Store) ServiceDiscovery

NewEtcdDiscoveryStore return a new EtcdDiscovery with specified store.

func NewEtcdDiscoveryTemplate Uses

func NewEtcdDiscoveryTemplate(basePath string, etcdAddr []string, options *store.Config) ServiceDiscovery

NewEtcdDiscoveryTemplate returns a new EtcdDiscovery template.

func NewEtcdV3Discovery Uses

func NewEtcdV3Discovery(basePath string, servicePath string, etcdAddr []string, options *store.Config) ServiceDiscovery

NewEtcdV3Discovery returns a new EtcdV3Discovery.

func NewEtcdV3DiscoveryStore Uses

func NewEtcdV3DiscoveryStore(basePath string, kv store.Store) ServiceDiscovery

NewEtcdV3DiscoveryStore return a new EtcdV3Discovery with specified store.

func NewEtcdV3DiscoveryTemplate Uses

func NewEtcdV3DiscoveryTemplate(basePath string, etcdAddr []string, options *store.Config) ServiceDiscovery

NewEtcdV3DiscoveryTemplate returns a new EtcdV3Discovery template.

func NewInprocessDiscovery Uses

func NewInprocessDiscovery() ServiceDiscovery

NewInprocessDiscovery returns a new InprocessDiscovery.

func NewMDNSDiscovery Uses

func NewMDNSDiscovery(service string, timeout time.Duration, watchInterval time.Duration, domain string) ServiceDiscovery

NewMDNSDiscovery returns a new MDNSDiscovery. If domain is empty, use "local." in default.

func NewMDNSDiscoveryTemplate Uses

func NewMDNSDiscoveryTemplate(timeout time.Duration, watchInterval time.Duration, domain string) ServiceDiscovery

NewMDNSDiscoveryTemplate returns a new MDNSDiscovery template.

func NewMultipleServersDiscovery Uses

func NewMultipleServersDiscovery(pairs []*KVPair) ServiceDiscovery

NewMultipleServersDiscovery returns a new MultipleServersDiscovery.

func NewPeer2PeerDiscovery Uses

func NewPeer2PeerDiscovery(server, metadata string) ServiceDiscovery

NewPeer2PeerDiscovery returns a new Peer2PeerDiscovery.

func NewRedisDiscovery Uses

func NewRedisDiscovery(basePath string, servicePath string, etcdAddr []string, options *store.Config) ServiceDiscovery

NewRedisDiscovery returns a new RedisDiscovery.

func NewRedisDiscoveryStore Uses

func NewRedisDiscoveryStore(basePath string, kv store.Store) ServiceDiscovery

NewRedisDiscoveryStore return a new RedisDiscovery with specified store.

func NewRedisDiscoveryTemplate Uses

func NewRedisDiscoveryTemplate(basePath string, etcdAddr []string, options *store.Config) ServiceDiscovery

NewRedisDiscoveryTemplate returns a new RedisDiscovery template.

func NewZookeeperDiscovery Uses

func NewZookeeperDiscovery(basePath string, servicePath string, zkAddr []string, options *store.Config) ServiceDiscovery

NewZookeeperDiscovery returns a new ZookeeperDiscovery.

func NewZookeeperDiscoveryTemplate Uses

func NewZookeeperDiscoveryTemplate(basePath string, zkAddr []string, options *store.Config) ServiceDiscovery

NewZookeeperDiscoveryTemplate returns a new ZookeeperDiscovery template.

func NewZookeeperDiscoveryWithStore Uses

func NewZookeeperDiscoveryWithStore(basePath string, kv store.Store) ServiceDiscovery

NewZookeeperDiscoveryWithStore returns a new ZookeeperDiscovery with specified store.

type ServiceDiscoveryFilter Uses

type ServiceDiscoveryFilter func(kvp *KVPair) bool

ServiceDiscoveryFilter can be used to filter services with customized logics. Servers can register its services but clients can use the customized filter to select some services. It returns true if ServiceDiscovery wants to use this service, otherwise it returns false.

type ServiceError Uses

type ServiceError string

ServiceError is an error from server.

func (ServiceError) Error Uses

func (e ServiceError) Error() string

type Weighted Uses

type Weighted struct {
    Server          string
    Weight          int
    CurrentWeight   int
    EffectiveWeight int
}

Weighted is a wrapped server with weight

type XClient Uses

type XClient interface {
    SetPlugins(plugins PluginContainer)
    GetPlugins() PluginContainer
    SetSelector(s Selector)
    ConfigGeoSelector(latitude, longitude float64)
    Auth(auth string)

    Go(ctx context.Context, serviceMethod string, args interface{}, reply interface{}, done chan *Call) (*Call, error)
    Call(ctx context.Context, serviceMethod string, args interface{}, reply interface{}) error
    Broadcast(ctx context.Context, serviceMethod string, args interface{}, reply interface{}) error
    Fork(ctx context.Context, serviceMethod string, args interface{}, reply interface{}) error
    SendRaw(ctx context.Context, r *protocol.Message) (map[string]string, []byte, error)
    SendFile(ctx context.Context, fileName string, rateInBytesPerSecond int64) error
    DownloadFile(ctx context.Context, requestFileName string, saveTo io.Writer) error
    Close() error
}

XClient is an interface that used by client with service discovery and service governance. One XClient is used only for one service. You should create multiple XClient for multiple services.

func NewBidirectionalXClient Uses

func NewBidirectionalXClient(servicePath string, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option, serverMessageChan chan<- *protocol.Message) XClient

NewBidirectionalXClient creates a new xclient that can receive notifications from servers.

func NewXClient Uses

func NewXClient(servicePath string, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option) XClient

NewXClient creates a XClient that supports service discovery and service governance.

type XClientPool Uses

type XClientPool struct {
    // contains filtered or unexported fields
}

XClientPool is a xclient pool with fixed size. It uses roundrobin algorithm to call its xclients. All xclients share the same configurations such as ServiceDiscovery and serverMessageChan.

func NewBidirectionalXClientPool Uses

func NewBidirectionalXClientPool(count int, servicePath string, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option, serverMessageChan chan<- *protocol.Message) *XClientPool

NewBidirectionalXClientPool creates a BidirectionalXClient pool with fixed size.

func NewXClientPool Uses

func NewXClientPool(count int, servicePath string, failMode FailMode, selectMode SelectMode, discovery ServiceDiscovery, option Option) *XClientPool

NewXClientPool creates a fixed size XClient pool.

func (*XClientPool) Close Uses

func (p *XClientPool) Close()

Close this pool. Please make sure it won't be used any more.

func (*XClientPool) Get Uses

func (p *XClientPool) Get() XClient

Get returns a xclient. It does not remove this xclient from its cache so you don't need to put it back. Don't close this xclient because maybe other goroutines are using this xclient.

type ZookeeperDiscovery Uses

type ZookeeperDiscovery struct {

    // -1 means it always retry to watch until zookeeper is ok, 0 means no retry.
    RetriesAfterWatchFailed int
    // contains filtered or unexported fields
}

ZookeeperDiscovery is a zoopkeer service discovery. It always returns the registered servers in zookeeper.

func (ZookeeperDiscovery) Clone Uses

func (d ZookeeperDiscovery) Clone(servicePath string) ServiceDiscovery

Clone clones this ServiceDiscovery with new servicePath.

func (*ZookeeperDiscovery) Close Uses

func (d *ZookeeperDiscovery) Close()

func (ZookeeperDiscovery) GetServices Uses

func (d ZookeeperDiscovery) GetServices() []*KVPair

GetServices returns the servers

func (*ZookeeperDiscovery) RemoveWatcher Uses

func (d *ZookeeperDiscovery) RemoveWatcher(ch chan []*KVPair)

func (ZookeeperDiscovery) SetFilter Uses

func (d ZookeeperDiscovery) SetFilter(filter ServiceDiscoveryFilter)

SetFilter sets the filer.

func (*ZookeeperDiscovery) WatchService Uses

func (d *ZookeeperDiscovery) WatchService() chan []*KVPair

WatchService returns a nil chan.

Package client imports 45 packages (graph) and is imported by 47 packages. Updated 2019-11-16. Refresh now. Tools for package owners.