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/client_basicrw.go

98 lines
2.0 KiB
Go

package starmap
import (
"errors"
"time"
)
func (kv *RemoteKv) clientOnline() error {
if kv.client == nil || (kv.setKeepAlive && !kv.client.Online) {
return errors.New("Client Not Online,Please Contact A Server First")
}
if (!kv.setKeepAlive) && (!kv.client.Online) {
err := kv.reconnect()
return err
}
return nil
}
func (kv *RemoteKv) MustGet(key string) interface{} {
result, _ := kv.Get(key)
return result
}
func (kv *RemoteKv) Get(key string) (interface{}, error) {
kv.kvmu.Lock()
defer kv.kvmu.Unlock()
defer kv.keepalive()
if err := kv.clientOnline(); err != nil {
return nil, err
}
data, err := kv.client.SendValueWait("Get", key, kv.TimeOut)
if err != nil {
return nil, err
}
inf, err := decode([]byte(data.Value))
if err != nil {
return nil, err
}
var repInf *basicReply
repInf = inf.(*basicReply)
if repInf.Key == "ok" {
inf2, err := decode(repInf.Value)
if err != nil {
return nil, err
}
return inf2, nil
}
return nil, errors.New(string(repInf.Value))
}
func (kv *RemoteKv) Store(key string, value interface{}) error {
kv.kvmu.Lock()
defer kv.kvmu.Unlock()
defer kv.keepalive()
if err := kv.clientOnline(); err != nil {
return err
}
encodeData, err := encode(value)
if err != nil {
return err
}
sendData, _ := encode(basicReply{key, encodeData})
data, err := kv.client.SendValueWait("Store", string(sendData), kv.TimeOut)
if err != nil {
return err
}
if data.Value == "ok" {
return nil
}
return errors.New(data.Value)
}
func (kv *RemoteKv) Delete(key string) error {
kv.kvmu.Lock()
defer kv.kvmu.Unlock()
defer kv.keepalive()
if err := kv.clientOnline(); err != nil {
return err
}
data, err := kv.client.SendValueWait("Delete", key, kv.TimeOut)
if err != nil {
return err
}
if data.Value == "ok" {
return nil
}
return errors.New(data.Value)
}
func (kv *RemoteKv) keepalive() {
if !kv.setKeepAlive && kv.client.Online {
kv.client.ClientStop()
for kv.client.Online {
time.Sleep(time.Millisecond)
}
}
}