You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
starmap/remote_define.go

103 lines
1.8 KiB
Go

4 years ago
package starmap
import (
"encoding/gob"
"os"
4 years ago
"time"
"b612.me/notify"
)
func init() {
notify.Register(kvMsg{})
notify.Register(starMapErr{})
}
type starMapErr struct {
Err string
}
func (s starMapErr) Error() string {
return s.Err
}
func newStarMapErr(err error) error {
if err == nil {
return nil
}
return starMapErr{Err: err.Error()}
}
type kvMsg struct {
Key interface{}
Value interface{}
Err error
}
4 years ago
type RemoteKv struct {
server notify.Server
client notify.Client
kvmap StarMapKV
addr string
network string
readTimeout time.Duration
timeout time.Duration
4 years ago
}
func NewServer(network, addr string) (*RemoteKv, error) {
4 years ago
var err error
kv := RemoteKv{
server: notify.NewServer(),
kvmap: NewStarMap(),
addr: addr,
network: network,
}
err = kv.server.Listen(network, addr)
4 years ago
if err == nil {
kv.bind()
}
return &kv, err
}
func NewClient(network, addr string, dialTimeout time.Duration) (*RemoteKv, error) {
4 years ago
var err error
kv := RemoteKv{
client: notify.NewClient(),
kvmap: NewStarMap(),
addr: addr,
network: network,
timeout: dialTimeout,
readTimeout: time.Second * 5,
4 years ago
}
err = kv.client.ConnectTimeout(network, addr, dialTimeout)
4 years ago
return &kv, err
}
func (kv *RemoteKv) Register(data interface{}) {
gob.Register(data)
}
func (kv *RemoteKv) RegisterAll(data []interface{}) {
for _, v := range data {
gob.Register(v)
}
}
func (kv *RemoteKv) bind() {
//for server
kv.server.SetDefaultLink(kv.dispatch)
//for client
4 years ago
}
func (kv *RemoteKv) reconnect() error {
if kv.server != nil {
return nil
4 years ago
}
if kv.client != nil {
if kv.client.Status().Alive {
return nil
}
return kv.client.ConnectTimeout(kv.network, kv.addr, kv.timeout)
4 years ago
}
return os.ErrInvalid
4 years ago
}