mirror of
https://github.com/duanhf2012/origin.git
synced 2026-02-03 22:45:13 +08:00
优化工程结构
This commit is contained in:
@@ -7,10 +7,10 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var Default_MaxHeaderBytes int = 1<<20
|
||||
var DefaultMaxHeaderBytes int = 1<<20
|
||||
|
||||
type CAFile struct {
|
||||
Certfile string
|
||||
CertFile string
|
||||
Keyfile string
|
||||
}
|
||||
|
||||
@@ -40,9 +40,9 @@ func (slf *HttpServer) startListen() error {
|
||||
var tlsCaList []tls.Certificate
|
||||
var tlsConfig *tls.Config
|
||||
for _, caFile := range slf.caFileList {
|
||||
cer, err := tls.LoadX509KeyPair(caFile.Certfile, caFile.Keyfile)
|
||||
cer, err := tls.LoadX509KeyPair(caFile.CertFile, caFile.Keyfile)
|
||||
if err != nil {
|
||||
log.Fatal("Load CA [%s]-[%s] file is fail:%s", caFile.Certfile, caFile.Keyfile, err.Error())
|
||||
log.Fatal("Load CA [%s]-[%s] file is fail:%s", caFile.CertFile, caFile.Keyfile, err.Error())
|
||||
return err
|
||||
}
|
||||
tlsCaList = append(tlsCaList, cer)
|
||||
@@ -57,7 +57,7 @@ func (slf *HttpServer) startListen() error {
|
||||
Handler: slf.handler,
|
||||
ReadTimeout: slf.readTimeout,
|
||||
WriteTimeout: slf.writeTimeout,
|
||||
MaxHeaderBytes: Default_MaxHeaderBytes,
|
||||
MaxHeaderBytes: DefaultMaxHeaderBytes,
|
||||
TLSConfig: tlsConfig,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package network
|
||||
|
||||
type inetserver interface {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -11,13 +11,11 @@ type MessageJsonInfo struct {
|
||||
msgHandler MessageJsonHandler
|
||||
}
|
||||
|
||||
type MessageJsonHandler func(clientid uint64,msg interface{})
|
||||
type ConnectJsonHandler func(clientid uint64)
|
||||
type UnknownMessageJsonHandler func(clientid uint64,msg []byte)
|
||||
type MessageJsonHandler func(clientId uint64,msg interface{})
|
||||
type ConnectJsonHandler func(clientId uint64)
|
||||
type UnknownMessageJsonHandler func(clientId uint64,msg []byte)
|
||||
|
||||
type JsonProcessor struct {
|
||||
//SetByteOrder(littleEndian bool)
|
||||
//SetMsgLen(lenMsgLen int, minMsgLen uint32, maxMsgLen uint32)
|
||||
mapMsg map[uint16]MessageJsonInfo
|
||||
LittleEndian bool
|
||||
|
||||
@@ -26,33 +24,25 @@ type JsonProcessor struct {
|
||||
disconnectHandler ConnectJsonHandler
|
||||
}
|
||||
|
||||
func NewJsonProcessor() *JsonProcessor {
|
||||
processor := &JsonProcessor{mapMsg:map[uint16]MessageJsonInfo{}}
|
||||
return processor
|
||||
}
|
||||
|
||||
func (p *JsonProcessor) SetByteOrder(littleEndian bool) {
|
||||
p.LittleEndian = littleEndian
|
||||
}
|
||||
|
||||
type JsonPackInfo struct {
|
||||
typ uint16
|
||||
msg interface{}
|
||||
rawMsg []byte
|
||||
}
|
||||
|
||||
func (slf *JsonPackInfo) GetPackType() uint16 {
|
||||
return slf.typ
|
||||
func NewJsonProcessor() *JsonProcessor {
|
||||
processor := &JsonProcessor{mapMsg:map[uint16]MessageJsonInfo{}}
|
||||
return processor
|
||||
}
|
||||
|
||||
func (slf *JsonPackInfo) GetMsg() interface{} {
|
||||
return slf.msg
|
||||
func (jsonProcessor *JsonProcessor) SetByteOrder(littleEndian bool) {
|
||||
jsonProcessor.LittleEndian = littleEndian
|
||||
}
|
||||
|
||||
// must goroutine safe
|
||||
func (slf *JsonProcessor ) MsgRoute(msg interface{},userdata interface{}) error{
|
||||
func (jsonProcessor *JsonProcessor ) MsgRoute(msg interface{},userdata interface{}) error{
|
||||
pPackInfo := msg.(*JsonPackInfo)
|
||||
v,ok := slf.mapMsg[pPackInfo.typ]
|
||||
v,ok := jsonProcessor.mapMsg[pPackInfo.typ]
|
||||
if ok == false {
|
||||
return fmt.Errorf("cannot find msgtype %d is register!",pPackInfo.typ)
|
||||
}
|
||||
@@ -61,18 +51,19 @@ func (slf *JsonProcessor ) MsgRoute(msg interface{},userdata interface{}) error{
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) Unmarshal(data []byte) (interface{}, error) {
|
||||
typeStrcut := struct {Type int `json:"typ"`}{}
|
||||
err := json.Unmarshal(data, &typeStrcut)
|
||||
func (jsonProcessor *JsonProcessor) Unmarshal(data []byte) (interface{}, error) {
|
||||
typeStruct := struct {Type int `json:"typ"`}{}
|
||||
err := json.Unmarshal(data, &typeStruct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgType := uint16(typeStrcut.Type)
|
||||
|
||||
info,ok := slf.mapMsg[msgType]
|
||||
msgType := uint16(typeStruct.Type)
|
||||
info,ok := jsonProcessor.mapMsg[msgType]
|
||||
if ok == false {
|
||||
return nil,fmt.Errorf("cannot find register %d msgtype!",msgType)
|
||||
return nil,fmt.Errorf("Cannot find register %d msgType!",msgType)
|
||||
}
|
||||
|
||||
msg := reflect.New(info.msgType.Elem()).Interface()
|
||||
err = json.Unmarshal(data, msg)
|
||||
if err != nil {
|
||||
@@ -82,8 +73,7 @@ func (slf *JsonProcessor) Unmarshal(data []byte) (interface{}, error) {
|
||||
return &JsonPackInfo{typ:msgType,msg:msg},nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *JsonProcessor) Marshal(msg interface{}) ([]byte, error) {
|
||||
func (jsonProcessor *JsonProcessor) Marshal(msg interface{}) ([]byte, error) {
|
||||
rawMsg,err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil,err
|
||||
@@ -92,43 +82,50 @@ func (slf *JsonProcessor) Marshal(msg interface{}) ([]byte, error) {
|
||||
return rawMsg,nil
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) Register(msgtype uint16,msg interface{},handle MessageJsonHandler) {
|
||||
func (jsonProcessor *JsonProcessor) Register(msgtype uint16,msg interface{},handle MessageJsonHandler) {
|
||||
var info MessageJsonInfo
|
||||
|
||||
info.msgType = reflect.TypeOf(msg)
|
||||
info.msgHandler = handle
|
||||
slf.mapMsg[msgtype] = info
|
||||
jsonProcessor.mapMsg[msgtype] = info
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) MakeMsg(msgType uint16,msg interface{}) *JsonPackInfo {
|
||||
func (jsonProcessor *JsonProcessor) MakeMsg(msgType uint16,msg interface{}) *JsonPackInfo {
|
||||
return &JsonPackInfo{typ:msgType,msg:msg}
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) MakeRawMsg(msgType uint16,msg []byte) *JsonPackInfo {
|
||||
func (jsonProcessor *JsonProcessor) MakeRawMsg(msgType uint16,msg []byte) *JsonPackInfo {
|
||||
return &JsonPackInfo{typ:msgType,rawMsg:msg}
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) UnknownMsgRoute(msg interface{}, userData interface{}){
|
||||
slf.unknownMessageHandler(userData.(uint64),msg.([]byte))
|
||||
func (jsonProcessor *JsonProcessor) UnknownMsgRoute(msg interface{}, userData interface{}){
|
||||
jsonProcessor.unknownMessageHandler(userData.(uint64),msg.([]byte))
|
||||
}
|
||||
|
||||
// connect event
|
||||
func (slf *JsonProcessor) ConnectedRoute(userData interface{}){
|
||||
slf.connectHandler(userData.(uint64))
|
||||
func (jsonProcessor *JsonProcessor) ConnectedRoute(userData interface{}){
|
||||
jsonProcessor.connectHandler(userData.(uint64))
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) DisConnectedRoute(userData interface{}){
|
||||
slf.disconnectHandler(userData.(uint64))
|
||||
func (jsonProcessor *JsonProcessor) DisConnectedRoute(userData interface{}){
|
||||
jsonProcessor.disconnectHandler(userData.(uint64))
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) RegisterUnknownMsg(unknownMessageHandler UnknownMessageJsonHandler){
|
||||
slf.unknownMessageHandler = unknownMessageHandler
|
||||
func (jsonProcessor *JsonProcessor) RegisterUnknownMsg(unknownMessageHandler UnknownMessageJsonHandler){
|
||||
jsonProcessor.unknownMessageHandler = unknownMessageHandler
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) RegisterConnected(connectHandler ConnectJsonHandler){
|
||||
slf.connectHandler = connectHandler
|
||||
func (jsonProcessor *JsonProcessor) RegisterConnected(connectHandler ConnectJsonHandler){
|
||||
jsonProcessor.connectHandler = connectHandler
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) RegisterDisConnected(disconnectHandler ConnectJsonHandler){
|
||||
slf.disconnectHandler = disconnectHandler
|
||||
func (jsonProcessor *JsonProcessor) RegisterDisConnected(disconnectHandler ConnectJsonHandler){
|
||||
jsonProcessor.disconnectHandler = disconnectHandler
|
||||
}
|
||||
|
||||
func (slf *JsonPackInfo) GetPackType() uint16 {
|
||||
return slf.typ
|
||||
}
|
||||
|
||||
func (slf *JsonPackInfo) GetMsg() interface{} {
|
||||
return slf.msg
|
||||
}
|
||||
@@ -12,9 +12,9 @@ type MessageInfo struct {
|
||||
msgHandler MessageHandler
|
||||
}
|
||||
|
||||
type MessageHandler func(clientid uint64,msg proto.Message)
|
||||
type ConnectHandler func(clientid uint64)
|
||||
type UnknownMessageHandler func(clientid uint64,msg []byte)
|
||||
type MessageHandler func(clientId uint64,msg proto.Message)
|
||||
type ConnectHandler func(clientId uint64)
|
||||
type UnknownMessageHandler func(clientId uint64,msg []byte)
|
||||
|
||||
const MsgTypeSize = 2
|
||||
type PBProcessor struct {
|
||||
@@ -26,20 +26,19 @@ type PBProcessor struct {
|
||||
disconnectHandler ConnectHandler
|
||||
}
|
||||
|
||||
type PBPackInfo struct {
|
||||
typ uint16
|
||||
msg proto.Message
|
||||
rawMsg []byte
|
||||
}
|
||||
|
||||
func NewPBProcessor() *PBProcessor {
|
||||
processor := &PBProcessor{mapMsg:map[uint16]MessageInfo{}}
|
||||
return processor
|
||||
}
|
||||
|
||||
func (p *PBProcessor) SetByteOrder(littleEndian bool) {
|
||||
p.LittleEndian = littleEndian
|
||||
}
|
||||
|
||||
|
||||
type PBPackInfo struct {
|
||||
typ uint16
|
||||
msg proto.Message
|
||||
rawMsg []byte
|
||||
func (pbProcessor *PBProcessor) SetByteOrder(littleEndian bool) {
|
||||
pbProcessor.LittleEndian = littleEndian
|
||||
}
|
||||
|
||||
func (slf *PBPackInfo) GetPackType() uint16 {
|
||||
@@ -51,28 +50,27 @@ func (slf *PBPackInfo) GetMsg() proto.Message {
|
||||
}
|
||||
|
||||
// must goroutine safe
|
||||
func (slf *PBProcessor ) MsgRoute(msg interface{},userdata interface{}) error{
|
||||
func (pbProcessor *PBProcessor ) MsgRoute(msg interface{},userdata interface{}) error{
|
||||
pPackInfo := msg.(*PBPackInfo)
|
||||
v,ok := slf.mapMsg[pPackInfo.typ]
|
||||
v,ok := pbProcessor.mapMsg[pPackInfo.typ]
|
||||
if ok == false {
|
||||
return fmt.Errorf("cannot find msgtype %d is register!",pPackInfo.typ)
|
||||
return fmt.Errorf("Cannot find msgtype %d is register!",pPackInfo.typ)
|
||||
}
|
||||
|
||||
|
||||
v.msgHandler(userdata.(uint64),pPackInfo.msg)
|
||||
return nil
|
||||
}
|
||||
|
||||
// must goroutine safe
|
||||
func (slf *PBProcessor ) Unmarshal(data []byte) (interface{}, error) {
|
||||
func (pbProcessor *PBProcessor ) Unmarshal(data []byte) (interface{}, error) {
|
||||
var msgType uint16
|
||||
if slf.LittleEndian == true {
|
||||
if pbProcessor.LittleEndian == true {
|
||||
msgType = binary.LittleEndian.Uint16(data[:2])
|
||||
}else{
|
||||
msgType = binary.BigEndian.Uint16(data[:2])
|
||||
}
|
||||
|
||||
info,ok := slf.mapMsg[msgType]
|
||||
info,ok := pbProcessor.mapMsg[msgType]
|
||||
if ok == false {
|
||||
return nil,fmt.Errorf("cannot find register %d msgtype!",msgType)
|
||||
}
|
||||
@@ -87,7 +85,7 @@ func (slf *PBProcessor ) Unmarshal(data []byte) (interface{}, error) {
|
||||
}
|
||||
|
||||
// must goroutine safe
|
||||
func (slf *PBProcessor ) Marshal(msg interface{}) ([]byte, error){
|
||||
func (pbProcessor *PBProcessor ) Marshal(msg interface{}) ([]byte, error){
|
||||
pMsg := msg.(*PBPackInfo)
|
||||
|
||||
var err error
|
||||
@@ -99,7 +97,7 @@ func (slf *PBProcessor ) Marshal(msg interface{}) ([]byte, error){
|
||||
}
|
||||
|
||||
buff := make([]byte, 2, len(pMsg.rawMsg)+MsgTypeSize)
|
||||
if slf.LittleEndian == true {
|
||||
if pbProcessor.LittleEndian == true {
|
||||
binary.LittleEndian.PutUint16(buff[:2],pMsg.typ)
|
||||
}else{
|
||||
binary.BigEndian.PutUint16(buff[:2],pMsg.typ)
|
||||
@@ -109,45 +107,45 @@ func (slf *PBProcessor ) Marshal(msg interface{}) ([]byte, error){
|
||||
return buff,nil
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) Register(msgtype uint16,msg proto.Message,handle MessageHandler) {
|
||||
func (pbProcessor *PBProcessor) Register(msgtype uint16,msg proto.Message,handle MessageHandler) {
|
||||
var info MessageInfo
|
||||
|
||||
info.msgType = reflect.TypeOf(msg.(proto.Message))
|
||||
info.msgHandler = handle
|
||||
slf.mapMsg[msgtype] = info
|
||||
pbProcessor.mapMsg[msgtype] = info
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) MakeMsg(msgType uint16,protoMsg proto.Message) *PBPackInfo {
|
||||
func (pbProcessor *PBProcessor) MakeMsg(msgType uint16,protoMsg proto.Message) *PBPackInfo {
|
||||
return &PBPackInfo{typ:msgType,msg:protoMsg}
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) MakeRawMsg(msgType uint16,msg []byte) *PBPackInfo {
|
||||
func (pbProcessor *PBProcessor) MakeRawMsg(msgType uint16,msg []byte) *PBPackInfo {
|
||||
return &PBPackInfo{typ:msgType,rawMsg:msg}
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) UnknownMsgRoute(msg interface{}, userData interface{}){
|
||||
slf.unknownMessageHandler(userData.(uint64),msg.([]byte))
|
||||
func (pbProcessor *PBProcessor) UnknownMsgRoute(msg interface{}, userData interface{}){
|
||||
pbProcessor.unknownMessageHandler(userData.(uint64),msg.([]byte))
|
||||
}
|
||||
|
||||
// connect event
|
||||
func (slf *PBProcessor) ConnectedRoute(userData interface{}){
|
||||
slf.connectHandler(userData.(uint64))
|
||||
func (pbProcessor *PBProcessor) ConnectedRoute(userData interface{}){
|
||||
pbProcessor.connectHandler(userData.(uint64))
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) DisConnectedRoute(userData interface{}){
|
||||
slf.disconnectHandler(userData.(uint64))
|
||||
func (pbProcessor *PBProcessor) DisConnectedRoute(userData interface{}){
|
||||
pbProcessor.disconnectHandler(userData.(uint64))
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) RegisterUnknownMsg(unknownMessageHandler UnknownMessageHandler){
|
||||
slf.unknownMessageHandler = unknownMessageHandler
|
||||
func (pbProcessor *PBProcessor) RegisterUnknownMsg(unknownMessageHandler UnknownMessageHandler){
|
||||
pbProcessor.unknownMessageHandler = unknownMessageHandler
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) RegisterConnected(connectHandler ConnectHandler){
|
||||
slf.connectHandler = connectHandler
|
||||
func (pbProcessor *PBProcessor) RegisterConnected(connectHandler ConnectHandler){
|
||||
pbProcessor.connectHandler = connectHandler
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) RegisterDisConnected(disconnectHandler ConnectHandler){
|
||||
slf.disconnectHandler = disconnectHandler
|
||||
func (pbProcessor *PBProcessor) RegisterDisConnected(disconnectHandler ConnectHandler){
|
||||
pbProcessor.disconnectHandler = disconnectHandler
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -18,45 +18,36 @@ const RawMsgTypeSize = 2
|
||||
type PBRawProcessor struct {
|
||||
msgHandler RawMessageHandler
|
||||
LittleEndian bool
|
||||
|
||||
unknownMessageHandler UnknownRawMessageHandler
|
||||
connectHandler RawConnectHandler
|
||||
disconnectHandler RawConnectHandler
|
||||
}
|
||||
|
||||
func NewPBRawProcessor() *PBRawProcessor {
|
||||
processor := &PBRawProcessor{}
|
||||
return processor
|
||||
}
|
||||
|
||||
func (p *PBRawProcessor) SetByteOrder(littleEndian bool) {
|
||||
p.LittleEndian = littleEndian
|
||||
}
|
||||
|
||||
type PBRawPackInfo struct {
|
||||
typ uint16
|
||||
rawMsg []byte
|
||||
}
|
||||
|
||||
func (slf *PBRawPackInfo) GetPackType() uint16 {
|
||||
return slf.typ
|
||||
func NewPBRawProcessor() *PBRawProcessor {
|
||||
processor := &PBRawProcessor{}
|
||||
return processor
|
||||
}
|
||||
|
||||
func (slf *PBRawPackInfo) GetMsg() []byte {
|
||||
return slf.rawMsg
|
||||
func (pbRawProcessor *PBRawProcessor) SetByteOrder(littleEndian bool) {
|
||||
pbRawProcessor.LittleEndian = littleEndian
|
||||
}
|
||||
|
||||
// must goroutine safe
|
||||
func (slf *PBRawProcessor ) MsgRoute(msg interface{},userdata interface{}) error{
|
||||
func (pbRawProcessor *PBRawProcessor ) MsgRoute(msg interface{},userdata interface{}) error{
|
||||
pPackInfo := msg.(*PBRawPackInfo)
|
||||
slf.msgHandler(userdata.(uint64),pPackInfo.typ,pPackInfo.rawMsg)
|
||||
pbRawProcessor.msgHandler(userdata.(uint64),pPackInfo.typ,pPackInfo.rawMsg)
|
||||
return nil
|
||||
}
|
||||
|
||||
// must goroutine safe
|
||||
func (slf *PBRawProcessor ) Unmarshal(data []byte) (interface{}, error) {
|
||||
func (pbRawProcessor *PBRawProcessor ) Unmarshal(data []byte) (interface{}, error) {
|
||||
var msgType uint16
|
||||
if slf.LittleEndian == true {
|
||||
if pbRawProcessor.LittleEndian == true {
|
||||
msgType = binary.LittleEndian.Uint16(data[:2])
|
||||
}else{
|
||||
msgType = binary.BigEndian.Uint16(data[:2])
|
||||
@@ -66,11 +57,11 @@ func (slf *PBRawProcessor ) Unmarshal(data []byte) (interface{}, error) {
|
||||
}
|
||||
|
||||
// must goroutine safe
|
||||
func (slf *PBRawProcessor ) Marshal(msg interface{}) ([]byte, error){
|
||||
func (pbRawProcessor *PBRawProcessor ) Marshal(msg interface{}) ([]byte, error){
|
||||
pMsg := msg.(*PBRawPackInfo)
|
||||
|
||||
buff := make([]byte, 2, len(pMsg.rawMsg)+RawMsgTypeSize)
|
||||
if slf.LittleEndian == true {
|
||||
if pbRawProcessor.LittleEndian == true {
|
||||
binary.LittleEndian.PutUint16(buff[:2],pMsg.typ)
|
||||
}else{
|
||||
binary.BigEndian.PutUint16(buff[:2],pMsg.typ)
|
||||
@@ -80,40 +71,46 @@ func (slf *PBRawProcessor ) Marshal(msg interface{}) ([]byte, error){
|
||||
return buff,nil
|
||||
}
|
||||
|
||||
func (slf *PBRawProcessor) SetRawMsgHandler(handle RawMessageHandler) {
|
||||
slf.msgHandler = handle
|
||||
func (pbRawProcessor *PBRawProcessor) SetRawMsgHandler(handle RawMessageHandler) {
|
||||
pbRawProcessor.msgHandler = handle
|
||||
}
|
||||
|
||||
|
||||
func (slf *PBRawProcessor) MakeRawMsg(msgType uint16,msg []byte) *PBRawPackInfo {
|
||||
func (pbRawProcessor *PBRawProcessor) MakeRawMsg(msgType uint16,msg []byte) *PBRawPackInfo {
|
||||
return &PBRawPackInfo{typ:msgType,rawMsg:msg}
|
||||
}
|
||||
|
||||
func (slf *PBRawProcessor) UnknownMsgRoute(msg interface{}, userData interface{}){
|
||||
if slf.unknownMessageHandler == nil {
|
||||
func (pbRawProcessor *PBRawProcessor) UnknownMsgRoute(msg interface{}, userData interface{}){
|
||||
if pbRawProcessor.unknownMessageHandler == nil {
|
||||
return
|
||||
}
|
||||
slf.unknownMessageHandler(userData.(uint64),msg.([]byte))
|
||||
pbRawProcessor.unknownMessageHandler(userData.(uint64),msg.([]byte))
|
||||
}
|
||||
|
||||
// connect event
|
||||
func (slf *PBRawProcessor) ConnectedRoute(userData interface{}){
|
||||
slf.connectHandler(userData.(uint64))
|
||||
func (pbRawProcessor *PBRawProcessor) ConnectedRoute(userData interface{}){
|
||||
pbRawProcessor.connectHandler(userData.(uint64))
|
||||
}
|
||||
|
||||
func (slf *PBRawProcessor) DisConnectedRoute(userData interface{}){
|
||||
slf.disconnectHandler(userData.(uint64))
|
||||
func (pbRawProcessor *PBRawProcessor) DisConnectedRoute(userData interface{}){
|
||||
pbRawProcessor.disconnectHandler(userData.(uint64))
|
||||
}
|
||||
|
||||
func (slf *PBRawProcessor) SetUnknownMsgHandler(unknownMessageHandler UnknownRawMessageHandler){
|
||||
slf.unknownMessageHandler = unknownMessageHandler
|
||||
func (pbRawProcessor *PBRawProcessor) SetUnknownMsgHandler(unknownMessageHandler UnknownRawMessageHandler){
|
||||
pbRawProcessor.unknownMessageHandler = unknownMessageHandler
|
||||
}
|
||||
|
||||
func (slf *PBRawProcessor) SetConnectedHandler(connectHandler RawConnectHandler){
|
||||
slf.connectHandler = connectHandler
|
||||
func (pbRawProcessor *PBRawProcessor) SetConnectedHandler(connectHandler RawConnectHandler){
|
||||
pbRawProcessor.connectHandler = connectHandler
|
||||
}
|
||||
|
||||
func (slf *PBRawProcessor) SetDisConnectedHandler(disconnectHandler RawConnectHandler){
|
||||
slf.disconnectHandler = disconnectHandler
|
||||
func (pbRawProcessor *PBRawProcessor) SetDisConnectedHandler(disconnectHandler RawConnectHandler){
|
||||
pbRawProcessor.disconnectHandler = disconnectHandler
|
||||
}
|
||||
|
||||
func (slf *PBRawPackInfo) GetPackType() uint16 {
|
||||
return slf.typ
|
||||
}
|
||||
|
||||
func (slf *PBRawPackInfo) GetMsg() []byte {
|
||||
return slf.rawMsg
|
||||
}
|
||||
@@ -59,10 +59,6 @@ func (areaPool *memAreaPool) releaseByteSlice(byteBuff []byte) bool{
|
||||
}
|
||||
|
||||
areaPool.pool[pos].Put(byteBuff)
|
||||
|
||||
|
||||
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ type TCPClient struct {
|
||||
PendingWriteNum int
|
||||
AutoReconnect bool
|
||||
NewAgent func(*TCPConn) Agent
|
||||
conns ConnSet
|
||||
cons ConnSet
|
||||
wg sync.WaitGroup
|
||||
closeFlag bool
|
||||
|
||||
@@ -55,11 +55,11 @@ func (client *TCPClient) init() {
|
||||
if client.NewAgent == nil {
|
||||
log.Fatal("NewAgent must not be nil")
|
||||
}
|
||||
if client.conns != nil {
|
||||
if client.cons != nil {
|
||||
log.Fatal("client is running")
|
||||
}
|
||||
|
||||
client.conns = make(ConnSet)
|
||||
client.cons = make(ConnSet)
|
||||
client.closeFlag = false
|
||||
|
||||
// msg parser
|
||||
@@ -97,7 +97,7 @@ reconnect:
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
client.conns[conn] = struct{}{}
|
||||
client.cons[conn] = struct{}{}
|
||||
client.Unlock()
|
||||
|
||||
tcpConn := newTCPConn(conn, client.PendingWriteNum, client.msgParser)
|
||||
@@ -107,7 +107,7 @@ reconnect:
|
||||
// cleanup
|
||||
tcpConn.Close()
|
||||
client.Lock()
|
||||
delete(client.conns, conn)
|
||||
delete(client.cons, conn)
|
||||
client.Unlock()
|
||||
agent.OnClose()
|
||||
|
||||
@@ -120,10 +120,10 @@ reconnect:
|
||||
func (client *TCPClient) Close(waitDone bool) {
|
||||
client.Lock()
|
||||
client.closeFlag = true
|
||||
for conn := range client.conns {
|
||||
for conn := range client.cons {
|
||||
conn.Close()
|
||||
}
|
||||
client.conns = nil
|
||||
client.cons = nil
|
||||
client.Unlock()
|
||||
|
||||
if waitDone == true{
|
||||
|
||||
@@ -17,7 +17,6 @@ type TCPConn struct {
|
||||
msgParser *MsgParser
|
||||
}
|
||||
|
||||
|
||||
func freeChannel(conn *TCPConn){
|
||||
for;len(conn.writeChan)>0;{
|
||||
byteBuff := <- conn.writeChan
|
||||
|
||||
@@ -90,7 +90,6 @@ func (p *MsgParser) Read(conn *TCPConn) ([]byte, error) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// check len
|
||||
if msgLen > p.maxMsgLen {
|
||||
return nil, errors.New("message too long")
|
||||
@@ -124,7 +123,6 @@ func (p *MsgParser) Write(conn *TCPConn, args ...[]byte) error {
|
||||
return errors.New("message too short")
|
||||
}
|
||||
|
||||
//msgLen -= 2
|
||||
//msg := make([]byte, uint32(p.lenMsgLen)+msgLen)
|
||||
msg := makeByteSlice(p.lenMsgLen+int(msgLen))
|
||||
// write len
|
||||
|
||||
@@ -18,7 +18,7 @@ type WSClient struct {
|
||||
AutoReconnect bool
|
||||
NewAgent func(*WSConn) Agent
|
||||
dialer websocket.Dialer
|
||||
conns WebsocketConnSet
|
||||
cons WebsocketConnSet
|
||||
wg sync.WaitGroup
|
||||
closeFlag bool
|
||||
}
|
||||
@@ -59,11 +59,11 @@ func (client *WSClient) init() {
|
||||
if client.NewAgent == nil {
|
||||
log.Fatal("NewAgent must not be nil")
|
||||
}
|
||||
if client.conns != nil {
|
||||
if client.cons != nil {
|
||||
log.Fatal("client is running")
|
||||
}
|
||||
|
||||
client.conns = make(WebsocketConnSet)
|
||||
client.cons = make(WebsocketConnSet)
|
||||
client.closeFlag = false
|
||||
client.dialer = websocket.Dialer{
|
||||
HandshakeTimeout: client.HandshakeTimeout,
|
||||
@@ -99,7 +99,7 @@ reconnect:
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
client.conns[conn] = struct{}{}
|
||||
client.cons[conn] = struct{}{}
|
||||
client.Unlock()
|
||||
|
||||
wsConn := newWSConn(conn, client.PendingWriteNum, client.MaxMsgLen)
|
||||
@@ -109,7 +109,7 @@ reconnect:
|
||||
// cleanup
|
||||
wsConn.Close()
|
||||
client.Lock()
|
||||
delete(client.conns, conn)
|
||||
delete(client.cons, conn)
|
||||
client.Unlock()
|
||||
agent.OnClose()
|
||||
|
||||
@@ -122,10 +122,10 @@ reconnect:
|
||||
func (client *WSClient) Close() {
|
||||
client.Lock()
|
||||
client.closeFlag = true
|
||||
for conn := range client.conns {
|
||||
for conn := range client.cons {
|
||||
conn.Close()
|
||||
}
|
||||
client.conns = nil
|
||||
client.cons = nil
|
||||
client.Unlock()
|
||||
|
||||
client.wg.Wait()
|
||||
|
||||
@@ -133,6 +133,5 @@ func (wsConn *WSConn) WriteMsg(args ...[]byte) error {
|
||||
}
|
||||
|
||||
wsConn.doWrite(msg)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
30
node/node.go
30
node/node.go
@@ -9,17 +9,17 @@ import (
|
||||
"github.com/duanhf2012/origin/service"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
_ "net/http/pprof"
|
||||
)
|
||||
|
||||
var closeSig chan bool
|
||||
var sigs chan os.Signal
|
||||
var sig chan os.Signal
|
||||
var nodeId int
|
||||
var preSetupService []service.IService //预安装
|
||||
var profilerInterval time.Duration
|
||||
@@ -28,8 +28,8 @@ var bValid bool
|
||||
func init() {
|
||||
|
||||
closeSig = make(chan bool,1)
|
||||
sigs = make(chan os.Signal, 3)
|
||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM,syscall.Signal(10))
|
||||
sig = make(chan os.Signal, 3)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM,syscall.Signal(10))
|
||||
|
||||
console.RegisterCommandBool("help",false,"This help.",usage)
|
||||
console.RegisterCommandString("start","","Run originserver.",startNode)
|
||||
@@ -88,12 +88,12 @@ func getRunProcessPid() (int,error) {
|
||||
return 0,err
|
||||
}
|
||||
|
||||
pidbyte,errs := ioutil.ReadAll(f)
|
||||
pidByte,errs := ioutil.ReadAll(f)
|
||||
if errs!=nil {
|
||||
return 0,errs
|
||||
}
|
||||
|
||||
return strconv.Atoi(string(pidbyte))
|
||||
return strconv.Atoi(string(pidByte))
|
||||
}
|
||||
|
||||
func writeProcessPid() {
|
||||
@@ -171,14 +171,14 @@ func startNode(args interface{}) error{
|
||||
return nil
|
||||
}
|
||||
|
||||
sparam := strings.Split(param,"=")
|
||||
if len(sparam) != 2 {
|
||||
sParam := strings.Split(param,"=")
|
||||
if len(sParam) != 2 {
|
||||
return fmt.Errorf("invalid option %s",param)
|
||||
}
|
||||
if sparam[0]!="nodeid" {
|
||||
if sParam[0]!="nodeid" {
|
||||
return fmt.Errorf("invalid option %s",param)
|
||||
}
|
||||
nodeId,err:= strconv.Atoi(sparam[1])
|
||||
nodeId,err:= strconv.Atoi(sParam[1])
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid option %s",param)
|
||||
}
|
||||
@@ -204,7 +204,7 @@ func startNode(args interface{}) error{
|
||||
}
|
||||
for bRun {
|
||||
select {
|
||||
case <-sigs:
|
||||
case <-sig:
|
||||
log.Debug("receipt stop signal.")
|
||||
bRun = false
|
||||
case <- pProfilerTicker.C:
|
||||
@@ -228,12 +228,12 @@ func Setup(s ...service.IService) {
|
||||
}
|
||||
}
|
||||
|
||||
func GetService(servicename string) service.IService {
|
||||
return service.GetService(servicename)
|
||||
func GetService(serviceName string) service.IService {
|
||||
return service.GetService(serviceName)
|
||||
}
|
||||
|
||||
func SetConfigDir(configdir string){
|
||||
cluster.SetConfigDir(configdir)
|
||||
func SetConfigDir(configDir string){
|
||||
cluster.SetConfigDir(configDir)
|
||||
}
|
||||
|
||||
func SetSysLog(strLevel string, pathname string, flag int){
|
||||
|
||||
@@ -9,10 +9,13 @@ import (
|
||||
)
|
||||
|
||||
//最大超长时间,一般可以认为是死锁或者死循环,或者极差的性能问题
|
||||
var Default_MaxOverTime time.Duration = 5*time.Second
|
||||
var DefaultMaxOvertime time.Duration = 5*time.Second
|
||||
//超过该时间将会监控报告
|
||||
var Default_OverTime time.Duration = 10*time.Millisecond
|
||||
var Default_MaxRecordNum int = 100 //最大记录条数
|
||||
var DefaultOvertime time.Duration = 10*time.Millisecond
|
||||
var DefaultMaxRecordNum int = 100 //最大记录条数
|
||||
var mapProfiler map[string]*Profiler
|
||||
type ReportFunType func(name string,callNum int,costTime time.Duration,record *list.List)
|
||||
var reportFunc ReportFunType =DefaultReportFunction
|
||||
|
||||
type Element struct {
|
||||
tagName string
|
||||
@@ -21,24 +24,21 @@ type Element struct {
|
||||
|
||||
type RecordType int
|
||||
const (
|
||||
MaxOverTime_Type = 1
|
||||
OverTime_Type =2
|
||||
MaxOvertimeType = 1
|
||||
OvertimeType =2
|
||||
)
|
||||
|
||||
|
||||
type Record struct {
|
||||
RType RecordType
|
||||
CostTime time.Duration
|
||||
RecordName string
|
||||
}
|
||||
|
||||
|
||||
type Analyzer struct {
|
||||
elem *list.Element
|
||||
profiler *Profiler
|
||||
}
|
||||
|
||||
|
||||
type Profiler struct {
|
||||
stack *list.List //Element
|
||||
stackLocker sync.RWMutex
|
||||
@@ -53,8 +53,6 @@ type Profiler struct {
|
||||
maxRecordNum int
|
||||
}
|
||||
|
||||
var mapProfiler map[string]*Profiler
|
||||
|
||||
func init(){
|
||||
mapProfiler = map[string]*Profiler{}
|
||||
}
|
||||
@@ -64,7 +62,7 @@ func RegProfiler(profilerName string) *Profiler {
|
||||
return nil
|
||||
}
|
||||
|
||||
pProfiler := &Profiler{stack:list.New(),record:list.New(),maxOverTime:Default_MaxOverTime,overTime:Default_OverTime}
|
||||
pProfiler := &Profiler{stack:list.New(),record:list.New(),maxOverTime: DefaultMaxOvertime,overTime: DefaultOvertime}
|
||||
mapProfiler[profilerName] =pProfiler
|
||||
return pProfiler
|
||||
}
|
||||
@@ -90,7 +88,6 @@ func (slf *Profiler) Push(tag string) *Analyzer{
|
||||
return &Analyzer{elem:pElem,profiler:slf}
|
||||
}
|
||||
|
||||
|
||||
func (slf *Profiler) check(pElem *Element) (*Record,time.Duration) {
|
||||
if pElem == nil {
|
||||
return nil,0
|
||||
@@ -102,13 +99,13 @@ func (slf *Profiler) check(pElem *Element) (*Record,time.Duration) {
|
||||
}
|
||||
|
||||
record := Record{
|
||||
RType: OverTime_Type,
|
||||
RType: OvertimeType,
|
||||
CostTime: subTm,
|
||||
RecordName: pElem.tagName,
|
||||
}
|
||||
|
||||
if subTm>slf.maxOverTime {
|
||||
record.RType = MaxOverTime_Type
|
||||
record.RType = MaxOvertimeType
|
||||
}
|
||||
|
||||
return &record,subTm
|
||||
@@ -129,7 +126,7 @@ func (slf *Analyzer) Pop(){
|
||||
}
|
||||
|
||||
func (slf *Profiler) pushRecordLog(record *Record){
|
||||
if slf.record.Len()>=Default_MaxRecordNum{
|
||||
if slf.record.Len()>= DefaultMaxRecordNum {
|
||||
front := slf.stack.Front()
|
||||
if front!=nil {
|
||||
slf.stack.Remove(front)
|
||||
@@ -139,12 +136,6 @@ func (slf *Profiler) pushRecordLog(record *Record){
|
||||
slf.record.PushBack(record)
|
||||
}
|
||||
|
||||
|
||||
|
||||
type ReportFunType func(name string,callNum int,costTime time.Duration,record *list.List)
|
||||
|
||||
var reportFunc ReportFunType =DefaultReportFunction
|
||||
|
||||
func SetReportFunction(reportFun ReportFunType) {
|
||||
reportFunc = reportFun
|
||||
}
|
||||
@@ -166,7 +157,7 @@ func DefaultReportFunction(name string,callNum int,costTime time.Duration,record
|
||||
var strTypes string
|
||||
for elem!=nil {
|
||||
pRecord := elem.Value.(*Record)
|
||||
if pRecord.RType == MaxOverTime_Type {
|
||||
if pRecord.RType == MaxOvertimeType {
|
||||
strTypes = "too slow process"
|
||||
}else{
|
||||
strTypes = "slow process"
|
||||
|
||||
222
rpc/client.go
222
rpc/client.go
@@ -18,146 +18,146 @@ type Client struct {
|
||||
network.TCPClient
|
||||
conn *network.TCPConn
|
||||
|
||||
pendingLock sync.RWMutex
|
||||
startSeq uint64
|
||||
pending map[uint64]*list.Element
|
||||
pendingTimer *list.List
|
||||
callRpcTimerout time.Duration
|
||||
pendingLock sync.RWMutex
|
||||
startSeq uint64
|
||||
pending map[uint64]*list.Element
|
||||
pendingTimer *list.List
|
||||
callRpcTimeout time.Duration
|
||||
maxCheckCallRpcCount int
|
||||
}
|
||||
|
||||
func (slf *Client) NewClientAgent(conn *network.TCPConn) network.Agent {
|
||||
slf.conn = conn
|
||||
slf.ResetPending()
|
||||
func (client *Client) NewClientAgent(conn *network.TCPConn) network.Agent {
|
||||
client.conn = conn
|
||||
client.ResetPending()
|
||||
|
||||
return slf
|
||||
return client
|
||||
}
|
||||
|
||||
func (slf *Client) Connect(addr string) error {
|
||||
slf.Addr = addr
|
||||
slf.maxCheckCallRpcCount = 100
|
||||
slf.callRpcTimerout = 15*time.Second
|
||||
slf.ConnNum = 1
|
||||
slf.ConnectInterval = time.Second*2
|
||||
slf.PendingWriteNum = 2000000
|
||||
slf.AutoReconnect = true
|
||||
slf.LenMsgLen = 2
|
||||
slf.MinMsgLen = 2
|
||||
slf.MaxMsgLen = math.MaxUint16
|
||||
slf.NewAgent = slf.NewClientAgent
|
||||
slf.LittleEndian = LittleEndian
|
||||
slf.ResetPending()
|
||||
go slf.startCheckRpcCallTimer()
|
||||
func (client *Client) Connect(addr string) error {
|
||||
client.Addr = addr
|
||||
client.maxCheckCallRpcCount = 100
|
||||
client.callRpcTimeout = 15*time.Second
|
||||
client.ConnNum = 1
|
||||
client.ConnectInterval = time.Second*2
|
||||
client.PendingWriteNum = 2000000
|
||||
client.AutoReconnect = true
|
||||
client.LenMsgLen = 2
|
||||
client.MinMsgLen = 2
|
||||
client.MaxMsgLen = math.MaxUint16
|
||||
client.NewAgent = client.NewClientAgent
|
||||
client.LittleEndian = LittleEndian
|
||||
client.ResetPending()
|
||||
go client.startCheckRpcCallTimer()
|
||||
if addr == "" {
|
||||
slf.bSelfNode = true
|
||||
client.bSelfNode = true
|
||||
return nil
|
||||
}
|
||||
|
||||
slf.Start()
|
||||
client.Start()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *Client) startCheckRpcCallTimer(){
|
||||
func (client *Client) startCheckRpcCallTimer(){
|
||||
tick :=time.NewTicker( 3 * time.Second)
|
||||
|
||||
for{
|
||||
select {
|
||||
case <- tick.C:
|
||||
slf.checkRpcCallTimerout()
|
||||
client.checkRpcCallTimeout()
|
||||
}
|
||||
}
|
||||
|
||||
tick.Stop()
|
||||
}
|
||||
|
||||
func (slf *Client) makeCallFail(call *Call){
|
||||
func (client *Client) makeCallFail(call *Call){
|
||||
if call.callback!=nil && call.callback.IsValid() {
|
||||
call.rpcHandler.(*RpcHandler).callResponeCallBack<-call
|
||||
call.rpcHandler.(*RpcHandler).callResponseCallBack <-call
|
||||
}else{
|
||||
call.done <- call
|
||||
}
|
||||
slf.removePending(call.Seq)
|
||||
client.removePending(call.Seq)
|
||||
}
|
||||
|
||||
func (slf *Client) checkRpcCallTimerout(){
|
||||
tnow := time.Now()
|
||||
func (client *Client) checkRpcCallTimeout(){
|
||||
now := time.Now()
|
||||
|
||||
for i:=0;i<slf.maxCheckCallRpcCount;i++ {
|
||||
slf.pendingLock.Lock()
|
||||
pElem := slf.pendingTimer.Front()
|
||||
for i:=0;i< client.maxCheckCallRpcCount;i++ {
|
||||
client.pendingLock.Lock()
|
||||
pElem := client.pendingTimer.Front()
|
||||
if pElem == nil {
|
||||
slf.pendingLock.Unlock()
|
||||
client.pendingLock.Unlock()
|
||||
break
|
||||
}
|
||||
pCall := pElem.Value.(*Call)
|
||||
if tnow.Sub(pCall.calltime) > slf.callRpcTimerout {
|
||||
pCall.Err = fmt.Errorf("RPC call takes more than %d seconds!",slf.callRpcTimerout/time.Second)
|
||||
slf.makeCallFail(pCall)
|
||||
slf.pendingLock.Unlock()
|
||||
if now.Sub(pCall.callTime) > client.callRpcTimeout {
|
||||
pCall.Err = fmt.Errorf("RPC call takes more than %d seconds!", client.callRpcTimeout/time.Second)
|
||||
client.makeCallFail(pCall)
|
||||
client.pendingLock.Unlock()
|
||||
continue
|
||||
}
|
||||
slf.pendingLock.Unlock()
|
||||
client.pendingLock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Client) ResetPending(){
|
||||
slf.pendingLock.Lock()
|
||||
if slf.pending != nil {
|
||||
for _,v := range slf.pending {
|
||||
func (client *Client) ResetPending(){
|
||||
client.pendingLock.Lock()
|
||||
if client.pending != nil {
|
||||
for _,v := range client.pending {
|
||||
v.Value.(*Call).Err = fmt.Errorf("node is disconnect.")
|
||||
v.Value.(*Call).done <- v.Value.(*Call)
|
||||
}
|
||||
}
|
||||
|
||||
slf.pending = map[uint64]*list.Element{}
|
||||
slf.pendingTimer = list.New()
|
||||
slf.pendingLock.Unlock()
|
||||
client.pending = map[uint64]*list.Element{}
|
||||
client.pendingTimer = list.New()
|
||||
client.pendingLock.Unlock()
|
||||
}
|
||||
|
||||
func (slf *Client) AddPending(call *Call){
|
||||
slf.pendingLock.Lock()
|
||||
call.calltime = time.Now()
|
||||
elemTimer := slf.pendingTimer.PushBack(call)
|
||||
slf.pending[call.Seq] = elemTimer//如果下面发送失败,将会一一直存在这里
|
||||
slf.pendingLock.Unlock()
|
||||
func (client *Client) AddPending(call *Call){
|
||||
client.pendingLock.Lock()
|
||||
call.callTime = time.Now()
|
||||
elemTimer := client.pendingTimer.PushBack(call)
|
||||
client.pending[call.Seq] = elemTimer //如果下面发送失败,将会一一直存在这里
|
||||
client.pendingLock.Unlock()
|
||||
}
|
||||
|
||||
func (slf *Client) RemovePending(seq uint64) *Call{
|
||||
slf.pendingLock.Lock()
|
||||
call := slf.removePending(seq)
|
||||
slf.pendingLock.Unlock()
|
||||
func (client *Client) RemovePending(seq uint64) *Call{
|
||||
client.pendingLock.Lock()
|
||||
call := client.removePending(seq)
|
||||
client.pendingLock.Unlock()
|
||||
return call
|
||||
}
|
||||
|
||||
func (slf *Client) removePending(seq uint64) *Call{
|
||||
v,ok := slf.pending[seq]
|
||||
func (client *Client) removePending(seq uint64) *Call{
|
||||
v,ok := client.pending[seq]
|
||||
if ok == false{
|
||||
return nil
|
||||
}
|
||||
slf.pendingTimer.Remove(v)
|
||||
delete(slf.pending,seq)
|
||||
client.pendingTimer.Remove(v)
|
||||
delete(client.pending,seq)
|
||||
return v.Value.(*Call)
|
||||
}
|
||||
|
||||
|
||||
func (slf *Client) FindPending(seq uint64) *Call{
|
||||
slf.pendingLock.Lock()
|
||||
v,ok := slf.pending[seq]
|
||||
func (client *Client) FindPending(seq uint64) *Call{
|
||||
client.pendingLock.Lock()
|
||||
v,ok := client.pending[seq]
|
||||
if ok == false {
|
||||
slf.pendingLock.Unlock()
|
||||
client.pendingLock.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
pCall := v.Value.(*Call)
|
||||
slf.pendingLock.Unlock()
|
||||
client.pendingLock.Unlock()
|
||||
|
||||
return pCall
|
||||
}
|
||||
|
||||
func (slf *Client) generateSeq() uint64{
|
||||
return atomic.AddUint64(&slf.startSeq,1)
|
||||
func (client *Client) generateSeq() uint64{
|
||||
return atomic.AddUint64(&client.startSeq,1)
|
||||
}
|
||||
|
||||
func (slf *Client) AsycCall(rpcHandler IRpcHandler,serviceMethod string,callback reflect.Value, args interface{},replyParam interface{}) error {
|
||||
func (client *Client) AsyncCall(rpcHandler IRpcHandler,serviceMethod string,callback reflect.Value, args interface{},replyParam interface{}) error {
|
||||
call := MakeCall()
|
||||
call.Reply = replyParam
|
||||
call.callback = &callback
|
||||
@@ -173,69 +173,69 @@ func (slf *Client) AsycCall(rpcHandler IRpcHandler,serviceMethod string,callback
|
||||
|
||||
request := &RpcRequest{}
|
||||
call.Arg = args
|
||||
call.Seq = slf.generateSeq()
|
||||
request.RpcRequestData = processor.MakeRpcRequest(slf.startSeq,serviceMethod,false,InParam,nil)
|
||||
slf.AddPending(call)
|
||||
call.Seq = client.generateSeq()
|
||||
request.RpcRequestData = processor.MakeRpcRequest(client.startSeq,serviceMethod,false,InParam,nil)
|
||||
client.AddPending(call)
|
||||
|
||||
bytes,err := processor.Marshal(request.RpcRequestData)
|
||||
processor.ReleaseRpcRequest(request.RpcRequestData)
|
||||
if err != nil {
|
||||
slf.RemovePending(call.Seq)
|
||||
client.RemovePending(call.Seq)
|
||||
ReleaseCall(call)
|
||||
return err
|
||||
}
|
||||
|
||||
if slf.conn == nil {
|
||||
slf.RemovePending(call.Seq)
|
||||
if client.conn == nil {
|
||||
client.RemovePending(call.Seq)
|
||||
ReleaseCall(call)
|
||||
return fmt.Errorf("Rpc server is disconnect,call %s is fail!",serviceMethod)
|
||||
}
|
||||
|
||||
err = slf.conn.WriteMsg([]byte{uint8(processorType)},bytes)
|
||||
err = client.conn.WriteMsg([]byte{uint8(processorType)},bytes)
|
||||
if err != nil {
|
||||
slf.RemovePending(call.Seq)
|
||||
client.RemovePending(call.Seq)
|
||||
ReleaseCall(call)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *Client) RawGo(processor IRpcProcessor,noReply bool,serviceMethod string,args []byte,additionParam interface{},reply interface{}) *Call {
|
||||
func (client *Client) RawGo(processor IRpcProcessor,noReply bool,serviceMethod string,args []byte,additionParam interface{},reply interface{}) *Call {
|
||||
call := MakeCall()
|
||||
call.ServiceMethod = serviceMethod
|
||||
call.Reply = reply
|
||||
|
||||
request := &RpcRequest{}
|
||||
call.Arg = args
|
||||
call.Seq = slf.generateSeq()
|
||||
call.Seq = client.generateSeq()
|
||||
if noReply == false {
|
||||
slf.AddPending(call)
|
||||
client.AddPending(call)
|
||||
}
|
||||
request.RpcRequestData = processor.MakeRpcRequest(slf.startSeq,serviceMethod,noReply,args,additionParam)
|
||||
request.RpcRequestData = processor.MakeRpcRequest(client.startSeq,serviceMethod,noReply,args,additionParam)
|
||||
bytes,err := processor.Marshal(request.RpcRequestData)
|
||||
processor.ReleaseRpcRequest(request.RpcRequestData)
|
||||
if err != nil {
|
||||
call.Err = err
|
||||
slf.RemovePending(call.Seq)
|
||||
client.RemovePending(call.Seq)
|
||||
return call
|
||||
}
|
||||
|
||||
if slf.conn == nil {
|
||||
if client.conn == nil {
|
||||
call.Err = fmt.Errorf("call %s is fail,rpc client is disconnect.",serviceMethod)
|
||||
slf.RemovePending(call.Seq)
|
||||
client.RemovePending(call.Seq)
|
||||
return call
|
||||
}
|
||||
|
||||
err = slf.conn.WriteMsg([]byte{uint8(processor.GetProcessorType())},bytes)
|
||||
err = client.conn.WriteMsg([]byte{uint8(processor.GetProcessorType())},bytes)
|
||||
if err != nil {
|
||||
slf.RemovePending(call.Seq)
|
||||
client.RemovePending(call.Seq)
|
||||
call.Err = err
|
||||
}
|
||||
|
||||
return call
|
||||
}
|
||||
|
||||
func (slf *Client) Go(noReply bool,serviceMethod string, args interface{},reply interface{}) *Call {
|
||||
func (client *Client) Go(noReply bool,serviceMethod string, args interface{},reply interface{}) *Call {
|
||||
_,processor := GetProcessorType(args)
|
||||
InParam,err := processor.Marshal(args)
|
||||
if err != nil {
|
||||
@@ -243,10 +243,10 @@ func (slf *Client) Go(noReply bool,serviceMethod string, args interface{},reply
|
||||
call.Err = err
|
||||
}
|
||||
|
||||
return slf.RawGo(processor,noReply,serviceMethod,InParam,nil,reply)
|
||||
return client.RawGo(processor,noReply,serviceMethod,InParam,nil,reply)
|
||||
}
|
||||
|
||||
func (slf *Client) Run(){
|
||||
func (client *Client) Run(){
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 4096)
|
||||
@@ -257,62 +257,62 @@ func (slf *Client) Run(){
|
||||
}()
|
||||
|
||||
for {
|
||||
bytes,err := slf.conn.ReadMsg()
|
||||
bytes,err := client.conn.ReadMsg()
|
||||
if err != nil {
|
||||
log.Error("rpcClient %s ReadMsg error:%+v",slf.Addr,err)
|
||||
log.Error("rpcClient %s ReadMsg error:%+v", client.Addr,err)
|
||||
return
|
||||
}
|
||||
|
||||
processor := GetProcessor(uint8(bytes[0]))
|
||||
if processor==nil {
|
||||
slf.conn.ReleaseReadMsg(bytes)
|
||||
log.Error("rpcClient %s ReadMsg head error:%+v",slf.Addr,err)
|
||||
client.conn.ReleaseReadMsg(bytes)
|
||||
log.Error("rpcClient %s ReadMsg head error:%+v", client.Addr,err)
|
||||
return
|
||||
}
|
||||
|
||||
//1.解析head
|
||||
respone := &RpcResponse{}
|
||||
respone.RpcResponeData =processor.MakeRpcResponse(0,nil,nil)
|
||||
respone.RpcResponseData =processor.MakeRpcResponse(0,nil,nil)
|
||||
|
||||
err = processor.Unmarshal(bytes[1:],respone.RpcResponeData)
|
||||
slf.conn.ReleaseReadMsg(bytes)
|
||||
err = processor.Unmarshal(bytes[1:],respone.RpcResponseData)
|
||||
client.conn.ReleaseReadMsg(bytes)
|
||||
if err != nil {
|
||||
processor.ReleaseRpcRespose(respone.RpcResponeData)
|
||||
processor.ReleaseRpcRespose(respone.RpcResponseData)
|
||||
log.Error("rpcClient Unmarshal head error,error:%+v",err)
|
||||
continue
|
||||
}
|
||||
|
||||
v := slf.RemovePending(respone.RpcResponeData.GetSeq())
|
||||
v := client.RemovePending(respone.RpcResponseData.GetSeq())
|
||||
if v == nil {
|
||||
log.Error("rpcClient cannot find seq %d in pending",respone.RpcResponeData.GetSeq())
|
||||
log.Error("rpcClient cannot find seq %d in pending",respone.RpcResponseData.GetSeq())
|
||||
}else {
|
||||
v.Err = nil
|
||||
if len(respone.RpcResponeData.GetReply()) >0 {
|
||||
err = processor.Unmarshal(respone.RpcResponeData.GetReply(),v.Reply)
|
||||
if len(respone.RpcResponseData.GetReply()) >0 {
|
||||
err = processor.Unmarshal(respone.RpcResponseData.GetReply(),v.Reply)
|
||||
if err != nil {
|
||||
log.Error("rpcClient Unmarshal body error,error:%+v",err)
|
||||
v.Err = err
|
||||
}
|
||||
}
|
||||
|
||||
if respone.RpcResponeData.GetErr() != nil {
|
||||
v.Err= respone.RpcResponeData.GetErr()
|
||||
if respone.RpcResponseData.GetErr() != nil {
|
||||
v.Err= respone.RpcResponseData.GetErr()
|
||||
}
|
||||
|
||||
if v.callback!=nil && v.callback.IsValid() {
|
||||
v.rpcHandler.(*RpcHandler).callResponeCallBack<-v
|
||||
v.rpcHandler.(*RpcHandler).callResponseCallBack <-v
|
||||
}else{
|
||||
v.done <- v
|
||||
}
|
||||
}
|
||||
|
||||
processor.ReleaseRpcRespose(respone.RpcResponeData)
|
||||
processor.ReleaseRpcRespose(respone.RpcResponseData)
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Client) OnClose(){
|
||||
func (client *Client) OnClose(){
|
||||
}
|
||||
|
||||
func (slf *Client) IsConnected() bool {
|
||||
return slf.conn!=nil && slf.conn.IsConnected()==true
|
||||
func (client *Client) IsConnected() bool {
|
||||
return client.conn!=nil && client.conn.IsConnected()==true
|
||||
}
|
||||
@@ -20,7 +20,6 @@ type JsonRpcRequestData struct {
|
||||
AdditionParam interface{}
|
||||
}
|
||||
|
||||
|
||||
type JsonRpcResponseData struct {
|
||||
//head
|
||||
Seq uint64 // sequence number chosen by client
|
||||
@@ -30,14 +29,11 @@ type JsonRpcResponseData struct {
|
||||
Reply []byte
|
||||
}
|
||||
|
||||
|
||||
var rpcJsonResponeDataPool sync.Pool
|
||||
var rpcJsonResponseDataPool sync.Pool
|
||||
var rpcJsonRequestDataPool sync.Pool
|
||||
|
||||
|
||||
|
||||
func init(){
|
||||
rpcJsonResponeDataPool.New = func()interface{}{
|
||||
rpcJsonResponseDataPool.New = func()interface{}{
|
||||
return &JsonRpcResponseData{}
|
||||
}
|
||||
|
||||
@@ -46,16 +42,15 @@ func init(){
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) Marshal(v interface{}) ([]byte, error){
|
||||
return json.Marshal(v)
|
||||
func (jsonProcessor *JsonProcessor) Marshal(v interface{}) ([]byte, error){
|
||||
return jsonProcessor.Marshal(v)
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) Unmarshal(data []byte, v interface{}) error{
|
||||
func (jsonProcessor *JsonProcessor) Unmarshal(data []byte, v interface{}) error{
|
||||
return json.Unmarshal(data,v)
|
||||
}
|
||||
|
||||
|
||||
func (slf *JsonProcessor) MakeRpcRequest(seq uint64,serviceMethod string,noReply bool,inParam []byte,additionParam interface{}) IRpcRequestData{
|
||||
func (jsonProcessor *JsonProcessor) MakeRpcRequest(seq uint64,serviceMethod string,noReply bool,inParam []byte,additionParam interface{}) IRpcRequestData{
|
||||
jsonRpcRequestData := rpcJsonRequestDataPool.Get().(*JsonRpcRequestData)
|
||||
jsonRpcRequestData.Seq = seq
|
||||
jsonRpcRequestData.ServiceMethod = serviceMethod
|
||||
@@ -65,75 +60,72 @@ func (slf *JsonProcessor) MakeRpcRequest(seq uint64,serviceMethod string,noReply
|
||||
return jsonRpcRequestData
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) MakeRpcResponse(seq uint64,err *RpcError,reply []byte) IRpcResponseData {
|
||||
jsonRpcResponseData := rpcJsonResponeDataPool.Get().(*JsonRpcResponseData)
|
||||
func (jsonProcessor *JsonProcessor) MakeRpcResponse(seq uint64,err *RpcError,reply []byte) IRpcResponseData {
|
||||
jsonRpcResponseData := rpcJsonResponseDataPool.Get().(*JsonRpcResponseData)
|
||||
jsonRpcResponseData.Seq = seq
|
||||
jsonRpcResponseData.Err = err.Error()
|
||||
jsonRpcResponseData.Reply = reply
|
||||
return jsonRpcResponseData
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) ReleaseRpcRequest(rpcRequestData IRpcRequestData){
|
||||
func (jsonProcessor *JsonProcessor) ReleaseRpcRequest(rpcRequestData IRpcRequestData){
|
||||
rpcJsonRequestDataPool.Put(rpcRequestData)
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) ReleaseRpcRespose(rpcRequestData IRpcResponseData){
|
||||
rpcJsonResponeDataPool.Put(rpcRequestData)
|
||||
func (jsonProcessor *JsonProcessor) ReleaseRpcRespose(rpcRequestData IRpcResponseData){
|
||||
rpcJsonResponseDataPool.Put(rpcRequestData)
|
||||
}
|
||||
|
||||
func (slf *JsonProcessor) IsParse(param interface{}) bool {
|
||||
func (jsonProcessor *JsonProcessor) IsParse(param interface{}) bool {
|
||||
_,err := json.Marshal(param)
|
||||
return err==nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *JsonProcessor) GetProcessorType() RpcProcessorType{
|
||||
return RPC_PROCESSOR_JSON
|
||||
func (jsonProcessor *JsonProcessor) GetProcessorType() RpcProcessorType{
|
||||
return RpcProcessorJson
|
||||
}
|
||||
|
||||
|
||||
func (slf *JsonRpcRequestData) IsNoReply() bool{
|
||||
return slf.NoReply
|
||||
func (jsonRpcRequestData *JsonRpcRequestData) IsNoReply() bool{
|
||||
return jsonRpcRequestData.NoReply
|
||||
}
|
||||
|
||||
func (slf *JsonRpcRequestData) GetSeq() uint64{
|
||||
return slf.Seq
|
||||
func (jsonRpcRequestData *JsonRpcRequestData) GetSeq() uint64{
|
||||
return jsonRpcRequestData.Seq
|
||||
}
|
||||
|
||||
func (slf *JsonRpcRequestData) GetServiceMethod() string{
|
||||
return slf.ServiceMethod
|
||||
func (jsonRpcRequestData *JsonRpcRequestData) GetServiceMethod() string{
|
||||
return jsonRpcRequestData.ServiceMethod
|
||||
}
|
||||
|
||||
func (slf *JsonRpcRequestData) GetInParam() []byte{
|
||||
return slf.InParam
|
||||
func (jsonRpcRequestData *JsonRpcRequestData) GetInParam() []byte{
|
||||
return jsonRpcRequestData.InParam
|
||||
}
|
||||
|
||||
func (slf *JsonRpcRequestData) GetParamValue() interface{}{
|
||||
return slf.AdditionParam
|
||||
func (jsonRpcRequestData *JsonRpcRequestData) GetParamValue() interface{}{
|
||||
return jsonRpcRequestData.AdditionParam
|
||||
}
|
||||
|
||||
func (slf *JsonRpcRequestData) GetAdditionParams() IRawAdditionParam{
|
||||
return slf
|
||||
func (jsonRpcRequestData *JsonRpcRequestData) GetAdditionParams() IRawAdditionParam{
|
||||
return jsonRpcRequestData
|
||||
}
|
||||
|
||||
|
||||
func (slf *JsonRpcResponseData) GetSeq() uint64 {
|
||||
return slf.Seq
|
||||
func (jsonRpcResponseData *JsonRpcResponseData) GetSeq() uint64 {
|
||||
return jsonRpcResponseData.Seq
|
||||
}
|
||||
|
||||
func (slf *JsonRpcResponseData) GetErr() *RpcError {
|
||||
if slf.Err == ""{
|
||||
func (jsonRpcResponseData *JsonRpcResponseData) GetErr() *RpcError {
|
||||
if jsonRpcResponseData.Err == ""{
|
||||
return nil
|
||||
}
|
||||
|
||||
return Errorf(slf.Err)
|
||||
return Errorf(jsonRpcResponseData.Err)
|
||||
}
|
||||
|
||||
|
||||
func (slf *JsonRpcResponseData) GetReply() []byte{
|
||||
return slf.Reply
|
||||
func (jsonRpcResponseData *JsonRpcResponseData) GetReply() []byte{
|
||||
return jsonRpcResponseData.Reply
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ import (
|
||||
type PBProcessor struct {
|
||||
}
|
||||
|
||||
var rpcPbResponeDataPool sync.Pool
|
||||
var rpcPbResponseDataPool sync.Pool
|
||||
var rpcPbRequestDataPool sync.Pool
|
||||
|
||||
|
||||
func init(){
|
||||
rpcPbResponeDataPool.New = func()interface{}{
|
||||
rpcPbResponseDataPool.New = func()interface{}{
|
||||
return &PBRpcResponseData{}
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ func (slf *PBProcessor) MakeRpcRequest(seq uint64,serviceMethod string,noReply b
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) MakeRpcResponse(seq uint64,err *RpcError,reply []byte) IRpcResponseData {
|
||||
pPBRpcResponseData := rpcPbResponeDataPool.Get().(*PBRpcResponseData)
|
||||
pPBRpcResponseData := rpcPbResponseDataPool.Get().(*PBRpcResponseData)
|
||||
pPBRpcResponseData.MakeRespone(seq,err,reply)
|
||||
return pPBRpcResponseData
|
||||
}
|
||||
@@ -125,7 +125,7 @@ func (slf *PBProcessor) ReleaseRpcRequest(rpcRequestData IRpcRequestData){
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) ReleaseRpcRespose(rpcRequestData IRpcResponseData){
|
||||
rpcPbResponeDataPool.Put(rpcRequestData)
|
||||
rpcPbResponseDataPool.Put(rpcRequestData)
|
||||
}
|
||||
|
||||
func (slf *PBProcessor) IsParse(param interface{}) bool {
|
||||
@@ -135,7 +135,7 @@ func (slf *PBProcessor) IsParse(param interface{}) bool {
|
||||
|
||||
|
||||
func (slf *PBProcessor) GetProcessorType() RpcProcessorType{
|
||||
return RPC_PROCESSOR_PB
|
||||
return RpcProcessorPb
|
||||
}
|
||||
|
||||
|
||||
|
||||
123
rpc/rpc.go
123
rpc/rpc.go
@@ -19,22 +19,12 @@ type RpcRequest struct {
|
||||
}
|
||||
|
||||
type RpcResponse struct {
|
||||
RpcResponeData IRpcResponseData
|
||||
RpcResponseData IRpcResponseData
|
||||
}
|
||||
|
||||
func (slf *RpcRequest) Clear() *RpcRequest{
|
||||
slf.RpcRequestData = nil
|
||||
slf.localReply = nil
|
||||
slf.localParam = nil
|
||||
slf.requestHandle = nil
|
||||
slf.callback = nil
|
||||
return slf
|
||||
}
|
||||
|
||||
func (slf *RpcResponse) Clear() *RpcResponse{
|
||||
slf.RpcResponeData = nil
|
||||
return slf
|
||||
}
|
||||
var rpcResponsePool sync.Pool
|
||||
var rpcRequestPool sync.Pool
|
||||
var rpcCallPool sync.Pool
|
||||
|
||||
type IRawAdditionParam interface {
|
||||
GetParamValue() interface{}
|
||||
@@ -54,60 +44,30 @@ type IRpcResponseData interface {
|
||||
GetReply() []byte
|
||||
}
|
||||
|
||||
type RequestHandler func(Returns interface{},Err *RpcError)
|
||||
|
||||
type RawAdditionParamNull struct {
|
||||
}
|
||||
|
||||
func (slf *RawAdditionParamNull) GetParamValue() interface{}{
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
type Call struct {
|
||||
Seq uint64
|
||||
ServiceMethod string
|
||||
Arg interface{}
|
||||
Reply interface{}
|
||||
Respone *RpcResponse
|
||||
Err error
|
||||
done chan *Call // Strobes when call is complete.
|
||||
connid int
|
||||
callback *reflect.Value
|
||||
rpcHandler IRpcHandler
|
||||
calltime time.Time
|
||||
}
|
||||
|
||||
func (slf *Call) Clear() *Call{
|
||||
slf.Seq = 0
|
||||
slf.ServiceMethod = ""
|
||||
slf.Arg = nil
|
||||
slf.Reply = nil
|
||||
slf.Respone = nil
|
||||
slf.Err = nil
|
||||
slf.connid = 0
|
||||
slf.callback = nil
|
||||
slf.rpcHandler = nil
|
||||
return slf
|
||||
}
|
||||
|
||||
func (slf *Call) Done() *Call{
|
||||
return <-slf.done
|
||||
}
|
||||
|
||||
type RpcHandleFinder interface {
|
||||
FindRpcHandler(serviceMethod string) IRpcHandler
|
||||
}
|
||||
|
||||
type RequestHandler func(Returns interface{},Err *RpcError)
|
||||
type RawAdditionParamNull struct {
|
||||
}
|
||||
|
||||
var rpcResponePool sync.Pool
|
||||
var rpcRequestPool sync.Pool
|
||||
var rpcCallPool sync.Pool
|
||||
|
||||
|
||||
type Call struct {
|
||||
Seq uint64
|
||||
ServiceMethod string
|
||||
Arg interface{}
|
||||
Reply interface{}
|
||||
Response *RpcResponse
|
||||
Err error
|
||||
done chan *Call // Strobes when call is complete.
|
||||
connId int
|
||||
callback *reflect.Value
|
||||
rpcHandler IRpcHandler
|
||||
callTime time.Time
|
||||
}
|
||||
|
||||
func init(){
|
||||
rpcResponePool.New = func()interface{}{
|
||||
rpcResponsePool.New = func()interface{}{
|
||||
return &RpcResponse{}
|
||||
}
|
||||
|
||||
@@ -120,8 +80,39 @@ func init(){
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *RpcRequest) Clear() *RpcRequest{
|
||||
slf.RpcRequestData = nil
|
||||
slf.localReply = nil
|
||||
slf.localParam = nil
|
||||
slf.requestHandle = nil
|
||||
slf.callback = nil
|
||||
return slf
|
||||
}
|
||||
|
||||
func (rpcResponse *RpcResponse) Clear() *RpcResponse{
|
||||
rpcResponse.RpcResponseData = nil
|
||||
return rpcResponse
|
||||
}
|
||||
|
||||
func (call *Call) Clear() *Call{
|
||||
call.Seq = 0
|
||||
call.ServiceMethod = ""
|
||||
call.Arg = nil
|
||||
call.Reply = nil
|
||||
call.Response = nil
|
||||
call.Err = nil
|
||||
call.connId = 0
|
||||
call.callback = nil
|
||||
call.rpcHandler = nil
|
||||
return call
|
||||
}
|
||||
|
||||
func (call *Call) Done() *Call{
|
||||
return <-call.done
|
||||
}
|
||||
|
||||
func MakeRpcResponse() *RpcResponse{
|
||||
return rpcResponePool.Get().(*RpcResponse).Clear()
|
||||
return rpcResponsePool.Get().(*RpcResponse).Clear()
|
||||
}
|
||||
|
||||
func MakeRpcRequest() *RpcRequest{
|
||||
@@ -132,8 +123,8 @@ func MakeCall() *Call {
|
||||
return rpcCallPool.Get().(*Call).Clear()
|
||||
}
|
||||
|
||||
func ReleaseRpcResponse(rpcRespone *RpcResponse){
|
||||
rpcResponePool.Put(rpcRespone)
|
||||
func ReleaseRpcResponse(rpcResponse *RpcResponse){
|
||||
rpcResponsePool.Put(rpcResponse)
|
||||
}
|
||||
|
||||
func ReleaseRpcRequest(rpcRequest *RpcRequest){
|
||||
@@ -143,3 +134,7 @@ func ReleaseRpcRequest(rpcRequest *RpcRequest){
|
||||
func ReleaseCall(call *Call){
|
||||
rpcCallPool.Put(call)
|
||||
}
|
||||
|
||||
func (slf *RawAdditionParamNull) GetParamValue() interface{}{
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type FuncRpcClient func(nodeid int,serviceMethod string,client *[]*Client) error
|
||||
type FuncRpcClient func(nodeId int,serviceMethod string,client *[]*Client) error
|
||||
type FuncRpcServer func() (*Server)
|
||||
var NilError = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())
|
||||
|
||||
@@ -35,42 +35,40 @@ func ConvertError(e error) *RpcError{
|
||||
|
||||
func Errorf(format string, a ...interface{}) *RpcError {
|
||||
rpcErr := RpcError(fmt.Sprintf(format,a...))
|
||||
|
||||
return &rpcErr
|
||||
}
|
||||
|
||||
|
||||
type RpcMethodInfo struct {
|
||||
method reflect.Method
|
||||
iparam reflect.Value
|
||||
iInParam interface{}
|
||||
oParam reflect.Value
|
||||
iOutParam interface{}
|
||||
inParamValue reflect.Value
|
||||
inParam interface{}
|
||||
outParamValue reflect.Value
|
||||
additionParam reflect.Value
|
||||
//addition *IRawAdditionParam
|
||||
hashAdditionParam bool
|
||||
hasAdditionParam bool
|
||||
rpcProcessorType RpcProcessorType
|
||||
}
|
||||
|
||||
type RpcHandler struct {
|
||||
callRequest chan *RpcRequest
|
||||
rpcHandler IRpcHandler
|
||||
mapfunctons map[string]RpcMethodInfo
|
||||
callRequest chan *RpcRequest
|
||||
rpcHandler IRpcHandler
|
||||
mapFunctions map[string]RpcMethodInfo
|
||||
funcRpcClient FuncRpcClient
|
||||
funcRpcServer FuncRpcServer
|
||||
|
||||
callResponeCallBack chan *Call //异步返回的回调
|
||||
callResponseCallBack chan *Call //异步返回的回调
|
||||
}
|
||||
|
||||
type IRpcHandler interface {
|
||||
GetName() string
|
||||
InitRpcHandler(rpcHandler IRpcHandler,getClientFun FuncRpcClient,getServerFun FuncRpcServer)
|
||||
GetRpcHandler() IRpcHandler
|
||||
PushRequest(callinfo *RpcRequest) error
|
||||
PushRequest(callInfo *RpcRequest) error
|
||||
HandlerRpcRequest(request *RpcRequest)
|
||||
HandlerRpcResponeCB(call *Call)
|
||||
HandlerRpcResponseCB(call *Call)
|
||||
|
||||
GetRpcRequestChan() chan *RpcRequest
|
||||
GetRpcResponeChan() chan *Call
|
||||
GetRpcResponseChan() chan *Call
|
||||
CallMethod(ServiceMethod string,param interface{},reply interface{}) error
|
||||
|
||||
AsyncCall(serviceMethod string,args interface{},callback interface{}) error
|
||||
@@ -88,20 +86,20 @@ var rawAdditionParamValueNull reflect.Value
|
||||
func init(){
|
||||
rawAdditionParamValueNull = reflect.ValueOf(&RawAdditionParamNull{})
|
||||
}
|
||||
func (slf *RpcHandler) GetRpcHandler() IRpcHandler{
|
||||
return slf.rpcHandler
|
||||
func (handler *RpcHandler) GetRpcHandler() IRpcHandler{
|
||||
return handler.rpcHandler
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) InitRpcHandler(rpcHandler IRpcHandler,getClientFun FuncRpcClient,getServerFun FuncRpcServer) {
|
||||
slf.callRequest = make(chan *RpcRequest,1000000)
|
||||
slf.callResponeCallBack = make(chan *Call,1000000)
|
||||
func (handler *RpcHandler) InitRpcHandler(rpcHandler IRpcHandler,getClientFun FuncRpcClient,getServerFun FuncRpcServer) {
|
||||
handler.callRequest = make(chan *RpcRequest,1000000)
|
||||
handler.callResponseCallBack = make(chan *Call,1000000)
|
||||
|
||||
slf.rpcHandler = rpcHandler
|
||||
slf.mapfunctons = map[string]RpcMethodInfo{}
|
||||
slf.funcRpcClient = getClientFun
|
||||
slf.funcRpcServer = getServerFun
|
||||
handler.rpcHandler = rpcHandler
|
||||
handler.mapFunctions = map[string]RpcMethodInfo{}
|
||||
handler.funcRpcClient = getClientFun
|
||||
handler.funcRpcServer = getServerFun
|
||||
|
||||
slf.RegisterRpc(rpcHandler)
|
||||
handler.RegisterRpc(rpcHandler)
|
||||
}
|
||||
|
||||
// Is this an exported - upper case - name?
|
||||
@@ -111,7 +109,7 @@ func isExported(name string) bool {
|
||||
}
|
||||
|
||||
// Is this type exported or a builtin?
|
||||
func (slf *RpcHandler) isExportedOrBuiltinType(t reflect.Type) bool {
|
||||
func (handler *RpcHandler) isExportedOrBuiltinType(t reflect.Type) bool {
|
||||
for t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
@@ -120,8 +118,7 @@ func (slf *RpcHandler) isExportedOrBuiltinType(t reflect.Type) bool {
|
||||
return isExported(t.Name()) || t.PkgPath() == ""
|
||||
}
|
||||
|
||||
|
||||
func (slf *RpcHandler) suitableMethods(method reflect.Method) error {
|
||||
func (handler *RpcHandler) suitableMethods(method reflect.Method) error {
|
||||
//只有RPC_开头的才能被调用
|
||||
if strings.Index(method.Name,"RPC_")!=0 {
|
||||
return nil
|
||||
@@ -146,35 +143,35 @@ func (slf *RpcHandler) suitableMethods(method reflect.Method) error {
|
||||
var parIdx int = 1
|
||||
if typ.In(parIdx).String() == "rpc.IRawAdditionParam" {
|
||||
parIdx += 1
|
||||
rpcMethodInfo.hashAdditionParam = true
|
||||
rpcMethodInfo.hasAdditionParam = true
|
||||
}
|
||||
|
||||
for i:= parIdx ;i<typ.NumIn();i++{
|
||||
if slf.isExportedOrBuiltinType(typ.In(i)) == false {
|
||||
if handler.isExportedOrBuiltinType(typ.In(i)) == false {
|
||||
return fmt.Errorf("%s Unsupported parameter types!",method.Name)
|
||||
}
|
||||
}
|
||||
|
||||
rpcMethodInfo.iparam = reflect.New(typ.In(parIdx).Elem()) //append(rpcMethodInfo.iparam,)
|
||||
rpcMethodInfo.iInParam = reflect.New(typ.In(parIdx).Elem()).Interface()
|
||||
pt,_ := GetProcessorType(rpcMethodInfo.iparam.Interface())
|
||||
rpcMethodInfo.inParamValue = reflect.New(typ.In(parIdx).Elem()) //append(rpcMethodInfo.iparam,)
|
||||
rpcMethodInfo.inParam = reflect.New(typ.In(parIdx).Elem()).Interface()
|
||||
pt,_ := GetProcessorType(rpcMethodInfo.inParamValue.Interface())
|
||||
rpcMethodInfo.rpcProcessorType = pt
|
||||
|
||||
parIdx++
|
||||
if parIdx< typ.NumIn() {
|
||||
rpcMethodInfo.oParam = reflect.New(typ.In(parIdx).Elem())
|
||||
rpcMethodInfo.outParamValue = reflect.New(typ.In(parIdx).Elem())
|
||||
}
|
||||
|
||||
rpcMethodInfo.method = method
|
||||
slf.mapfunctons[slf.rpcHandler.GetName()+"."+method.Name] = rpcMethodInfo
|
||||
handler.mapFunctions[handler.rpcHandler.GetName()+"."+method.Name] = rpcMethodInfo
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) RegisterRpc(rpcHandler IRpcHandler) error {
|
||||
func (handler *RpcHandler) RegisterRpc(rpcHandler IRpcHandler) error {
|
||||
typ := reflect.TypeOf(rpcHandler)
|
||||
for m:=0;m<typ.NumMethod();m++{
|
||||
method := typ.Method(m)
|
||||
err := slf.suitableMethods(method)
|
||||
err := handler.suitableMethods(method)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -183,24 +180,24 @@ func (slf *RpcHandler) RegisterRpc(rpcHandler IRpcHandler) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) PushRequest(req *RpcRequest) error{
|
||||
if len(slf.callRequest) >= cap(slf.callRequest){
|
||||
return fmt.Errorf("RpcHandler %s Rpc Channel is full.",slf.GetName())
|
||||
func (handler *RpcHandler) PushRequest(req *RpcRequest) error{
|
||||
if len(handler.callRequest) >= cap(handler.callRequest){
|
||||
return fmt.Errorf("RpcHandler %s Rpc Channel is full.", handler.GetName())
|
||||
}
|
||||
|
||||
slf.callRequest <- req
|
||||
handler.callRequest <- req
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) GetRpcRequestChan() (chan *RpcRequest) {
|
||||
return slf.callRequest
|
||||
func (handler *RpcHandler) GetRpcRequestChan() (chan *RpcRequest) {
|
||||
return handler.callRequest
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) GetRpcResponeChan() chan *Call{
|
||||
return slf.callResponeCallBack
|
||||
func (handler *RpcHandler) GetRpcResponseChan() chan *Call{
|
||||
return handler.callResponseCallBack
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) HandlerRpcResponeCB(call *Call){
|
||||
func (handler *RpcHandler) HandlerRpcResponseCB(call *Call){
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 4096)
|
||||
@@ -218,8 +215,7 @@ func (slf *RpcHandler) HandlerRpcResponeCB(call *Call){
|
||||
ReleaseCall(call)
|
||||
}
|
||||
|
||||
|
||||
func (slf *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
func (handler *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 4096)
|
||||
@@ -235,9 +231,9 @@ func (slf *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
defer ReleaseRpcRequest(request)
|
||||
defer request.rpcProcessor.ReleaseRpcRequest(request.RpcRequestData)
|
||||
|
||||
v,ok := slf.mapfunctons[request.RpcRequestData.GetServiceMethod()]
|
||||
v,ok := handler.mapFunctions[request.RpcRequestData.GetServiceMethod()]
|
||||
if ok == false {
|
||||
err := Errorf("RpcHandler %s cannot find %s",slf.rpcHandler.GetName(),request.RpcRequestData.GetServiceMethod())
|
||||
err := Errorf("RpcHandler %s cannot find %s", handler.rpcHandler.GetName(),request.RpcRequestData.GetServiceMethod())
|
||||
log.Error("%s",err.Error())
|
||||
if request.requestHandle!=nil {
|
||||
request.requestHandle(nil,err)
|
||||
@@ -249,10 +245,10 @@ func (slf *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
var err error
|
||||
var iParam interface{}
|
||||
//单协程下减少gc
|
||||
if slf.IsSingleCoroutine(){
|
||||
iParam = v.iInParam
|
||||
if handler.IsSingleCoroutine(){
|
||||
iParam = v.inParam
|
||||
}else{
|
||||
iParam = reflect.New(v.iparam.Type().Elem()).Interface()
|
||||
iParam = reflect.New(v.inParamValue.Type().Elem()).Interface()
|
||||
}
|
||||
|
||||
if request.bLocalRequest == false {
|
||||
@@ -269,10 +265,10 @@ func (slf *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
if request.localRawParam!=nil {
|
||||
err = request.rpcProcessor.Unmarshal(request.localRawParam,iParam)
|
||||
if err!=nil {
|
||||
rerr := Errorf("Call Rpc %s Param error %+v",request.RpcRequestData.GetServiceMethod(),err)
|
||||
log.Error("%s",rerr.Error())
|
||||
rErr := Errorf("Call Rpc %s Param error %+v",request.RpcRequestData.GetServiceMethod(),err)
|
||||
log.Error("%s", rErr.Error())
|
||||
if request.requestHandle!=nil {
|
||||
request.requestHandle(nil, rerr)
|
||||
request.requestHandle(nil, rErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -281,9 +277,9 @@ func (slf *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
paramList = append(paramList,reflect.ValueOf(slf.GetRpcHandler())) //接受者
|
||||
paramList = append(paramList,reflect.ValueOf(handler.GetRpcHandler())) //接受者
|
||||
additionParams := request.RpcRequestData.GetAdditionParams()
|
||||
if v.hashAdditionParam == true{
|
||||
if v.hasAdditionParam == true{
|
||||
if additionParams!=nil && additionParams.GetParamValue()!=nil{
|
||||
additionVal := reflect.ValueOf(additionParams)
|
||||
paramList = append(paramList,additionVal)
|
||||
@@ -294,19 +290,19 @@ func (slf *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
|
||||
paramList = append(paramList,reflect.ValueOf(iParam))
|
||||
var oParam reflect.Value
|
||||
if v.oParam.IsValid() {
|
||||
if v.outParamValue.IsValid() {
|
||||
if request.localReply!=nil {
|
||||
oParam = reflect.ValueOf(request.localReply) //输出参数
|
||||
}else if slf.IsSingleCoroutine()==true{
|
||||
oParam = v.oParam
|
||||
}else if handler.IsSingleCoroutine()==true{
|
||||
oParam = v.outParamValue
|
||||
}else{
|
||||
oParam = reflect.New(v.oParam.Type().Elem())
|
||||
oParam = reflect.New(v.outParamValue.Type().Elem())
|
||||
}
|
||||
paramList = append(paramList,oParam) //输出参数
|
||||
}else if(request.requestHandle!=nil){ //调用方有返回值,但被调用函数没有返回参数
|
||||
rerr := Errorf("Call Rpc %s without return parameter!",request.RpcRequestData.GetServiceMethod())
|
||||
log.Error("%s",rerr.Error())
|
||||
request.requestHandle(nil, rerr)
|
||||
}else if(request.requestHandle != nil){ //调用方有返回值,但被调用函数没有返回参数
|
||||
rErr := Errorf("Call Rpc %s without return parameter!",request.RpcRequestData.GetServiceMethod())
|
||||
log.Error("%s",rErr.Error())
|
||||
request.requestHandle(nil, rErr)
|
||||
return
|
||||
}
|
||||
returnValues := v.method.Func.Call(paramList)
|
||||
@@ -320,18 +316,18 @@ func (slf *RpcHandler) HandlerRpcRequest(request *RpcRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) CallMethod(ServiceMethod string,param interface{},reply interface{}) error{
|
||||
func (handler *RpcHandler) CallMethod(ServiceMethod string,param interface{},reply interface{}) error{
|
||||
var err error
|
||||
v,ok := slf.mapfunctons[ServiceMethod]
|
||||
v,ok := handler.mapFunctions[ServiceMethod]
|
||||
if ok == false {
|
||||
err = fmt.Errorf("RpcHandler %s cannot find %s",slf.rpcHandler.GetName(),ServiceMethod)
|
||||
err = fmt.Errorf("RpcHandler %s cannot find %s", handler.rpcHandler.GetName(),ServiceMethod)
|
||||
log.Error("%s",err.Error())
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
var paramList []reflect.Value
|
||||
paramList = append(paramList,reflect.ValueOf(slf.GetRpcHandler())) //接受者
|
||||
paramList = append(paramList,reflect.ValueOf(handler.GetRpcHandler())) //接受者
|
||||
paramList = append(paramList,reflect.ValueOf(param))
|
||||
paramList = append(paramList,reflect.ValueOf(reply)) //输出参数
|
||||
|
||||
@@ -344,9 +340,9 @@ func (slf *RpcHandler) CallMethod(ServiceMethod string,param interface{},reply i
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) goRpc(processor IRpcProcessor,bCast bool,nodeId int,serviceMethod string,args interface{}) error {
|
||||
func (handler *RpcHandler) goRpc(processor IRpcProcessor,bCast bool,nodeId int,serviceMethod string,args interface{}) error {
|
||||
var pClientList []*Client
|
||||
err := slf.funcRpcClient(nodeId,serviceMethod,&pClientList)
|
||||
err := handler.funcRpcClient(nodeId,serviceMethod,&pClientList)
|
||||
if err != nil {
|
||||
log.Error("Call serviceMethod is error:%+v!",err)
|
||||
return err
|
||||
@@ -360,19 +356,19 @@ func (slf *RpcHandler) goRpc(processor IRpcProcessor,bCast bool,nodeId int,servi
|
||||
//如果调用本结点服务
|
||||
for _,pClient := range pClientList {
|
||||
if pClient.bSelfNode == true {
|
||||
pLocalRpcServer:=slf.funcRpcServer()
|
||||
pLocalRpcServer:= handler.funcRpcServer()
|
||||
//判断是否是同一服务
|
||||
sMethod := strings.Split(serviceMethod,".")
|
||||
if len(sMethod)!=2 {
|
||||
serr := fmt.Errorf("Call serviceMethod %s is error!",serviceMethod)
|
||||
log.Error("%+v",serr)
|
||||
if serr!= nil {
|
||||
err = serr
|
||||
sErr := fmt.Errorf("Call serviceMethod %s is error!",serviceMethod)
|
||||
log.Error("%+v", sErr)
|
||||
if sErr != nil {
|
||||
err = sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
//调用自己rpcHandler处理器
|
||||
if sMethod[0] == slf.rpcHandler.GetName() { //自己服务调用
|
||||
if sMethod[0] == handler.rpcHandler.GetName() { //自己服务调用
|
||||
//
|
||||
return pLocalRpcServer.myselfRpcHandlerGo(sMethod[0],sMethod[1],args,nil)
|
||||
}
|
||||
@@ -396,11 +392,9 @@ func (slf *RpcHandler) goRpc(processor IRpcProcessor,bCast bool,nodeId int,servi
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (slf *RpcHandler) rawGoRpc(processor IRpcProcessor,bCast bool,nodeId int,serviceMethod string,args []byte,additionParam interface{}) error {
|
||||
func (handler *RpcHandler) rawGoRpc(processor IRpcProcessor,bCast bool,nodeId int,serviceMethod string,args []byte,additionParam interface{}) error {
|
||||
var pClientList []*Client
|
||||
err := slf.funcRpcClient(nodeId,serviceMethod,&pClientList)
|
||||
err := handler.funcRpcClient(nodeId,serviceMethod,&pClientList)
|
||||
if err != nil {
|
||||
log.Error("Call serviceMethod is error:%+v!",err)
|
||||
return err
|
||||
@@ -414,7 +408,7 @@ func (slf *RpcHandler) rawGoRpc(processor IRpcProcessor,bCast bool,nodeId int,se
|
||||
//如果调用本结点服务
|
||||
for _,pClient := range pClientList {
|
||||
if pClient.bSelfNode == true {
|
||||
pLocalRpcServer:=slf.funcRpcServer()
|
||||
pLocalRpcServer:= handler.funcRpcServer()
|
||||
//判断是否是同一服务
|
||||
sMethod := strings.Split(serviceMethod,".")
|
||||
if len(sMethod)!=2 {
|
||||
@@ -426,7 +420,7 @@ func (slf *RpcHandler) rawGoRpc(processor IRpcProcessor,bCast bool,nodeId int,se
|
||||
continue
|
||||
}
|
||||
//调用自己rpcHandler处理器
|
||||
if sMethod[0] == slf.rpcHandler.GetName() { //自己服务调用
|
||||
if sMethod[0] == handler.rpcHandler.GetName() { //自己服务调用
|
||||
//
|
||||
return pLocalRpcServer.myselfRpcHandlerGo(sMethod[0],sMethod[1],args,nil)
|
||||
}
|
||||
@@ -451,9 +445,9 @@ func (slf *RpcHandler) rawGoRpc(processor IRpcProcessor,bCast bool,nodeId int,se
|
||||
}
|
||||
|
||||
|
||||
func (slf *RpcHandler) callRpc(nodeId int,serviceMethod string,args interface{},reply interface{}) error {
|
||||
func (handler *RpcHandler) callRpc(nodeId int,serviceMethod string,args interface{},reply interface{}) error {
|
||||
var pClientList []*Client
|
||||
err := slf.funcRpcClient(nodeId,serviceMethod,&pClientList)
|
||||
err := handler.funcRpcClient(nodeId,serviceMethod,&pClientList)
|
||||
if err != nil {
|
||||
log.Error("Call serviceMethod is error:%+v!",err)
|
||||
return err
|
||||
@@ -467,7 +461,7 @@ func (slf *RpcHandler) callRpc(nodeId int,serviceMethod string,args interface{},
|
||||
//如果调用本结点服务
|
||||
pClient := pClientList[0]
|
||||
if pClient.bSelfNode == true {
|
||||
pLocalRpcServer:=slf.funcRpcServer()
|
||||
pLocalRpcServer:= handler.funcRpcServer()
|
||||
//判断是否是同一服务
|
||||
sMethod := strings.Split(serviceMethod,".")
|
||||
if len(sMethod)!=2 {
|
||||
@@ -476,7 +470,7 @@ func (slf *RpcHandler) callRpc(nodeId int,serviceMethod string,args interface{},
|
||||
return err
|
||||
}
|
||||
//调用自己rpcHandler处理器
|
||||
if sMethod[0] == slf.rpcHandler.GetName() { //自己服务调用
|
||||
if sMethod[0] == handler.rpcHandler.GetName() { //自己服务调用
|
||||
//
|
||||
return pLocalRpcServer.myselfRpcHandlerGo(sMethod[0],sMethod[1],args,reply)
|
||||
}
|
||||
@@ -499,7 +493,7 @@ func (slf *RpcHandler) callRpc(nodeId int,serviceMethod string,args interface{},
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) asyncCallRpc(nodeid int,serviceMethod string,args interface{},callback interface{}) error {
|
||||
func (handler *RpcHandler) asyncCallRpc(nodeid int,serviceMethod string,args interface{},callback interface{}) error {
|
||||
fVal := reflect.ValueOf(callback)
|
||||
if fVal.Kind()!=reflect.Func{
|
||||
err := fmt.Errorf("call %s input callback param is error!",serviceMethod)
|
||||
@@ -521,7 +515,7 @@ func (slf *RpcHandler) asyncCallRpc(nodeid int,serviceMethod string,args interfa
|
||||
|
||||
reply := reflect.New(fVal.Type().In(0).Elem()).Interface()
|
||||
var pClientList []*Client
|
||||
err := slf.funcRpcClient(nodeid,serviceMethod,&pClientList)
|
||||
err := handler.funcRpcClient(nodeid,serviceMethod,&pClientList)
|
||||
if err != nil {
|
||||
fVal.Call([]reflect.Value{reflect.ValueOf(reply),reflect.ValueOf(err)})
|
||||
log.Error("Call serviceMethod is error:%+v!",err)
|
||||
@@ -539,7 +533,7 @@ func (slf *RpcHandler) asyncCallRpc(nodeid int,serviceMethod string,args interfa
|
||||
//如果调用本结点服务
|
||||
pClient := pClientList[0]
|
||||
if pClient.bSelfNode == true {
|
||||
pLocalRpcServer:=slf.funcRpcServer()
|
||||
pLocalRpcServer:= handler.funcRpcServer()
|
||||
//判断是否是同一服务
|
||||
sMethod := strings.Split(serviceMethod,".")
|
||||
if len(sMethod)!=2 {
|
||||
@@ -549,7 +543,7 @@ func (slf *RpcHandler) asyncCallRpc(nodeid int,serviceMethod string,args interfa
|
||||
return nil
|
||||
}
|
||||
//调用自己rpcHandler处理器
|
||||
if sMethod[0] == slf.rpcHandler.GetName() { //自己服务调用
|
||||
if sMethod[0] == handler.rpcHandler.GetName() { //自己服务调用
|
||||
err := pLocalRpcServer.myselfRpcHandlerGo(sMethod[0],sMethod[1],args,reply)
|
||||
if err == nil {
|
||||
fVal.Call([]reflect.Value{reflect.ValueOf(reply),NilError})
|
||||
@@ -560,7 +554,7 @@ func (slf *RpcHandler) asyncCallRpc(nodeid int,serviceMethod string,args interfa
|
||||
|
||||
//其他的rpcHandler的处理器
|
||||
if callback!=nil {
|
||||
err = pLocalRpcServer.selfNodeRpcHandlerAsyncGo(pClient,slf,false,sMethod[0],sMethod[1],args,reply,fVal)
|
||||
err = pLocalRpcServer.selfNodeRpcHandlerAsyncGo(pClient, handler,false,sMethod[0],sMethod[1],args,reply,fVal)
|
||||
if err != nil {
|
||||
fVal.Call([]reflect.Value{reflect.ValueOf(reply),reflect.ValueOf(err)})
|
||||
}
|
||||
@@ -575,54 +569,54 @@ func (slf *RpcHandler) asyncCallRpc(nodeid int,serviceMethod string,args interfa
|
||||
}
|
||||
|
||||
//跨node调用
|
||||
err = pClient.AsycCall(slf,serviceMethod,fVal,args,reply)
|
||||
err = pClient.AsyncCall(handler,serviceMethod,fVal,args,reply)
|
||||
if err != nil {
|
||||
fVal.Call([]reflect.Value{reflect.ValueOf(reply),reflect.ValueOf(err)})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) GetName() string{
|
||||
return slf.rpcHandler.GetName()
|
||||
func (handler *RpcHandler) GetName() string{
|
||||
return handler.rpcHandler.GetName()
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) IsSingleCoroutine() bool{
|
||||
return slf.rpcHandler.IsSingleCoroutine()
|
||||
func (handler *RpcHandler) IsSingleCoroutine() bool{
|
||||
return handler.rpcHandler.IsSingleCoroutine()
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) AsyncCall(serviceMethod string,args interface{},callback interface{}) error {
|
||||
return slf.asyncCallRpc(0,serviceMethod,args,callback)
|
||||
func (handler *RpcHandler) AsyncCall(serviceMethod string,args interface{},callback interface{}) error {
|
||||
return handler.asyncCallRpc(0,serviceMethod,args,callback)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) Call(serviceMethod string,args interface{},reply interface{}) error {
|
||||
return slf.callRpc(0,serviceMethod,args,reply)
|
||||
func (handler *RpcHandler) Call(serviceMethod string,args interface{},reply interface{}) error {
|
||||
return handler.callRpc(0,serviceMethod,args,reply)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) Go(serviceMethod string,args interface{}) error {
|
||||
return slf.goRpc(nil,false,0,serviceMethod,args)
|
||||
func (handler *RpcHandler) Go(serviceMethod string,args interface{}) error {
|
||||
return handler.goRpc(nil,false,0,serviceMethod,args)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) AsyncCallNode(nodeId int,serviceMethod string,args interface{},callback interface{}) error {
|
||||
return slf.asyncCallRpc(nodeId,serviceMethod,args,callback)
|
||||
func (handler *RpcHandler) AsyncCallNode(nodeId int,serviceMethod string,args interface{},callback interface{}) error {
|
||||
return handler.asyncCallRpc(nodeId,serviceMethod,args,callback)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) CallNode(nodeId int,serviceMethod string,args interface{},reply interface{}) error {
|
||||
return slf.callRpc(nodeId,serviceMethod,args,reply)
|
||||
func (handler *RpcHandler) CallNode(nodeId int,serviceMethod string,args interface{},reply interface{}) error {
|
||||
return handler.callRpc(nodeId,serviceMethod,args,reply)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) GoNode(nodeId int,serviceMethod string,args interface{}) error {
|
||||
return slf.goRpc(nil,false,nodeId,serviceMethod,args)
|
||||
func (handler *RpcHandler) GoNode(nodeId int,serviceMethod string,args interface{}) error {
|
||||
return handler.goRpc(nil,false,nodeId,serviceMethod,args)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) CastGo(serviceMethod string,args interface{}) {
|
||||
slf.goRpc(nil,true,0,serviceMethod,args)
|
||||
func (handler *RpcHandler) CastGo(serviceMethod string,args interface{}) {
|
||||
handler.goRpc(nil,true,0,serviceMethod,args)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) RawGoNode(rpcProcessorType RpcProcessorType,nodeId int,serviceMethod string,args []byte,additionParam interface{}) error {
|
||||
return slf.rawGoRpc(GetProcessor(uint8(rpcProcessorType)),false,nodeId,serviceMethod,args,additionParam)
|
||||
func (handler *RpcHandler) RawGoNode(rpcProcessorType RpcProcessorType,nodeId int,serviceMethod string,args []byte,additionParam interface{}) error {
|
||||
return handler.rawGoRpc(GetProcessor(uint8(rpcProcessorType)),false,nodeId,serviceMethod,args,additionParam)
|
||||
}
|
||||
|
||||
func (slf *RpcHandler) RawCastGo(rpcProcessorType RpcProcessorType,serviceMethod string,args []byte,additionParam interface{}) {
|
||||
slf.goRpc(GetProcessor(uint8(rpcProcessorType)),true,0,serviceMethod,args)
|
||||
func (handler *RpcHandler) RawCastGo(rpcProcessorType RpcProcessorType,serviceMethod string,args []byte,additionParam interface{}) {
|
||||
handler.goRpc(GetProcessor(uint8(rpcProcessorType)),true,0,serviceMethod,args)
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
type RpcProcessorType uint8
|
||||
|
||||
const (
|
||||
RPC_PROCESSOR_JSON RpcProcessorType = 0
|
||||
RPC_PROCESSOR_PB RpcProcessorType = 1
|
||||
RpcProcessorJson RpcProcessorType = 0
|
||||
RpcProcessorPb RpcProcessorType = 1
|
||||
)
|
||||
|
||||
//var processor IRpcProcessor = &JsonProcessor{}
|
||||
@@ -22,10 +22,16 @@ var arrayProcessorLen uint8 = 2
|
||||
var LittleEndian bool
|
||||
|
||||
type Server struct {
|
||||
functions map[interface{}]interface{}
|
||||
cmdchannel chan *Call
|
||||
functions map[interface{}]interface{}
|
||||
cmdChannel chan *Call
|
||||
rpcHandleFinder RpcHandleFinder
|
||||
rpcserver *network.TCPServer
|
||||
rpcServer *network.TCPServer
|
||||
}
|
||||
|
||||
type RpcAgent struct {
|
||||
conn network.Conn
|
||||
rpcServer *Server
|
||||
userData interface{}
|
||||
}
|
||||
|
||||
func AppendProcessor(rpcProcessor IRpcProcessor) {
|
||||
@@ -40,7 +46,7 @@ func GetProcessorType(param interface{}) (RpcProcessorType,IRpcProcessor){
|
||||
}
|
||||
}
|
||||
|
||||
return RPC_PROCESSOR_JSON,arrayProcessor[RPC_PROCESSOR_JSON]
|
||||
return RpcProcessorJson,arrayProcessor[RpcProcessorJson]
|
||||
}
|
||||
|
||||
func GetProcessor(processorType uint8) IRpcProcessor{
|
||||
@@ -50,39 +56,32 @@ func GetProcessor(processorType uint8) IRpcProcessor{
|
||||
return arrayProcessor[processorType]
|
||||
}
|
||||
|
||||
func (slf *Server) Init(rpcHandleFinder RpcHandleFinder) {
|
||||
slf.cmdchannel = make(chan *Call,100000)
|
||||
slf.rpcHandleFinder = rpcHandleFinder
|
||||
slf.rpcserver = &network.TCPServer{}
|
||||
func (server *Server) Init(rpcHandleFinder RpcHandleFinder) {
|
||||
server.cmdChannel = make(chan *Call,100000)
|
||||
server.rpcHandleFinder = rpcHandleFinder
|
||||
server.rpcServer = &network.TCPServer{}
|
||||
}
|
||||
|
||||
func (slf *Server) Start(listenAddr string) {
|
||||
func (server *Server) Start(listenAddr string) {
|
||||
splitAddr := strings.Split(listenAddr,":")
|
||||
if len(splitAddr)!=2{
|
||||
log.Fatal("listen addr is error :%s",listenAddr)
|
||||
}
|
||||
slf.rpcserver.Addr = ":"+splitAddr[1]
|
||||
slf.rpcserver.LenMsgLen = 2 //uint16
|
||||
slf.rpcserver.MinMsgLen = 2
|
||||
slf.rpcserver.MaxMsgLen = math.MaxUint16
|
||||
slf.rpcserver.MaxConnNum = 10000
|
||||
slf.rpcserver.PendingWriteNum = 2000000
|
||||
slf.rpcserver.NewAgent =slf.NewAgent
|
||||
slf.rpcserver.LittleEndian = LittleEndian
|
||||
slf.rpcserver.Start()
|
||||
|
||||
server.rpcServer.Addr = ":"+splitAddr[1]
|
||||
server.rpcServer.LenMsgLen = 2 //uint16
|
||||
server.rpcServer.MinMsgLen = 2
|
||||
server.rpcServer.MaxMsgLen = math.MaxUint16
|
||||
server.rpcServer.MaxConnNum = 10000
|
||||
server.rpcServer.PendingWriteNum = 2000000
|
||||
server.rpcServer.NewAgent = server.NewAgent
|
||||
server.rpcServer.LittleEndian = LittleEndian
|
||||
server.rpcServer.Start()
|
||||
}
|
||||
|
||||
func (agent *RpcAgent) OnDestroy() {}
|
||||
|
||||
func (gate *RpcAgent) OnDestroy() {}
|
||||
|
||||
type RpcAgent struct {
|
||||
conn network.Conn
|
||||
rpcserver *Server
|
||||
userData interface{}
|
||||
}
|
||||
|
||||
|
||||
func (agent *RpcAgent) WriteRespone(processor IRpcProcessor,serviceMethod string,seq uint64,reply interface{},err *RpcError) {
|
||||
func (agent *RpcAgent) WriteResponse(processor IRpcProcessor,serviceMethod string,seq uint64,reply interface{},err *RpcError) {
|
||||
var mReply []byte
|
||||
var rpcError *RpcError
|
||||
var errM error
|
||||
@@ -99,9 +98,9 @@ func (agent *RpcAgent) WriteRespone(processor IRpcProcessor,serviceMethod string
|
||||
}
|
||||
|
||||
var rpcResponse RpcResponse
|
||||
rpcResponse.RpcResponeData = processor.MakeRpcResponse(seq,rpcError,mReply)
|
||||
bytes,errM := processor.Marshal(rpcResponse.RpcResponeData)
|
||||
defer processor.ReleaseRpcRespose(rpcResponse.RpcResponeData)
|
||||
rpcResponse.RpcResponseData = processor.MakeRpcResponse(seq,rpcError,mReply)
|
||||
bytes,errM := processor.Marshal(rpcResponse.RpcResponseData)
|
||||
defer processor.ReleaseRpcRespose(rpcResponse.RpcResponseData)
|
||||
|
||||
if errM != nil {
|
||||
log.Error("service method %s %+v Marshal error:%+v!", serviceMethod,rpcResponse,errM)
|
||||
@@ -114,7 +113,6 @@ func (agent *RpcAgent) WriteRespone(processor IRpcProcessor,serviceMethod string
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func (agent *RpcAgent) Run() {
|
||||
for {
|
||||
data,err := agent.conn.ReadMsg()
|
||||
@@ -123,6 +121,7 @@ func (agent *RpcAgent) Run() {
|
||||
//will close tcpconn
|
||||
break
|
||||
}
|
||||
|
||||
processor := GetProcessor(uint8(data[0]))
|
||||
if processor==nil {
|
||||
agent.conn.ReleaseReadMsg(data)
|
||||
@@ -140,7 +139,7 @@ func (agent *RpcAgent) Run() {
|
||||
log.Error("rpc Unmarshal request is error: %v", err)
|
||||
if req.RpcRequestData.GetSeq()>0 {
|
||||
rpcError := RpcError(err.Error())
|
||||
agent.WriteRespone(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
agent.WriteResponse(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
processor.ReleaseRpcRequest(req.RpcRequestData)
|
||||
ReleaseRpcRequest(req)
|
||||
continue
|
||||
@@ -156,17 +155,17 @@ func (agent *RpcAgent) Run() {
|
||||
serviceMethod := strings.Split(req.RpcRequestData.GetServiceMethod(),".")
|
||||
if len(serviceMethod)!=2 {
|
||||
rpcError := RpcError("rpc request req.ServiceMethod is error")
|
||||
agent.WriteRespone(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
agent.WriteResponse(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
processor.ReleaseRpcRequest(req.RpcRequestData)
|
||||
ReleaseRpcRequest(req)
|
||||
log.Debug("rpc request req.ServiceMethod is error")
|
||||
continue
|
||||
}
|
||||
|
||||
rpcHandler := agent.rpcserver.rpcHandleFinder.FindRpcHandler(serviceMethod[0])
|
||||
rpcHandler := agent.rpcServer.rpcHandleFinder.FindRpcHandler(serviceMethod[0])
|
||||
if rpcHandler== nil {
|
||||
rpcError := RpcError(fmt.Sprintf("service method %s not config!", req.RpcRequestData.GetServiceMethod()))
|
||||
agent.WriteRespone(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
agent.WriteResponse(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
processor.ReleaseRpcRequest(req.RpcRequestData)
|
||||
ReleaseRpcRequest(req)
|
||||
log.Error("service method %s not config!", req.RpcRequestData.GetServiceMethod())
|
||||
@@ -175,7 +174,7 @@ func (agent *RpcAgent) Run() {
|
||||
|
||||
if req.RpcRequestData.IsNoReply()==false {
|
||||
req.requestHandle = func(Returns interface{},Err *RpcError){
|
||||
agent.WriteRespone(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),Returns,Err)
|
||||
agent.WriteResponse(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),Returns,Err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +183,7 @@ func (agent *RpcAgent) Run() {
|
||||
rpcError := RpcError(err.Error())
|
||||
|
||||
if req.RpcRequestData.IsNoReply() {
|
||||
agent.WriteRespone(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
agent.WriteResponse(processor,req.RpcRequestData.GetServiceMethod(),req.RpcRequestData.GetSeq(),nil,&rpcError)
|
||||
}
|
||||
|
||||
processor.ReleaseRpcRequest(req.RpcRequestData)
|
||||
@@ -215,15 +214,14 @@ func (agent *RpcAgent) Destroy() {
|
||||
agent.conn.Destroy()
|
||||
}
|
||||
|
||||
|
||||
func (slf *Server) NewAgent(conn *network.TCPConn) network.Agent {
|
||||
agent := &RpcAgent{conn: conn, rpcserver: slf}
|
||||
func (server *Server) NewAgent(conn *network.TCPConn) network.Agent {
|
||||
agent := &RpcAgent{conn: conn, rpcServer: server}
|
||||
|
||||
return agent
|
||||
}
|
||||
|
||||
func (slf *Server) myselfRpcHandlerGo(handlerName string,methodName string, args interface{},reply interface{}) error {
|
||||
rpcHandler := slf.rpcHandleFinder.FindRpcHandler(handlerName)
|
||||
func (server *Server) myselfRpcHandlerGo(handlerName string,methodName string, args interface{},reply interface{}) error {
|
||||
rpcHandler := server.rpcHandleFinder.FindRpcHandler(handlerName)
|
||||
if rpcHandler== nil {
|
||||
err := fmt.Errorf("service method %s.%s not config!", handlerName,methodName)
|
||||
log.Error("%s",err.Error())
|
||||
@@ -234,11 +232,11 @@ func (slf *Server) myselfRpcHandlerGo(handlerName string,methodName string, args
|
||||
}
|
||||
|
||||
|
||||
func (slf *Server) selfNodeRpcHandlerGo(processor IRpcProcessor,client *Client,noReply bool,handlerName string,methodName string, args interface{},rawArgs []byte,reply interface{},additionParam interface{}) *Call {
|
||||
func (server *Server) selfNodeRpcHandlerGo(processor IRpcProcessor,client *Client,noReply bool,handlerName string,methodName string, args interface{},rawArgs []byte,reply interface{},additionParam interface{}) *Call {
|
||||
pCall := MakeCall()
|
||||
pCall.Seq = client.generateSeq()
|
||||
|
||||
rpcHandler := slf.rpcHandleFinder.FindRpcHandler(handlerName)
|
||||
rpcHandler := server.rpcHandleFinder.FindRpcHandler(handlerName)
|
||||
if rpcHandler== nil {
|
||||
pCall.Err = fmt.Errorf("service method %s.%s not config!", handlerName,methodName)
|
||||
log.Error("%s",pCall.Err.Error())
|
||||
@@ -288,13 +286,13 @@ func (slf *Server) selfNodeRpcHandlerGo(processor IRpcProcessor,client *Client,n
|
||||
return pCall
|
||||
}
|
||||
|
||||
func (slf *Server) selfNodeRpcHandlerAsyncGo(client *Client,callerRpcHandler IRpcHandler,noReply bool,handlerName string,methodName string,args interface{},reply interface{},callback reflect.Value) error {
|
||||
func (server *Server) selfNodeRpcHandlerAsyncGo(client *Client,callerRpcHandler IRpcHandler,noReply bool,handlerName string,methodName string,args interface{},reply interface{},callback reflect.Value) error {
|
||||
pCall := MakeCall()
|
||||
pCall.Seq = client.generateSeq()
|
||||
pCall.rpcHandler = callerRpcHandler
|
||||
pCall.callback = &callback
|
||||
pCall.Reply = reply
|
||||
rpcHandler := slf.rpcHandleFinder.FindRpcHandler(handlerName)
|
||||
rpcHandler := server.rpcHandleFinder.FindRpcHandler(handlerName)
|
||||
if rpcHandler== nil {
|
||||
err := fmt.Errorf("service method %s.%s not config!", handlerName,methodName)
|
||||
log.Error("%+v",err)
|
||||
@@ -330,11 +328,10 @@ func (slf *Server) selfNodeRpcHandlerAsyncGo(client *Client,callerRpcHandler IRp
|
||||
if Returns!=nil {
|
||||
pCall.Reply = Returns
|
||||
}
|
||||
pCall.rpcHandler.(*RpcHandler).callResponeCallBack<-pCall
|
||||
pCall.rpcHandler.(*RpcHandler).callResponseCallBack <-pCall
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
err := rpcHandler.PushRequest(req)
|
||||
if err != nil {
|
||||
processor.ReleaseRpcRequest(req.RpcRequestData)
|
||||
|
||||
@@ -9,10 +9,8 @@ import (
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
const InitModuleId = 1e17
|
||||
|
||||
|
||||
type IModule interface {
|
||||
SetModuleId(moduleId int64) bool
|
||||
GetModuleId() int64
|
||||
@@ -31,102 +29,96 @@ type IModule interface {
|
||||
NotifyEvent(ev *event.Event)
|
||||
}
|
||||
|
||||
|
||||
|
||||
//1.管理各模块树层关系
|
||||
//2.提供定时器常用工具
|
||||
type Module struct {
|
||||
moduleId int64
|
||||
parent IModule //父亲
|
||||
self IModule //自己
|
||||
child map[int64]IModule //孩子们
|
||||
moduleId int64 //模块Id
|
||||
moduleName string //模块名称
|
||||
parent IModule //父亲
|
||||
self IModule //自己
|
||||
child map[int64]IModule //孩子们
|
||||
mapActiveTimer map[*timer.Timer]interface{}
|
||||
mapActiveCron map[*timer.Cron]interface{}
|
||||
|
||||
dispatcher *timer.Dispatcher //timer
|
||||
dispatcher *timer.Dispatcher //timer
|
||||
|
||||
//根结点
|
||||
ancestor IModule //始祖
|
||||
seedModuleId int64 //模块id种子
|
||||
descendants map[int64]IModule//始祖的后裔们
|
||||
ancestor IModule //始祖
|
||||
seedModuleId int64 //模块id种子
|
||||
descendants map[int64]IModule //始祖的后裔们
|
||||
|
||||
//事件管道
|
||||
moduleName string
|
||||
eventHandler event.IEventHandler
|
||||
//eventHandler event.EventHandler
|
||||
}
|
||||
|
||||
|
||||
func (slf *Module) SetModuleId(moduleId int64) bool{
|
||||
if slf.moduleId > 0 {
|
||||
func (m *Module) SetModuleId(moduleId int64) bool{
|
||||
if m.moduleId > 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
slf.moduleId = moduleId
|
||||
m.moduleId = moduleId
|
||||
return true
|
||||
}
|
||||
|
||||
func (slf *Module) GetModuleId() int64{
|
||||
return slf.moduleId
|
||||
func (m *Module) GetModuleId() int64{
|
||||
return m.moduleId
|
||||
}
|
||||
|
||||
func (slf *Module) GetModuleName() string{
|
||||
return slf.moduleName
|
||||
func (m *Module) GetModuleName() string{
|
||||
return m.moduleName
|
||||
}
|
||||
|
||||
func (slf *Module) OnInit() error{
|
||||
// slf.eventHandler = event.NewEventHandler()
|
||||
func (m *Module) OnInit() error{
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *Module) AddModule(module IModule) (int64,error){
|
||||
func (m *Module) AddModule(module IModule) (int64,error){
|
||||
//没有事件处理器不允许加入其他模块
|
||||
if slf.GetEventProcessor() == nil {
|
||||
return 0,fmt.Errorf("module %+v is not Event Processor is nil",slf.self)
|
||||
if m.GetEventProcessor() == nil {
|
||||
return 0,fmt.Errorf("module %+v is not Event Processor is nil", m.self)
|
||||
}
|
||||
pAddModule := module.getBaseModule().(*Module)
|
||||
if pAddModule.GetModuleId()==0 {
|
||||
pAddModule.moduleId = slf.NewModuleId()
|
||||
pAddModule.moduleId = m.NewModuleId()
|
||||
}
|
||||
|
||||
if slf.child == nil {
|
||||
slf.child = map[int64]IModule{}
|
||||
if m.child == nil {
|
||||
m.child = map[int64]IModule{}
|
||||
}
|
||||
_,ok := slf.child[module.GetModuleId()]
|
||||
_,ok := m.child[module.GetModuleId()]
|
||||
if ok == true {
|
||||
return 0,fmt.Errorf("Exists module id %d",module.GetModuleId())
|
||||
}
|
||||
|
||||
pAddModule.self = module
|
||||
pAddModule.parent = slf.self
|
||||
pAddModule.dispatcher = slf.GetAncestor().getBaseModule().(*Module).dispatcher
|
||||
pAddModule.ancestor = slf.ancestor
|
||||
pAddModule.parent = m.self
|
||||
pAddModule.dispatcher = m.GetAncestor().getBaseModule().(*Module).dispatcher
|
||||
pAddModule.ancestor = m.ancestor
|
||||
pAddModule.moduleName = reflect.Indirect(reflect.ValueOf(module)).Type().Name()
|
||||
pAddModule.eventHandler = event.NewEventHandler()
|
||||
pAddModule.eventHandler.Init(slf.eventHandler.GetEventProcessor())
|
||||
pAddModule.eventHandler.Init(m.eventHandler.GetEventProcessor())
|
||||
err := module.OnInit()
|
||||
if err != nil {
|
||||
return 0,err
|
||||
}
|
||||
|
||||
slf.child[module.GetModuleId()] = module
|
||||
slf.ancestor.getBaseModule().(*Module).descendants[module.GetModuleId()] = module
|
||||
m.child[module.GetModuleId()] = module
|
||||
m.ancestor.getBaseModule().(*Module).descendants[module.GetModuleId()] = module
|
||||
|
||||
log.Debug("Add module %s completed",slf.GetModuleName())
|
||||
log.Debug("Add module %s completed", m.GetModuleName())
|
||||
return module.GetModuleId(),nil
|
||||
}
|
||||
|
||||
func (slf *Module) ReleaseModule(moduleId int64){
|
||||
pModule := slf.GetModule(moduleId).getBaseModule().(*Module)
|
||||
func (m *Module) ReleaseModule(moduleId int64){
|
||||
pModule := m.GetModule(moduleId).getBaseModule().(*Module)
|
||||
|
||||
//释放子孙
|
||||
for id,_ := range pModule.child {
|
||||
slf.ReleaseModule(id)
|
||||
m.ReleaseModule(id)
|
||||
}
|
||||
|
||||
pModule.GetEventHandler().Destroy()
|
||||
pModule.self.OnRelease()
|
||||
log.Debug("Release module %s.",slf.GetModuleName())
|
||||
log.Debug("Release module %s.", m.GetModuleName())
|
||||
for pTimer,_ := range pModule.mapActiveTimer {
|
||||
pTimer.Close()
|
||||
}
|
||||
@@ -135,8 +127,8 @@ func (slf *Module) ReleaseModule(moduleId int64){
|
||||
pCron.Close()
|
||||
}
|
||||
|
||||
delete(slf.child,moduleId)
|
||||
delete (slf.ancestor.getBaseModule().(*Module).descendants,moduleId)
|
||||
delete(m.child,moduleId)
|
||||
delete (m.ancestor.getBaseModule().(*Module).descendants,moduleId)
|
||||
|
||||
//清理被删除的Module
|
||||
pModule.self = nil
|
||||
@@ -149,75 +141,74 @@ func (slf *Module) ReleaseModule(moduleId int64){
|
||||
pModule.descendants = nil
|
||||
}
|
||||
|
||||
func (slf *Module) NewModuleId() int64{
|
||||
slf.ancestor.getBaseModule().(*Module).seedModuleId+=1
|
||||
return slf.ancestor.getBaseModule().(*Module).seedModuleId
|
||||
func (m *Module) NewModuleId() int64{
|
||||
m.ancestor.getBaseModule().(*Module).seedModuleId+=1
|
||||
return m.ancestor.getBaseModule().(*Module).seedModuleId
|
||||
}
|
||||
|
||||
func (slf *Module) GetAncestor()IModule{
|
||||
return slf.ancestor
|
||||
func (m *Module) GetAncestor()IModule{
|
||||
return m.ancestor
|
||||
}
|
||||
|
||||
func (slf *Module) GetModule(moduleId int64) IModule{
|
||||
iModule,ok := slf.GetAncestor().getBaseModule().(*Module).descendants[moduleId]
|
||||
func (m *Module) GetModule(moduleId int64) IModule{
|
||||
iModule,ok := m.GetAncestor().getBaseModule().(*Module).descendants[moduleId]
|
||||
if ok == false{
|
||||
return nil
|
||||
}
|
||||
return iModule
|
||||
}
|
||||
|
||||
func (slf *Module) getBaseModule() IModule{
|
||||
return slf
|
||||
func (m *Module) getBaseModule() IModule{
|
||||
return m
|
||||
}
|
||||
|
||||
|
||||
func (slf *Module) GetParent()IModule{
|
||||
return slf.parent
|
||||
func (m *Module) GetParent()IModule{
|
||||
return m.parent
|
||||
}
|
||||
|
||||
func (slf *Module) AfterFunc(d time.Duration, cb func()) *timer.Timer {
|
||||
if slf.mapActiveTimer == nil {
|
||||
slf.mapActiveTimer =map[*timer.Timer]interface{}{}
|
||||
func (m *Module) AfterFunc(d time.Duration, cb func()) *timer.Timer {
|
||||
if m.mapActiveTimer == nil {
|
||||
m.mapActiveTimer =map[*timer.Timer]interface{}{}
|
||||
}
|
||||
|
||||
funName := runtime.FuncForPC(reflect.ValueOf(cb).Pointer()).Name()
|
||||
tm := slf.dispatcher.AfterFuncEx(funName,d,func(t *timer.Timer){
|
||||
tm := m.dispatcher.AfterFuncEx(funName,d,func(t *timer.Timer){
|
||||
cb()
|
||||
delete(slf.mapActiveTimer,t)
|
||||
delete(m.mapActiveTimer,t)
|
||||
})
|
||||
|
||||
slf.mapActiveTimer[tm] = nil
|
||||
m.mapActiveTimer[tm] = nil
|
||||
return tm
|
||||
}
|
||||
|
||||
func (slf *Module) CronFunc(cronExpr *timer.CronExpr, cb func()) *timer.Cron {
|
||||
if slf.mapActiveCron == nil {
|
||||
slf.mapActiveCron =map[*timer.Cron]interface{}{}
|
||||
func (m *Module) CronFunc(cronExpr *timer.CronExpr, cb func()) *timer.Cron {
|
||||
if m.mapActiveCron == nil {
|
||||
m.mapActiveCron =map[*timer.Cron]interface{}{}
|
||||
}
|
||||
|
||||
cron := slf.dispatcher.CronFuncEx(cronExpr, func(cron *timer.Cron) {
|
||||
cron := m.dispatcher.CronFuncEx(cronExpr, func(cron *timer.Cron) {
|
||||
cb()
|
||||
})
|
||||
|
||||
slf.mapActiveCron[cron] = nil
|
||||
m.mapActiveCron[cron] = nil
|
||||
return cron
|
||||
}
|
||||
|
||||
func (slf *Module) OnRelease(){
|
||||
func (m *Module) OnRelease(){
|
||||
}
|
||||
|
||||
func (slf *Module) GetService() IService {
|
||||
return slf.GetAncestor().(IService)
|
||||
func (m *Module) GetService() IService {
|
||||
return m.GetAncestor().(IService)
|
||||
}
|
||||
|
||||
func (slf *Module) GetEventProcessor() event.IEventProcessor{
|
||||
return slf.eventHandler.GetEventProcessor()
|
||||
func (m *Module) GetEventProcessor() event.IEventProcessor{
|
||||
return m.eventHandler.GetEventProcessor()
|
||||
}
|
||||
|
||||
func (slf *Module) NotifyEvent(ev *event.Event){
|
||||
slf.eventHandler.NotifyEvent(ev)
|
||||
func (m *Module) NotifyEvent(ev *event.Event){
|
||||
m.eventHandler.NotifyEvent(ev)
|
||||
}
|
||||
|
||||
func (slf *Module) GetEventHandler() event.IEventHandler{
|
||||
return slf.eventHandler
|
||||
func (m *Module) GetEventHandler() event.IEventHandler{
|
||||
return m.eventHandler
|
||||
}
|
||||
@@ -19,10 +19,10 @@ var closeSig chan bool
|
||||
var timerDispatcherLen = 10000
|
||||
|
||||
type IService interface {
|
||||
Init(iservice IService,getClientFun rpc.FuncRpcClient,getServerFun rpc.FuncRpcServer,serviceCfg interface{})
|
||||
Init(iService IService,getClientFun rpc.FuncRpcClient,getServerFun rpc.FuncRpcServer,serviceCfg interface{})
|
||||
SetName(serviceName string)
|
||||
GetName() string
|
||||
OnSetup(iservice IService)
|
||||
OnSetup(iService IService)
|
||||
OnInit() error
|
||||
OnRelease()
|
||||
Wait()
|
||||
@@ -33,115 +33,112 @@ type IService interface {
|
||||
GetProfiler() *profiler.Profiler
|
||||
}
|
||||
|
||||
|
||||
type Service struct {
|
||||
Module
|
||||
rpc.RpcHandler //rpc
|
||||
name string //service name
|
||||
wg sync.WaitGroup
|
||||
serviceCfg interface{}
|
||||
gorouterNum int32
|
||||
startStatus bool
|
||||
rpc.RpcHandler //rpc
|
||||
name string //service name
|
||||
wg sync.WaitGroup
|
||||
serviceCfg interface{}
|
||||
goroutineNum int32
|
||||
startStatus bool
|
||||
eventProcessor event.IEventProcessor
|
||||
|
||||
//eventProcessor event.EventProcessor //事件接收者
|
||||
profiler *profiler.Profiler //性能分析器
|
||||
}
|
||||
|
||||
func (slf *Service) OnSetup(iservice IService){
|
||||
if iservice.GetName() == "" {
|
||||
slf.name = reflect.Indirect(reflect.ValueOf(iservice)).Type().Name()
|
||||
func (s *Service) OnSetup(iService IService){
|
||||
if iService.GetName() == "" {
|
||||
s.name = reflect.Indirect(reflect.ValueOf(iService)).Type().Name()
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Service) OpenProfiler() {
|
||||
slf.profiler = profiler.RegProfiler(slf.GetName())
|
||||
if slf.profiler==nil {
|
||||
log.Fatal("rofiler.RegProfiler %s fail.",slf.GetName())
|
||||
func (s *Service) OpenProfiler() {
|
||||
s.profiler = profiler.RegProfiler(s.GetName())
|
||||
if s.profiler==nil {
|
||||
log.Fatal("rofiler.RegProfiler %s fail.", s.GetName())
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Service) Init(iservice IService,getClientFun rpc.FuncRpcClient,getServerFun rpc.FuncRpcServer,serviceCfg interface{}) {
|
||||
slf.dispatcher =timer.NewDispatcher(timerDispatcherLen)
|
||||
func (s *Service) Init(iService IService,getClientFun rpc.FuncRpcClient,getServerFun rpc.FuncRpcServer,serviceCfg interface{}) {
|
||||
s.dispatcher =timer.NewDispatcher(timerDispatcherLen)
|
||||
|
||||
slf.InitRpcHandler(iservice.(rpc.IRpcHandler),getClientFun,getServerFun)
|
||||
slf.self = iservice.(IModule)
|
||||
s.InitRpcHandler(iService.(rpc.IRpcHandler),getClientFun,getServerFun)
|
||||
s.self = iService.(IModule)
|
||||
//初始化祖先
|
||||
slf.ancestor = iservice.(IModule)
|
||||
slf.seedModuleId =InitModuleId
|
||||
slf.descendants = map[int64]IModule{}
|
||||
slf.serviceCfg = serviceCfg
|
||||
slf.gorouterNum = 1
|
||||
slf.eventProcessor = event.NewEventProcessor()
|
||||
slf.eventHandler = event.NewEventHandler()
|
||||
slf.eventHandler.Init(slf.eventProcessor)
|
||||
s.ancestor = iService.(IModule)
|
||||
s.seedModuleId =InitModuleId
|
||||
s.descendants = map[int64]IModule{}
|
||||
s.serviceCfg = serviceCfg
|
||||
s.goroutineNum = 1
|
||||
s.eventProcessor = event.NewEventProcessor()
|
||||
s.eventHandler = event.NewEventHandler()
|
||||
s.eventHandler.Init(s.eventProcessor)
|
||||
}
|
||||
|
||||
func (slf *Service) SetGoRouterNum(gorouterNum int32) bool {
|
||||
func (s *Service) SetGoRouterNum(goroutineNum int32) bool {
|
||||
//已经开始状态不允许修改协程数量,打开性能分析器不允许开多线程
|
||||
if slf.startStatus == true || slf.profiler!=nil {
|
||||
if s.startStatus == true || s.profiler!=nil {
|
||||
log.Error("open profiler mode is not allowed to set Multi-coroutine.")
|
||||
return false
|
||||
}
|
||||
|
||||
slf.gorouterNum = gorouterNum
|
||||
s.goroutineNum = goroutineNum
|
||||
return true
|
||||
}
|
||||
|
||||
func (slf *Service) Start() {
|
||||
slf.startStatus = true
|
||||
for i:=int32(0);i<slf.gorouterNum;i++{
|
||||
slf.wg.Add(1)
|
||||
func (s *Service) Start() {
|
||||
s.startStatus = true
|
||||
for i:=int32(0);i< s.goroutineNum;i++{
|
||||
s.wg.Add(1)
|
||||
go func(){
|
||||
slf.Run()
|
||||
s.Run()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Service) Run() {
|
||||
log.Debug("Start running Service %s.",slf.GetName())
|
||||
defer slf.wg.Done()
|
||||
func (s *Service) Run() {
|
||||
log.Debug("Start running Service %s.", s.GetName())
|
||||
defer s.wg.Done()
|
||||
var bStop = false
|
||||
for{
|
||||
rpcRequestChan := slf.GetRpcRequestChan()
|
||||
rpcResponeCallBack := slf.GetRpcResponeChan()
|
||||
eventChan := slf.eventProcessor.GetEventChan()
|
||||
rpcRequestChan := s.GetRpcRequestChan()
|
||||
rpcResponseCallBack := s.GetRpcResponseChan()
|
||||
eventChan := s.eventProcessor.GetEventChan()
|
||||
var analyzer *profiler.Analyzer
|
||||
select {
|
||||
case <- closeSig:
|
||||
bStop = true
|
||||
case rpcRequest :=<- rpcRequestChan:
|
||||
if slf.profiler!=nil {
|
||||
analyzer = slf.profiler.Push("Req_"+rpcRequest.RpcRequestData.GetServiceMethod())
|
||||
if s.profiler!=nil {
|
||||
analyzer = s.profiler.Push("Req_"+rpcRequest.RpcRequestData.GetServiceMethod())
|
||||
}
|
||||
|
||||
slf.GetRpcHandler().HandlerRpcRequest(rpcRequest)
|
||||
s.GetRpcHandler().HandlerRpcRequest(rpcRequest)
|
||||
if analyzer!=nil {
|
||||
analyzer.Pop()
|
||||
analyzer = nil
|
||||
}
|
||||
case rpcResponeCB := <- rpcResponeCallBack:
|
||||
if slf.profiler!=nil {
|
||||
analyzer = slf.profiler.Push("Res_" + rpcResponeCB.ServiceMethod)
|
||||
case rpcResponseCB := <-rpcResponseCallBack:
|
||||
if s.profiler!=nil {
|
||||
analyzer = s.profiler.Push("Res_" + rpcResponseCB.ServiceMethod)
|
||||
}
|
||||
slf.GetRpcHandler().HandlerRpcResponeCB(rpcResponeCB)
|
||||
s.GetRpcHandler().HandlerRpcResponseCB(rpcResponseCB)
|
||||
if analyzer!=nil {
|
||||
analyzer.Pop()
|
||||
analyzer = nil
|
||||
}
|
||||
case ev := <- eventChan:
|
||||
if slf.profiler!=nil {
|
||||
analyzer = slf.profiler.Push(fmt.Sprintf("Event_%d", int(ev.Type)))
|
||||
if s.profiler!=nil {
|
||||
analyzer = s.profiler.Push(fmt.Sprintf("Event_%d", int(ev.Type)))
|
||||
}
|
||||
slf.eventProcessor.EventHandler(ev)
|
||||
s.eventProcessor.EventHandler(ev)
|
||||
if analyzer!=nil {
|
||||
analyzer.Pop()
|
||||
analyzer = nil
|
||||
}
|
||||
case t := <- slf.dispatcher.ChanTimer:
|
||||
case t := <- s.dispatcher.ChanTimer:
|
||||
if t.IsClose() == false {
|
||||
if slf.profiler != nil {
|
||||
analyzer = slf.profiler.Push(fmt.Sprintf("Timer_%s", t.AdditionData.(*timer.Timer).GetFunctionName()))
|
||||
if s.profiler != nil {
|
||||
analyzer = s.profiler.Push(fmt.Sprintf("Timer_%s", t.AdditionData.(*timer.Timer).GetFunctionName()))
|
||||
}
|
||||
t.AdditionData.(*timer.Timer).Cb()
|
||||
if analyzer != nil {
|
||||
@@ -153,26 +150,25 @@ func (slf *Service) Run() {
|
||||
}
|
||||
|
||||
if bStop == true {
|
||||
if atomic.AddInt32(&slf.gorouterNum,-1)<=0 {
|
||||
slf.startStatus = false
|
||||
slf.Release()
|
||||
slf.OnRelease()
|
||||
if atomic.AddInt32(&s.goroutineNum,-1)<=0 {
|
||||
s.startStatus = false
|
||||
s.Release()
|
||||
s.OnRelease()
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Service) GetName() string{
|
||||
return slf.name
|
||||
func (s *Service) GetName() string{
|
||||
return s.name
|
||||
}
|
||||
|
||||
func (slf *Service) SetName(serviceName string) {
|
||||
slf.name = serviceName
|
||||
func (s *Service) SetName(serviceName string) {
|
||||
s.name = serviceName
|
||||
}
|
||||
|
||||
|
||||
func (slf *Service) Release(){
|
||||
func (s *Service) Release(){
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 4096)
|
||||
@@ -181,36 +177,37 @@ func (slf *Service) Release(){
|
||||
log.Error("core dump info:%+v\n",err)
|
||||
}
|
||||
}()
|
||||
slf.self.OnRelease()
|
||||
log.Debug("Release Service %s.",slf.GetName())
|
||||
s.self.OnRelease()
|
||||
log.Debug("Release Service %s.", s.GetName())
|
||||
}
|
||||
|
||||
func (slf *Service) OnRelease(){
|
||||
func (s *Service) OnRelease(){
|
||||
}
|
||||
|
||||
func (slf *Service) OnInit() error {
|
||||
func (s *Service) OnInit() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *Service) Wait(){
|
||||
slf.wg.Wait()
|
||||
func (s *Service) Wait(){
|
||||
s.wg.Wait()
|
||||
}
|
||||
|
||||
func (slf *Service) GetServiceCfg()interface{}{
|
||||
return slf.serviceCfg
|
||||
func (s *Service) GetServiceCfg()interface{}{
|
||||
return s.serviceCfg
|
||||
}
|
||||
|
||||
func (slf *Service) GetProfiler() *profiler.Profiler{
|
||||
return slf.profiler
|
||||
func (s *Service) GetProfiler() *profiler.Profiler{
|
||||
return s.profiler
|
||||
}
|
||||
|
||||
func (slf *Service) RegEventReciverFunc(eventType event.EventType,reciver event.IEventHandler,callback event.EventCallBack){
|
||||
slf.eventProcessor.RegEventReciverFunc(eventType,reciver,callback)
|
||||
func (s *Service) RegEventReceiverFunc(eventType event.EventType, receiver event.IEventHandler,callback event.EventCallBack){
|
||||
s.eventProcessor.RegEventReciverFunc(eventType, receiver,callback)
|
||||
}
|
||||
|
||||
func (slf *Service) UnRegEventReciverFun(eventType event.EventType,reciver event.IEventHandler){
|
||||
slf.eventProcessor.UnRegEventReciverFun(eventType,reciver)
|
||||
func (s *Service) UnRegEventReceiverFunc(eventType event.EventType, receiver event.IEventHandler){
|
||||
s.eventProcessor.UnRegEventReciverFun(eventType, receiver)
|
||||
}
|
||||
func (slf *Service) IsSingleCoroutine() bool {
|
||||
return slf.gorouterNum == 1
|
||||
|
||||
func (s *Service) IsSingleCoroutine() bool {
|
||||
return s.goroutineNum == 1
|
||||
}
|
||||
@@ -15,7 +15,6 @@ func Init(chanCloseSig chan bool) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func Setup(s IService) bool {
|
||||
_,ok := mapServiceName[s.GetName()]
|
||||
if ok == true {
|
||||
@@ -26,8 +25,8 @@ func Setup(s IService) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func GetService(servicename string) IService {
|
||||
s,ok := mapServiceName[servicename]
|
||||
func GetService(serviceName string) IService {
|
||||
s,ok := mapServiceName[serviceName]
|
||||
if ok == false {
|
||||
return nil
|
||||
}
|
||||
@@ -35,7 +34,6 @@ func GetService(servicename string) IService {
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
func Start(){
|
||||
for _,s := range mapServiceName {
|
||||
s.Start()
|
||||
@@ -47,4 +45,3 @@ func WaitStop(){
|
||||
s.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ type HttpClientModule struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type HttpRespone struct {
|
||||
type HttpResponse struct {
|
||||
Err error
|
||||
Header http.Header
|
||||
StatusCode int
|
||||
@@ -26,11 +26,11 @@ type HttpRespone struct {
|
||||
Body []byte
|
||||
}
|
||||
|
||||
type SyncHttpRespone struct {
|
||||
resp chan HttpRespone
|
||||
type SyncHttpResponse struct {
|
||||
resp chan HttpResponse
|
||||
}
|
||||
|
||||
func (slf *SyncHttpRespone) Get(timeoutMs int) HttpRespone {
|
||||
func (slf *SyncHttpResponse) Get(timeoutMs int) HttpResponse {
|
||||
timerC := time.NewTicker(time.Millisecond * time.Duration(timeoutMs)).C
|
||||
select {
|
||||
case <-timerC:
|
||||
@@ -38,21 +38,21 @@ func (slf *SyncHttpRespone) Get(timeoutMs int) HttpRespone {
|
||||
case rsp := <-slf.resp:
|
||||
return rsp
|
||||
}
|
||||
return HttpRespone{
|
||||
return HttpResponse{
|
||||
Err: fmt.Errorf("Getting the return result timeout [%d]ms", timeoutMs),
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *HttpClientModule) Init(maxpool int, proxyUrl string) {
|
||||
func (m *HttpClientModule) Init(maxpool int, proxyUrl string) {
|
||||
type ProxyFun func(_ *http.Request) (*url.URL, error)
|
||||
var proxyfun ProxyFun
|
||||
var proxyFun ProxyFun
|
||||
if proxyUrl != "" {
|
||||
proxyfun = func(_ *http.Request) (*url.URL, error) {
|
||||
proxyFun = func(_ *http.Request) (*url.URL, error) {
|
||||
return url.Parse(proxyUrl)
|
||||
}
|
||||
}
|
||||
|
||||
slf.client = &http.Client{
|
||||
m.client = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 5 * time.Second,
|
||||
@@ -61,33 +61,33 @@ func (slf *HttpClientModule) Init(maxpool int, proxyUrl string) {
|
||||
MaxIdleConns: maxpool,
|
||||
MaxIdleConnsPerHost: maxpool,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
Proxy: proxyfun,
|
||||
Proxy: proxyFun,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
},
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *HttpClientModule) SetTimeOut(value time.Duration) {
|
||||
slf.client.Timeout = value
|
||||
func (m *HttpClientModule) SetTimeOut(value time.Duration) {
|
||||
m.client.Timeout = value
|
||||
}
|
||||
|
||||
func (slf *HttpClientModule) SyncRequest(method string, url string, body []byte, header http.Header) SyncHttpRespone {
|
||||
ret := SyncHttpRespone{
|
||||
resp: make(chan HttpRespone, 1),
|
||||
func (m *HttpClientModule) SyncRequest(method string, url string, body []byte, header http.Header) SyncHttpResponse {
|
||||
ret := SyncHttpResponse{
|
||||
resp: make(chan HttpResponse, 1),
|
||||
}
|
||||
go func() {
|
||||
rsp := slf.Request(method, url, body, header)
|
||||
rsp := m.Request(method, url, body, header)
|
||||
ret.resp <- rsp
|
||||
}()
|
||||
return ret
|
||||
}
|
||||
|
||||
func (slf *HttpClientModule) Request(method string, url string, body []byte, header http.Header) HttpRespone {
|
||||
if slf.client == nil {
|
||||
func (m *HttpClientModule) Request(method string, url string, body []byte, header http.Header) HttpResponse {
|
||||
if m.client == nil {
|
||||
panic("Call the init function first")
|
||||
}
|
||||
ret := HttpRespone{}
|
||||
ret := HttpResponse{}
|
||||
req, err := http.NewRequest(method, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
ret.Err = err
|
||||
@@ -96,7 +96,7 @@ func (slf *HttpClientModule) Request(method string, url string, body []byte, hea
|
||||
if header != nil {
|
||||
req.Header = header
|
||||
}
|
||||
rsp, err := slf.client.Do(req)
|
||||
rsp, err := m.client.Do(req)
|
||||
if err != nil {
|
||||
ret.Err = err
|
||||
return ret
|
||||
|
||||
@@ -33,7 +33,6 @@ func (slf *MangoModule) Init(url string,sessionNum uint32,dialTimeout time.Durat
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
func (slf *MangoModule) Take() *Session{
|
||||
return slf.dailContext.Take()
|
||||
}
|
||||
|
||||
@@ -64,46 +64,46 @@ type DataSetList struct {
|
||||
}
|
||||
|
||||
|
||||
type dbcontrol interface {
|
||||
type dbControl interface {
|
||||
Exec(query string, args ...interface{}) (sql.Result, error)
|
||||
Query(query string, args ...interface{}) (*sql.Rows, error)
|
||||
}
|
||||
|
||||
|
||||
func (slf *MySQLModule) Init( url string, userName string, password string, dbname string,maxConn int) error {
|
||||
slf.url = url
|
||||
slf.username = userName
|
||||
slf.password = password
|
||||
slf.dbname = dbname
|
||||
slf.pingCoroutine = PingExecute{tickerPing : time.NewTicker(5*time.Second), pintExit : make(chan bool, 1)}
|
||||
func (m *MySQLModule) Init( url string, userName string, password string, dbname string,maxConn int) error {
|
||||
m.url = url
|
||||
m.username = userName
|
||||
m.password = password
|
||||
m.dbname = dbname
|
||||
m.pingCoroutine = PingExecute{tickerPing : time.NewTicker(5*time.Second), pintExit : make(chan bool, 1)}
|
||||
|
||||
return slf.connect(maxConn)
|
||||
return m.connect(maxConn)
|
||||
}
|
||||
|
||||
func (slf *MySQLModule) SetQuerySlowTime(slowDuration time.Duration) {
|
||||
slf.slowDuration = slowDuration
|
||||
func (m *MySQLModule) SetQuerySlowTime(slowDuration time.Duration) {
|
||||
m.slowDuration = slowDuration
|
||||
}
|
||||
|
||||
func (slf *MySQLModule) Query(strQuery string, args ...interface{}) (*DataSetList, error) {
|
||||
return query(slf.slowDuration,slf.db,strQuery,args...)
|
||||
func (m *MySQLModule) Query(strQuery string, args ...interface{}) (*DataSetList, error) {
|
||||
return query(m.slowDuration, m.db,strQuery,args...)
|
||||
}
|
||||
|
||||
// Exec ...
|
||||
func (slf *MySQLModule) Exec(strSql string, args ...interface{}) (*DBResult, error) {
|
||||
return exec(slf.slowDuration,slf.db,strSql,args...)
|
||||
func (m *MySQLModule) Exec(strSql string, args ...interface{}) (*DBResult, error) {
|
||||
return exec(m.slowDuration, m.db,strSql,args...)
|
||||
}
|
||||
|
||||
// Begin starts a transaction.
|
||||
func (slf *MySQLModule) Begin() (*Tx, error) {
|
||||
var txDBMoudule Tx
|
||||
txdb, err := slf.db.Begin()
|
||||
func (m *MySQLModule) Begin() (*Tx, error) {
|
||||
var txDBModule Tx
|
||||
txDb, err := m.db.Begin()
|
||||
if err != nil {
|
||||
log.Error("Begin error:%s", err.Error())
|
||||
return &txDBMoudule, err
|
||||
return &txDBModule, err
|
||||
}
|
||||
txDBMoudule.slowDuration = slf.slowDuration
|
||||
txDBMoudule.tx = txdb
|
||||
return &txDBMoudule, nil
|
||||
txDBModule.slowDuration = m.slowDuration
|
||||
txDBModule.tx = txDb
|
||||
return &txDBModule, nil
|
||||
}
|
||||
|
||||
// Rollback aborts the transaction.
|
||||
@@ -116,7 +116,6 @@ func (slf *Tx) Commit() error {
|
||||
return slf.tx.Commit()
|
||||
}
|
||||
|
||||
|
||||
// QueryEx executes a query that return rows.
|
||||
func (slf *Tx) Query(strQuery string, args ...interface{}) (*DataSetList, error) {
|
||||
return query(slf.slowDuration,slf.tx,strQuery,args...)
|
||||
@@ -127,14 +126,13 @@ func (slf *Tx) Exec(strSql string, args ...interface{}) (*DBResult, error) {
|
||||
return exec(slf.slowDuration,slf.tx,strSql,args...)
|
||||
}
|
||||
|
||||
|
||||
// Connect ...
|
||||
func (slf *MySQLModule) connect(maxConn int) error {
|
||||
func (m *MySQLModule) connect(maxConn int) error {
|
||||
cmd := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true&loc=%s&readTimeout=30s&timeout=15s&writeTimeout=30s",
|
||||
slf.username,
|
||||
slf.password,
|
||||
slf.url,
|
||||
slf.dbname,
|
||||
m.username,
|
||||
m.password,
|
||||
m.url,
|
||||
m.dbname,
|
||||
url.QueryEscape(time.Local.String()))
|
||||
|
||||
db, err := sql.Open("mysql", cmd)
|
||||
@@ -146,25 +144,25 @@ func (slf *MySQLModule) connect(maxConn int) error {
|
||||
db.Close()
|
||||
return err
|
||||
}
|
||||
slf.db = db
|
||||
m.db = db
|
||||
db.SetMaxOpenConns(maxConn)
|
||||
db.SetMaxIdleConns(maxConn)
|
||||
db.SetConnMaxLifetime(time.Second * 90)
|
||||
|
||||
go slf.runPing()
|
||||
go m.runPing()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *MySQLModule) runPing() {
|
||||
func (m *MySQLModule) runPing() {
|
||||
for {
|
||||
select {
|
||||
case <-slf.pingCoroutine.pintExit:
|
||||
log.Error("RunPing stopping %s...", fmt.Sprintf("%T", slf))
|
||||
case <-m.pingCoroutine.pintExit:
|
||||
log.Error("RunPing stopping %s...", fmt.Sprintf("%T", m))
|
||||
return
|
||||
case <-slf.pingCoroutine.tickerPing.C:
|
||||
if slf.db != nil {
|
||||
slf.db.Ping()
|
||||
case <-m.pingCoroutine.tickerPing.C:
|
||||
if m.db != nil {
|
||||
m.db.Ping()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,7 +211,6 @@ func checkArgs(args ...interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func checkSlow(slowDuration time.Duration,Time time.Duration) bool {
|
||||
if slowDuration != 0 && Time >=slowDuration {
|
||||
return true
|
||||
@@ -221,7 +218,7 @@ func checkSlow(slowDuration time.Duration,Time time.Duration) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func query(slowDuration time.Duration,db dbcontrol,strQuery string, args ...interface{}) (*DataSetList, error) {
|
||||
func query(slowDuration time.Duration,db dbControl,strQuery string, args ...interface{}) (*DataSetList, error) {
|
||||
datasetList := DataSetList{}
|
||||
datasetList.tag = "json"
|
||||
datasetList.blur = true
|
||||
@@ -294,7 +291,7 @@ func query(slowDuration time.Duration,db dbcontrol,strQuery string, args ...inte
|
||||
return &datasetList, nil
|
||||
}
|
||||
|
||||
func exec(slowDuration time.Duration,db dbcontrol,strSql string, args ...interface{}) (*DBResult, error) {
|
||||
func exec(slowDuration time.Duration,db dbControl,strSql string, args ...interface{}) (*DBResult, error) {
|
||||
ret := &DBResult{}
|
||||
if db == nil {
|
||||
log.Error("cannot connect database:%s", strSql)
|
||||
@@ -323,9 +320,9 @@ func exec(slowDuration time.Duration,db dbcontrol,strSql string, args ...interfa
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (slf *DataSetList) UnMarshal(args ...interface{}) error {
|
||||
if len(slf.dataSetList) != len(args) {
|
||||
return errors.New(fmt.Sprintf("Data set len(%d,%d) is not equal to args!", len(slf.dataSetList), len(args)))
|
||||
func (ds *DataSetList) UnMarshal(args ...interface{}) error {
|
||||
if len(ds.dataSetList) != len(args) {
|
||||
return errors.New(fmt.Sprintf("Data set len(%d,%d) is not equal to args!", len(ds.dataSetList), len(args)))
|
||||
}
|
||||
|
||||
for _, out := range args {
|
||||
@@ -339,26 +336,26 @@ func (slf *DataSetList) UnMarshal(args ...interface{}) error {
|
||||
}
|
||||
|
||||
if v.Elem().Kind() == reflect.Struct {
|
||||
err := slf.rowData2interface(0, slf.dataSetList[slf.currentDataSetIdx].RowInfo, v)
|
||||
err := ds.rowData2interface(0, ds.dataSetList[ds.currentDataSetIdx].RowInfo, v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if v.Elem().Kind() == reflect.Slice {
|
||||
err := slf.slice2interface(out)
|
||||
err := ds.slice2interface(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
slf.currentDataSetIdx = slf.currentDataSetIdx + 1
|
||||
ds.currentDataSetIdx = ds.currentDataSetIdx + 1
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *DataSetList) slice2interface(in interface{}) error {
|
||||
length := slf.dataSetList[slf.currentDataSetIdx].rowNum
|
||||
func (ds *DataSetList) slice2interface(in interface{}) error {
|
||||
length := ds.dataSetList[ds.currentDataSetIdx].rowNum
|
||||
if length == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -378,7 +375,7 @@ func (slf *DataSetList) slice2interface(in interface{}) error {
|
||||
idxv = idxv.Addr()
|
||||
}
|
||||
|
||||
err := slf.rowData2interface(i, slf.dataSetList[slf.currentDataSetIdx].RowInfo, idxv)
|
||||
err := ds.rowData2interface(i, ds.dataSetList[ds.currentDataSetIdx].RowInfo, idxv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -387,7 +384,7 @@ func (slf *DataSetList) slice2interface(in interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *DataSetList) rowData2interface(rowIdx int, m map[string][]interface{}, v reflect.Value) error {
|
||||
func (ds *DataSetList) rowData2interface(rowIdx int, m map[string][]interface{}, v reflect.Value) error {
|
||||
t := v.Type()
|
||||
val := v.Elem()
|
||||
typ := t.Elem()
|
||||
@@ -399,7 +396,7 @@ func (slf *DataSetList) rowData2interface(rowIdx int, m map[string][]interface{}
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
value := val.Field(i)
|
||||
kind := value.Kind()
|
||||
tag := typ.Field(i).Tag.Get(slf.tag)
|
||||
tag := typ.Field(i).Tag.Get(ds.tag)
|
||||
if tag == "" {
|
||||
tag = typ.Field(i).Name
|
||||
}
|
||||
@@ -408,7 +405,7 @@ func (slf *DataSetList) rowData2interface(rowIdx int, m map[string][]interface{}
|
||||
vtag := strings.ToLower(tag)
|
||||
columnData, ok := m[vtag]
|
||||
if ok == false {
|
||||
if !slf.blur {
|
||||
if !ds.blur {
|
||||
return fmt.Errorf("Cannot find filed name %s!", vtag)
|
||||
}
|
||||
continue
|
||||
@@ -418,7 +415,7 @@ func (slf *DataSetList) rowData2interface(rowIdx int, m map[string][]interface{}
|
||||
}
|
||||
meta := columnData[rowIdx].(*sql.NullString)
|
||||
if !ok {
|
||||
if !slf.blur {
|
||||
if !ds.blur {
|
||||
return fmt.Errorf("No corresponding field was found in the result set %s!", tag)
|
||||
}
|
||||
continue
|
||||
|
||||
@@ -35,10 +35,9 @@ func (slf *RetMapString) Get() (error, map[string]bool) {
|
||||
return ret.resultError, ret.resultMapStringBool
|
||||
}
|
||||
|
||||
|
||||
type RedisModule struct {
|
||||
service.Module
|
||||
redispool *redis.Pool
|
||||
redisPool *redis.Pool
|
||||
}
|
||||
|
||||
// ConfigRedis 服务器配置
|
||||
@@ -52,9 +51,9 @@ type ConfigRedis struct {
|
||||
IdleTimeout int //最大的空闲连接等待时间,超过此时间后,空闲连接将被关闭
|
||||
}
|
||||
|
||||
func (slf *RedisModule) Init(redisCfg *ConfigRedis) {
|
||||
func (m *RedisModule) Init(redisCfg *ConfigRedis) {
|
||||
redisServer := fmt.Sprintf("%s:%d",redisCfg.IP, redisCfg.Port)
|
||||
slf.redispool = &redis.Pool{
|
||||
m.redisPool = &redis.Pool{
|
||||
Wait: true,
|
||||
MaxIdle: redisCfg.MaxIdle,
|
||||
MaxActive: redisCfg.MaxActive,
|
||||
@@ -88,13 +87,12 @@ func (slf *RedisModule) Init(redisCfg *ConfigRedis) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) getConn() (redis.Conn, error) {
|
||||
if slf.redispool == nil {
|
||||
func (m *RedisModule) getConn() (redis.Conn, error) {
|
||||
if m.redisPool == nil {
|
||||
log.Error("Not Init RedisModule")
|
||||
return nil, fmt.Errorf("Not Init RedisModule")
|
||||
}
|
||||
conn := slf.redispool.Get()
|
||||
conn := m.redisPool.Get()
|
||||
if conn == nil {
|
||||
log.Error("Cannot get connection")
|
||||
return nil, fmt.Errorf("Cannot get connection")
|
||||
@@ -111,15 +109,14 @@ func (slf *RedisModule) getConn() (redis.Conn, error) {
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) TestPingRedis() error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) TestPingRedis() error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
err = slf.redispool.TestOnBorrow(conn, time.Now())
|
||||
err = m.redisPool.TestOnBorrow(conn, time.Now())
|
||||
if err != nil {
|
||||
log.Error("TestOnBorrow fail,reason:%v", err)
|
||||
return err
|
||||
@@ -128,40 +125,38 @@ func (slf *RedisModule) TestPingRedis() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) SetString(key, value interface{}) (err error) {
|
||||
err = slf.setStringByExpire(key, value, "-1")
|
||||
func (m *RedisModule) SetString(key, value interface{}) (err error) {
|
||||
err = m.setStringByExpire(key, value, "-1")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) SetStringExpire(key, value, expire string) (err error) {
|
||||
err = slf.setStringByExpire(key, value, expire)
|
||||
func (m *RedisModule) SetStringExpire(key, value, expire string) (err error) {
|
||||
err = m.setStringByExpire(key, value, expire)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RedisModule) SetStringJSON(key interface{}, val interface{}) (err error) {
|
||||
err = slf.SetStringJSONExpire(key, val, "-1")
|
||||
func (m *RedisModule) SetStringJSON(key interface{}, val interface{}) (err error) {
|
||||
err = m.SetStringJSONExpire(key, val, "-1")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RedisModule) SetStringJSONExpire(key interface{}, val interface{}, expire string) (err error) {
|
||||
func (m *RedisModule) SetStringJSONExpire(key interface{}, val interface{}, expire string) (err error) {
|
||||
if temp, err := json.Marshal(val); err == nil {
|
||||
err = slf.setStringByExpire(key, string(temp), expire)
|
||||
err = m.setStringByExpire(key, string(temp), expire)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RedisModule) setStringByExpire(key, value, expire interface{}) error {
|
||||
func (m *RedisModule) setStringByExpire(key, value, expire interface{}) error {
|
||||
if key == "" {
|
||||
return errors.New("Key Is Empty")
|
||||
}
|
||||
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -190,25 +185,23 @@ func (slf *RedisModule) setStringByExpire(key, value, expire interface{}) error
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) SetStringMap(mapInfo map[interface{}]interface{}) (err error) {
|
||||
err = slf.setMuchStringByExpire(mapInfo, "-1")
|
||||
func (m *RedisModule) SetStringMap(mapInfo map[interface{}]interface{}) (err error) {
|
||||
err = m.setMuchStringByExpire(mapInfo, "-1")
|
||||
return
|
||||
}
|
||||
|
||||
func (slf *RedisModule) SetMuchStringExpire(mapInfo map[interface{}]interface{}, ex string) (err error) {
|
||||
err = slf.setMuchStringByExpire(mapInfo, ex)
|
||||
func (m *RedisModule) SetMuchStringExpire(mapInfo map[interface{}]interface{}, ex string) (err error) {
|
||||
err = m.setMuchStringByExpire(mapInfo, ex)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) setMuchStringByExpire(mapInfo map[interface{}]interface{}, expire string) error {
|
||||
func (m *RedisModule) setMuchStringByExpire(mapInfo map[interface{}]interface{}, expire string) error {
|
||||
if len(mapInfo) <= 0 {
|
||||
log.Error("setMuchStringByExpire Info Is Empty")
|
||||
return errors.New("setMuchStringByExpire Info Is Empty")
|
||||
}
|
||||
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -243,9 +236,8 @@ func (slf *RedisModule) setMuchStringByExpire(mapInfo map[interface{}]interface{
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) GetString(key interface{}) (string, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) GetString(key interface{}) (string, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -265,9 +257,8 @@ func (slf *RedisModule) GetString(key interface{}) (string, error) {
|
||||
return redis.String(ret,nil)
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) GetStringJSON(key string, st interface{}) error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) GetStringJSON(key string, st interface{}) error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -299,13 +290,12 @@ func (slf *RedisModule) GetStringJSON(key string, st interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) GetStringMap(keys []string) (retMap map[string]string, err error) {
|
||||
func (m *RedisModule) GetStringMap(keys []string) (retMap map[string]string, err error) {
|
||||
if len(keys) <= 0 {
|
||||
err = errors.New("Func[GetMuchRedisString] Keys Is Empty")
|
||||
return
|
||||
}
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -352,9 +342,8 @@ func (slf *RedisModule) GetStringMap(keys []string) (retMap map[string]string, e
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) ExistsKey(key interface{}) (bool, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ExistsKey(key interface{}) (bool, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -374,8 +363,8 @@ func (slf *RedisModule) ExistsKey(key interface{}) (bool, error) {
|
||||
return retValue != 0, nil
|
||||
}
|
||||
|
||||
func (slf *RedisModule) DelString(key interface{}) error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) DelString(key interface{}) error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -401,14 +390,13 @@ func (slf *RedisModule) DelString(key interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) DelStringKeyList(keys []interface{}) (map[interface{}]bool, error) {
|
||||
func (m *RedisModule) DelStringKeyList(keys []interface{}) (map[interface{}]bool, error) {
|
||||
if len(keys) <= 0 {
|
||||
err := errors.New("Func[DelMuchRedisString] Keys Is Empty")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -452,11 +440,11 @@ func (slf *RedisModule) DelStringKeyList(keys []interface{}) (map[interface{}]bo
|
||||
return retMap, nil
|
||||
}
|
||||
|
||||
func (slf *RedisModule) SetHash(redisKey, hashKey, value interface{}) error {
|
||||
func (m *RedisModule) SetHash(redisKey, hashKey, value interface{}) error {
|
||||
if redisKey == "" || hashKey == "" {
|
||||
return errors.New("Key Is Empty")
|
||||
}
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -470,13 +458,12 @@ func (slf *RedisModule) SetHash(redisKey, hashKey, value interface{}) error {
|
||||
return retErr
|
||||
}
|
||||
|
||||
|
||||
//GetRedisAllHashJSON ...
|
||||
func (slf *RedisModule) GetAllHashJSON(redisKey string) (map[string]string, error) {
|
||||
func (m *RedisModule) GetAllHashJSON(redisKey string) (map[string]string, error) {
|
||||
if redisKey == "" {
|
||||
return nil, errors.New("Key Is Empty")
|
||||
}
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -491,13 +478,12 @@ func (slf *RedisModule) GetAllHashJSON(redisKey string) (map[string]string, erro
|
||||
return redis.StringMap(value, err)
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) GetHash(redisKey interface{}, fieldKey interface{}) (string, error) {
|
||||
func (m *RedisModule) GetHash(redisKey interface{}, fieldKey interface{}) (string, error) {
|
||||
if redisKey == "" || fieldKey == "" {
|
||||
log.Error("GetHashValueByKey key is empty!")
|
||||
return "", errors.New("Key Is Empty")
|
||||
}
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -515,13 +501,12 @@ func (slf *RedisModule) GetHash(redisKey interface{}, fieldKey interface{}) (str
|
||||
return redis.String(value,nil)
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) GetMuchHash(args ...interface{}) ([]string, error) {
|
||||
func (m *RedisModule) GetMuchHash(args ...interface{}) ([]string, error) {
|
||||
if len(args) < 2 {
|
||||
log.Error("GetHashValueByHashKeyList key len less than two!")
|
||||
return nil, errors.New("Key Is Empty")
|
||||
}
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -550,7 +535,7 @@ func (slf *RedisModule) GetMuchHash(args ...interface{}) ([]string, error) {
|
||||
return retList, nil
|
||||
}
|
||||
|
||||
func (slf *RedisModule) ScanMatchKeys(cursorValue int, redisKey string, count int) (int, []string, error) {
|
||||
func (m *RedisModule) ScanMatchKeys(cursorValue int, redisKey string, count int) (int, []string, error) {
|
||||
retKeys := []string{}
|
||||
nextCursorValue := 0
|
||||
if redisKey == "" {
|
||||
@@ -558,7 +543,7 @@ func (slf *RedisModule) ScanMatchKeys(cursorValue int, redisKey string, count in
|
||||
return nextCursorValue, nil, errors.New("Key Is Empty")
|
||||
}
|
||||
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nextCursorValue, nil, err
|
||||
}
|
||||
@@ -583,14 +568,13 @@ func (slf *RedisModule) ScanMatchKeys(cursorValue int, redisKey string, count in
|
||||
return nextCursorValue, retKeys, nil
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) SetHashMapJSON(redisKey string, mapFieldValue map[interface{}]interface{}) error {
|
||||
func (m *RedisModule) SetHashMapJSON(redisKey string, mapFieldValue map[interface{}]interface{}) error {
|
||||
if len(mapFieldValue) <= 0 {
|
||||
err := errors.New("Func[SetMuchRedisHashJSON] value Is Empty")
|
||||
return err
|
||||
}
|
||||
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -618,8 +602,8 @@ func (slf *RedisModule) SetHashMapJSON(redisKey string, mapFieldValue map[interf
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RedisModule) DelHash(args ...interface{}) error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) DelHash(args ...interface{}) error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -632,30 +616,30 @@ func (slf *RedisModule) DelHash(args ...interface{}) error {
|
||||
return retErr
|
||||
}
|
||||
|
||||
func (slf *RedisModule) LPushList(args ...interface{}) error {
|
||||
err := slf.setListPush("LPUSH",args...)
|
||||
func (m *RedisModule) LPushList(args ...interface{}) error {
|
||||
err := m.setListPush("LPUSH",args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RedisModule) LPushListJSON(key interface{}, value ...interface{}) error {
|
||||
return slf.setListJSONPush("LPUSH",key,value...)
|
||||
func (m *RedisModule) LPushListJSON(key interface{}, value ...interface{}) error {
|
||||
return m.setListJSONPush("LPUSH",key,value...)
|
||||
}
|
||||
|
||||
func (slf *RedisModule) RPushList(args ...interface{}) error {
|
||||
err := slf.setListPush("RPUSH",args...)
|
||||
func (m *RedisModule) RPushList(args ...interface{}) error {
|
||||
err := m.setListPush("RPUSH",args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RedisModule) RPushListJSON(key interface{}, value ...interface{}) error {
|
||||
return slf.setListJSONPush("RPUSH",key,value...)
|
||||
func (m *RedisModule) RPushListJSON(key interface{}, value ...interface{}) error {
|
||||
return m.setListJSONPush("RPUSH",key,value...)
|
||||
}
|
||||
|
||||
//LPUSH和RPUSH
|
||||
func (slf *RedisModule) setListPush(setType string,args...interface{}) error {
|
||||
func (m *RedisModule) setListPush(setType string,args...interface{}) error {
|
||||
if setType != "LPUSH" && setType != "RPUSH" {
|
||||
return errors.New("Redis List Push Type Error,Must Be LPUSH or RPUSH")
|
||||
}
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -668,7 +652,7 @@ func (slf *RedisModule) setListPush(setType string,args...interface{}) error {
|
||||
return retErr
|
||||
}
|
||||
|
||||
func (slf *RedisModule) setListJSONPush(setType string,key interface{}, value ...interface{}) error {
|
||||
func (m *RedisModule) setListJSONPush(setType string,key interface{}, value ...interface{}) error {
|
||||
args := []interface{}{key}
|
||||
for _,v := range value{
|
||||
jData, err := json.Marshal(v)
|
||||
@@ -678,12 +662,12 @@ func (slf *RedisModule) setListJSONPush(setType string,key interface{}, value ..
|
||||
args = append(args,string(jData))
|
||||
}
|
||||
|
||||
return slf.setListPush(setType,args...)
|
||||
return m.setListPush(setType,args...)
|
||||
}
|
||||
|
||||
// Lrange ...
|
||||
func (slf *RedisModule) LRangeList(key string, start, end int) ([]string, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) LRangeList(key string, start, end int) ([]string, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -699,8 +683,8 @@ func (slf *RedisModule) LRangeList(key string, start, end int) ([]string, error)
|
||||
}
|
||||
|
||||
//获取List的长度
|
||||
func (slf *RedisModule) GetListLen(key string) (int, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) GetListLen(key string) (int, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
@@ -715,8 +699,8 @@ func (slf *RedisModule) GetListLen(key string) (int, error) {
|
||||
}
|
||||
|
||||
//弹出List最后条记录
|
||||
func (slf *RedisModule) RPOPListValue(key string) (string,error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) RPOPListValue(key string) (string,error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return "",err
|
||||
}
|
||||
@@ -725,9 +709,8 @@ func (slf *RedisModule) RPOPListValue(key string) (string,error) {
|
||||
return redis.String(conn.Do("RPOP", key))
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) LTrimList(key string, start, end int) error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) LTrimList(key string, start, end int) error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -741,8 +724,8 @@ func (slf *RedisModule) LTrimList(key string, start, end int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RedisModule) LRangeJSON(key string, start, stop int, data interface{}) error {
|
||||
b, err := slf.LRange(key, start, stop)
|
||||
func (m *RedisModule) LRangeJSON(key string, start, stop int, data interface{}) error {
|
||||
b, err := m.LRange(key, start, stop)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -753,8 +736,8 @@ func (slf *RedisModule) LRangeJSON(key string, start, stop int, data interface{}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RedisModule) LRange(key string, start, stop int) ([]byte, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) LRange(key string, start, stop int) ([]byte, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -768,8 +751,8 @@ func (slf *RedisModule) LRange(key string, start, stop int) ([]byte, error) {
|
||||
}
|
||||
|
||||
//弹出list(消息队列)数据,数据放入out fromLeft表示是否从左侧弹出 block表示是否阻塞 timeout表示阻塞超时
|
||||
func (slf *RedisModule) ListPopJson(key string, fromLeft, block bool, timeout int, out interface{}) error {
|
||||
b, err := slf.ListPop(key, fromLeft, block, timeout)
|
||||
func (m *RedisModule) ListPopJson(key string, fromLeft, block bool, timeout int, out interface{}) error {
|
||||
b, err := m.ListPop(key, fromLeft, block, timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -781,7 +764,7 @@ func (slf *RedisModule) ListPopJson(key string, fromLeft, block bool, timeout in
|
||||
}
|
||||
|
||||
//弹出list(消息队列)数据 fromLeft表示是否从左侧弹出 block表示是否阻塞 timeout表示阻塞超时
|
||||
func (slf *RedisModule) ListPop(key string, fromLeft, block bool, timeout int) ([]byte, error) {
|
||||
func (m *RedisModule) ListPop(key string, fromLeft, block bool, timeout int) ([]byte, error) {
|
||||
cmd := ""
|
||||
if fromLeft {
|
||||
if block {
|
||||
@@ -797,7 +780,7 @@ func (slf *RedisModule) ListPop(key string, fromLeft, block bool, timeout int) (
|
||||
}
|
||||
}
|
||||
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -822,11 +805,10 @@ func (slf *RedisModule) ListPop(key string, fromLeft, block bool, timeout int) (
|
||||
return b, nil
|
||||
}
|
||||
|
||||
|
||||
//有序集合插入Json
|
||||
func (slf *RedisModule) ZADDInsertJson(key string, score float64, value interface{}) error {
|
||||
func (m *RedisModule) ZADDInsertJson(key string, score float64, value interface{}) error {
|
||||
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -844,8 +826,8 @@ func (slf *RedisModule) ZADDInsertJson(key string, score float64, value interfac
|
||||
}
|
||||
|
||||
//有序集合插入
|
||||
func (slf *RedisModule) ZADDInsert(key string, score float64, Data interface{}) error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZADDInsert(key string, score float64, Data interface{}) error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -864,14 +846,14 @@ type ZSetDataWithScore struct {
|
||||
Score float64 `json:"score"`
|
||||
}
|
||||
|
||||
func (slf *RedisModule) ZRangeJSON(key string, start, stop int, ascend bool, withScores bool, data interface{}) error {
|
||||
func (m *RedisModule) ZRangeJSON(key string, start, stop int, ascend bool, withScores bool, data interface{}) error {
|
||||
if withScores {
|
||||
if _, ok := data.(*[]ZSetDataWithScore); !ok {
|
||||
return errors.New("withScores must decode by []ZSetDataWithScore")
|
||||
}
|
||||
}
|
||||
|
||||
b, err := slf.ZRange(key, start, stop, ascend, withScores)
|
||||
b, err := m.ZRange(key, start, stop, ascend, withScores)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -884,8 +866,8 @@ func (slf *RedisModule) ZRangeJSON(key string, start, stop int, ascend bool, wit
|
||||
}
|
||||
|
||||
//取有序set指定排名 ascend=true表示按升序遍历 否则按降序遍历
|
||||
func (slf *RedisModule) ZRange(key string, start, stop int, ascend bool, withScores bool) ([]byte, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZRange(key string, start, stop int, ascend bool, withScores bool) ([]byte, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -908,8 +890,8 @@ func (slf *RedisModule) ZRange(key string, start, stop int, ascend bool, withSco
|
||||
}
|
||||
|
||||
//获取有序集合长度
|
||||
func (slf *RedisModule) Zcard(key string) (int, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) Zcard(key string) (int, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -950,14 +932,14 @@ func makeListJson(redisReply []interface{}, withScores bool) []byte {
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func (slf *RedisModule) ZRangeByScoreJSON(key string, start, stop float64, ascend bool, withScores bool, data interface{}) error {
|
||||
func (m *RedisModule) ZRangeByScoreJSON(key string, start, stop float64, ascend bool, withScores bool, data interface{}) error {
|
||||
if withScores {
|
||||
if _, ok := data.(*[]ZSetDataWithScore); !ok {
|
||||
return errors.New("withScores must decode by []ZSetDataWithScore")
|
||||
}
|
||||
}
|
||||
|
||||
b, err := slf.ZRangeByScore(key, start, stop, ascend, withScores)
|
||||
b, err := m.ZRangeByScore(key, start, stop, ascend, withScores)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -969,8 +951,8 @@ func (slf *RedisModule) ZRangeByScoreJSON(key string, start, stop float64, ascen
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RedisModule) ZRangeByScore(key string, start, stop float64, ascend bool, withScores bool) ([]byte, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZRangeByScore(key string, start, stop float64, ascend bool, withScores bool) ([]byte, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -992,8 +974,8 @@ func (slf *RedisModule) ZRangeByScore(key string, start, stop float64, ascend bo
|
||||
}
|
||||
|
||||
//获取指定member的排名
|
||||
func (slf *RedisModule) ZScore(key string, member interface{}) (float64, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZScore(key string, member interface{}) (float64, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
@@ -1008,8 +990,8 @@ func (slf *RedisModule) ZScore(key string, member interface{}) (float64, error)
|
||||
}
|
||||
|
||||
//获取指定member的排名
|
||||
func (slf *RedisModule) ZRank(key string, member interface{}, ascend bool) (int, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZRank(key string, member interface{}, ascend bool) (int, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
@@ -1026,8 +1008,8 @@ func (slf *RedisModule) ZRank(key string, member interface{}, ascend bool) (int,
|
||||
return redis.Int(reply, err)
|
||||
}
|
||||
|
||||
func (slf *RedisModule) ZREMRANGEBYSCORE(key string, start, stop interface{}) error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZREMRANGEBYSCORE(key string, start, stop interface{}) error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1040,8 +1022,8 @@ func (slf *RedisModule) ZREMRANGEBYSCORE(key string, start, stop interface{}) er
|
||||
return err
|
||||
}
|
||||
|
||||
func (slf *RedisModule) ZREM(key string, member interface{}) (int, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZREM(key string, member interface{}) (int, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -1051,8 +1033,8 @@ func (slf *RedisModule) ZREM(key string, member interface{}) (int, error) {
|
||||
return redis.Int(reply, err)
|
||||
}
|
||||
|
||||
func (slf *RedisModule) ZREMMulti(key string, member ...interface{}) (int, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) ZREMMulti(key string, member ...interface{}) (int, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -1064,11 +1046,11 @@ func (slf *RedisModule) ZREMMulti(key string, member ...interface{}) (int, error
|
||||
return redis.Int(reply, err)
|
||||
}
|
||||
|
||||
func (slf *RedisModule) HincrbyHashInt(redisKey, hashKey string, value int) error {
|
||||
func (m *RedisModule) HincrbyHashInt(redisKey, hashKey string, value int) error {
|
||||
if redisKey == "" || hashKey == "" {
|
||||
return errors.New("Key Is Empty")
|
||||
}
|
||||
conn, err := slf.getConn()
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1082,8 +1064,8 @@ func (slf *RedisModule) HincrbyHashInt(redisKey, hashKey string, value int) erro
|
||||
return retErr
|
||||
}
|
||||
|
||||
func (slf *RedisModule) EXPlREInsert(key string, TTl int) error {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) EXPlREInsert(key string, TTl int) error {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1097,8 +1079,8 @@ func (slf *RedisModule) EXPlREInsert(key string, TTl int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *RedisModule) Zremrangebyrank(redisKey string, start, end interface{}) (int, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) Zremrangebyrank(redisKey string, start, end interface{}) (int, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -1108,9 +1090,8 @@ func (slf *RedisModule) Zremrangebyrank(redisKey string, start, end interface{})
|
||||
return redis.Int(reply, err)
|
||||
}
|
||||
|
||||
|
||||
func (slf *RedisModule) Keys(key string) ([]string, error) {
|
||||
conn, err := slf.getConn()
|
||||
func (m *RedisModule) Keys(key string) ([]string, error) {
|
||||
conn, err := m.getConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -17,11 +17,9 @@ import (
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
|
||||
var Default_ReadTimeout time.Duration = time.Second*10
|
||||
var Default_WriteTimeout time.Duration = time.Second*10
|
||||
var Default_ProcessTimeout time.Duration = time.Second*10
|
||||
|
||||
var Default_HttpRouter *HttpRouter= &HttpRouter{}
|
||||
var DefaultReadTimeout time.Duration = time.Second*10
|
||||
var DefaultWriteTimeout time.Duration = time.Second*10
|
||||
var DefaultProcessTimeout time.Duration = time.Second*10
|
||||
|
||||
//http redirect
|
||||
type HttpRedirectData struct {
|
||||
@@ -40,13 +38,11 @@ const (
|
||||
)
|
||||
|
||||
type HttpHandle func(session *HttpSession)
|
||||
|
||||
type routerMatchData struct {
|
||||
matchURL string
|
||||
httpHandle HttpHandle
|
||||
}
|
||||
|
||||
|
||||
type routerServeFileData struct {
|
||||
matchUrl string
|
||||
localPath string
|
||||
@@ -54,7 +50,6 @@ type routerServeFileData struct {
|
||||
}
|
||||
|
||||
type IHttpRouter interface {
|
||||
//RegRouter(method HTTP_METHOD, url string, handle HttpHandle) bool
|
||||
GET(url string, handle HttpHandle) bool
|
||||
POST(url string, handle HttpHandle) bool
|
||||
Router(session *HttpSession)
|
||||
@@ -65,11 +60,9 @@ type IHttpRouter interface {
|
||||
AddHttpFiltrate(FiltrateFun HttpFiltrate) bool
|
||||
}
|
||||
|
||||
|
||||
type HttpRouter struct {
|
||||
pathRouter map[HTTP_METHOD] map[string] routerMatchData //url地址,对应本service地址
|
||||
serveFileData map[string] *routerServeFileData
|
||||
//eventReciver event.IEventHandler
|
||||
httpFiltrateList [] HttpFiltrate
|
||||
|
||||
formFileKey string
|
||||
@@ -104,13 +97,18 @@ type HttpService struct {
|
||||
processTimeout time.Duration
|
||||
}
|
||||
|
||||
func (slf *HttpService) AddFiltrate(FiltrateFun HttpFiltrate) bool {
|
||||
return slf.httpRouter.AddHttpFiltrate(FiltrateFun)
|
||||
type HttpFiltrate func(session *HttpSession) bool //true is pass
|
||||
|
||||
type CORSHeader struct {
|
||||
AllowCORSHeader map[string][]string
|
||||
}
|
||||
|
||||
func (httpService *HttpService) AddFiltrate(FiltrateFun HttpFiltrate) bool {
|
||||
return httpService.httpRouter.AddHttpFiltrate(FiltrateFun)
|
||||
}
|
||||
|
||||
func NewHttpHttpRouter() IHttpRouter {
|
||||
httpRouter := &HttpRouter{}
|
||||
//httpRouter.eventReciver = eventHandler
|
||||
httpRouter.pathRouter =map[HTTP_METHOD] map[string] routerMatchData{}
|
||||
httpRouter.serveFileData = map[string] *routerServeFileData{}
|
||||
httpRouter.formFileKey = "file"
|
||||
@@ -118,14 +116,10 @@ func NewHttpHttpRouter() IHttpRouter {
|
||||
httpRouter.pathRouter[i] = map[string] routerMatchData{}
|
||||
}
|
||||
|
||||
|
||||
return httpRouter
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (slf *HttpSession) Query(key string) (string, bool) {
|
||||
|
||||
if slf.mapParam == nil {
|
||||
slf.mapParam = make(map[string]string)
|
||||
|
||||
@@ -211,8 +205,6 @@ func (slf *HttpSession) getMethod(method string) HTTP_METHOD {
|
||||
return METHOD_INVALID
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (slf *HttpRouter) analysisRouterUrl(url string) (string, error) {
|
||||
|
||||
//替换所有空格
|
||||
@@ -237,7 +229,6 @@ func (slf *HttpRouter) GetFormFileKey()string{
|
||||
return slf.formFileKey
|
||||
}
|
||||
|
||||
|
||||
func (slf *HttpRouter) GET(url string, handle HttpHandle) bool {
|
||||
return slf.regRouter(METHOD_GET, url, handle)
|
||||
}
|
||||
@@ -279,7 +270,6 @@ func (slf *HttpRouter) Router(session *HttpSession){
|
||||
}
|
||||
|
||||
v.httpHandle(session)
|
||||
//session.done()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -296,19 +286,15 @@ func (slf *HttpRouter) Router(session *HttpSession){
|
||||
session.Done()
|
||||
}
|
||||
|
||||
|
||||
func (slf *HttpService) HttpEventHandler(ev *event.Event) {
|
||||
func (httpService *HttpService) HttpEventHandler(ev *event.Event) {
|
||||
ev.Data.(*HttpSession).Handle()
|
||||
}
|
||||
|
||||
func (slf *HttpService) SetHttpRouter(httpRouter IHttpRouter,eventHandler event.IEventHandler) {
|
||||
slf.httpRouter = httpRouter
|
||||
slf.RegEventReciverFunc(event.Sys_Event_Http_Event,eventHandler,slf.HttpEventHandler)
|
||||
func (httpService *HttpService) SetHttpRouter(httpRouter IHttpRouter,eventHandler event.IEventHandler) {
|
||||
httpService.httpRouter = httpRouter
|
||||
httpService.RegEventReceiverFunc(event.Sys_Event_Http_Event,eventHandler, httpService.HttpEventHandler)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
func (slf *HttpRouter) SetServeFile(method HTTP_METHOD, urlpath string, dirname string) error {
|
||||
_, err := os.Stat(dirname)
|
||||
if err != nil {
|
||||
@@ -328,9 +314,6 @@ func (slf *HttpRouter) SetServeFile(method HTTP_METHOD, urlpath string, dirname
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
type HttpFiltrate func(session *HttpSession) bool //true is pass
|
||||
|
||||
func (slf *HttpRouter) AddHttpFiltrate(FiltrateFun HttpFiltrate) bool {
|
||||
slf.httpFiltrateList = append(slf.httpFiltrateList, FiltrateFun)
|
||||
return false
|
||||
@@ -359,20 +342,18 @@ func (slf *HttpSession) redirects() {
|
||||
http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (slf *HttpService) OnInit() error {
|
||||
iConfig := slf.GetServiceCfg()
|
||||
func (httpService *HttpService) OnInit() error {
|
||||
iConfig := httpService.GetServiceCfg()
|
||||
if iConfig == nil {
|
||||
return fmt.Errorf("%s service config is error!",slf.GetName())
|
||||
return fmt.Errorf("%s service config is error!", httpService.GetName())
|
||||
}
|
||||
tcpCfg := iConfig.(map[string]interface{})
|
||||
addr,ok := tcpCfg["ListenAddr"]
|
||||
if ok == false {
|
||||
return fmt.Errorf("%s service config is error!",slf.GetName())
|
||||
return fmt.Errorf("%s service config is error!", httpService.GetName())
|
||||
}
|
||||
var readTimeout time.Duration = Default_ReadTimeout
|
||||
var writeTimeout time.Duration = Default_WriteTimeout
|
||||
var readTimeout time.Duration = DefaultReadTimeout
|
||||
var writeTimeout time.Duration = DefaultWriteTimeout
|
||||
|
||||
if cfgRead,ok := tcpCfg["ReadTimeout"];ok == true {
|
||||
readTimeout = time.Duration(cfgRead.(float64))*time.Millisecond
|
||||
@@ -382,12 +363,12 @@ func (slf *HttpService) OnInit() error {
|
||||
writeTimeout = time.Duration(cfgWrite.(float64))*time.Millisecond
|
||||
}
|
||||
|
||||
slf.processTimeout = Default_ProcessTimeout
|
||||
httpService.processTimeout = DefaultProcessTimeout
|
||||
if cfgProcessTimeout,ok := tcpCfg["ProcessTimeout"];ok == true {
|
||||
slf.processTimeout = time.Duration(cfgProcessTimeout.(float64))*time.Millisecond
|
||||
httpService.processTimeout = time.Duration(cfgProcessTimeout.(float64))*time.Millisecond
|
||||
}
|
||||
|
||||
slf.httpServer.Init(addr.(string), slf, readTimeout, writeTimeout)
|
||||
httpService.httpServer.Init(addr.(string), httpService, readTimeout, writeTimeout)
|
||||
//Set CAFile
|
||||
caFileList,ok := tcpCfg["CAFile"]
|
||||
if ok == false {
|
||||
@@ -408,24 +389,24 @@ func (slf *HttpService) OnInit() error {
|
||||
|
||||
if c.(string)!="" && k.(string)!="" {
|
||||
caFile = append(caFile,network.CAFile{
|
||||
Certfile: c.(string),
|
||||
CertFile: c.(string),
|
||||
Keyfile: k.(string),
|
||||
})
|
||||
}
|
||||
}
|
||||
slf.httpServer.SetCAFile(caFile)
|
||||
slf.httpServer.Start()
|
||||
httpService.httpServer.SetCAFile(caFile)
|
||||
httpService.httpServer.Start()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *HttpService) SetAllowCORS(corsHeader *CORSHeader) {
|
||||
slf.corsHeader = corsHeader
|
||||
func (httpService *HttpService) SetAllowCORS(corsHeader *CORSHeader) {
|
||||
httpService.corsHeader = corsHeader
|
||||
}
|
||||
|
||||
func (slf *HttpService) ProcessFile(session *HttpSession){
|
||||
upath := session.r.URL.Path
|
||||
idx := strings.Index(upath, session.fileData.matchUrl)
|
||||
subPath := strings.Trim(upath[idx+len(session.fileData.matchUrl):], "/")
|
||||
func (httpService *HttpService) ProcessFile(session *HttpSession){
|
||||
uPath := session.r.URL.Path
|
||||
idx := strings.Index(uPath, session.fileData.matchUrl)
|
||||
subPath := strings.Trim(uPath[idx+len(session.fileData.matchUrl):], "/")
|
||||
|
||||
destLocalPath := session.fileData.localPath + "/"+subPath
|
||||
|
||||
@@ -461,26 +442,21 @@ func (slf *HttpService) ProcessFile(session *HttpSession){
|
||||
filePrefixName := uuid.Rand().HexEx()
|
||||
fileName := filePrefixName + "." + imgFormat[len(imgFormat)-1]
|
||||
//创建文件
|
||||
localpath := fmt.Sprintf("%s%s", destLocalPath, fileName)
|
||||
localfd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE, 0666)
|
||||
localPath := fmt.Sprintf("%s%s", destLocalPath, fileName)
|
||||
localFd, err := os.OpenFile(localPath, os.O_WRONLY|os.O_CREATE, 0666)
|
||||
if err != nil {
|
||||
session.WriteStatusCode(http.StatusNotFound)
|
||||
session.flush()
|
||||
return
|
||||
}
|
||||
defer localfd.Close()
|
||||
io.Copy(localfd, resourceFile)
|
||||
defer localFd.Close()
|
||||
io.Copy(localFd, resourceFile)
|
||||
session.WriteStatusCode(http.StatusOK)
|
||||
session.Write([]byte(upath+"/"+fileName))
|
||||
session.Write([]byte(uPath+"/"+fileName))
|
||||
session.flush()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
type CORSHeader struct {
|
||||
AllowCORSHeader map[string][]string
|
||||
}
|
||||
|
||||
func NewAllowCORSHeader() *CORSHeader{
|
||||
header := &CORSHeader{}
|
||||
header.AllowCORSHeader = map[string][]string{}
|
||||
@@ -503,17 +479,17 @@ func (slf *CORSHeader) copyTo(header http.Header){
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if slf.corsHeader != nil {
|
||||
func (httpService *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if httpService.corsHeader != nil {
|
||||
if origin := r.Header.Get("Origin"); origin != "" {
|
||||
slf.corsHeader.copyTo(w.Header())
|
||||
httpService.corsHeader.copyTo(w.Header())
|
||||
}
|
||||
}
|
||||
if r.Method == "OPTIONS" {
|
||||
return
|
||||
}
|
||||
|
||||
session := &HttpSession{sessionDone:make(chan *HttpSession,1),httpRouter:slf.httpRouter,statusCode:http.StatusOK}
|
||||
session := &HttpSession{sessionDone:make(chan *HttpSession,1),httpRouter:httpService.httpRouter,statusCode:http.StatusOK}
|
||||
session.r = r
|
||||
session.w = w
|
||||
|
||||
@@ -526,8 +502,8 @@ func (slf *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
session.body = body
|
||||
|
||||
slf.GetEventHandler().NotifyEvent(&event.Event{Type:event.Sys_Event_Http_Event,Data:session})
|
||||
ticker := time.NewTicker(slf.processTimeout)
|
||||
httpService.GetEventHandler().NotifyEvent(&event.Event{Type:event.Sys_Event_Http_Event,Data:session})
|
||||
ticker := time.NewTicker(httpService.processTimeout)
|
||||
select {
|
||||
case <-ticker.C:
|
||||
session.WriteStatusCode(http.StatusGatewayTimeout)
|
||||
@@ -535,7 +511,7 @@ func (slf *HttpService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
break
|
||||
case <- session.sessionDone:
|
||||
if session.fileData!=nil {
|
||||
slf.ProcessFile(session)
|
||||
httpService.ProcessFile(session)
|
||||
}else if session.redirectData!=nil {
|
||||
session.redirects()
|
||||
}else{
|
||||
|
||||
@@ -16,7 +16,7 @@ func NewGateProxyModule() *GateProxyModule{
|
||||
return &GateProxyModule{defaultGateRpc:"TcpGateService.RPC_Dispatch"}
|
||||
}
|
||||
|
||||
func (slf *GateProxyModule) Send(clientId interface{},msgType uint16,msg proto.Message) error {
|
||||
func (gate *GateProxyModule) Send(clientId interface{},msgType uint16,msg proto.Message) error {
|
||||
//对agentId进行分组
|
||||
mapNodeClientId := map[int][]uint64{}
|
||||
switch clientId.(type) {
|
||||
@@ -41,7 +41,6 @@ func (slf *GateProxyModule) Send(clientId interface{},msgType uint16,msg proto.M
|
||||
replyMsg.MsgType = proto.Uint32(uint32(msgType))
|
||||
replyMsg.Msg = bData
|
||||
|
||||
|
||||
for nodeId,clientIdList := range mapNodeClientId {
|
||||
if nodeId <0 || nodeId>tcpservice.MaxNodeId {
|
||||
fmt.Errorf("nodeid is error %d",nodeId)
|
||||
@@ -49,20 +48,17 @@ func (slf *GateProxyModule) Send(clientId interface{},msgType uint16,msg proto.M
|
||||
}
|
||||
|
||||
replyMsg.ClientList = clientIdList
|
||||
slf.GetService().GetRpcHandler().GoNode(nodeId,slf.defaultGateRpc,&replyMsg)
|
||||
gate.GetService().GetRpcHandler().GoNode(nodeId,gate.defaultGateRpc,&replyMsg)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (slf *GateProxyModule) SetDefaultGateRpcMethodName(rpcMethodName string){
|
||||
slf.defaultGateRpc = rpcMethodName
|
||||
func (gate *GateProxyModule) SetDefaultGateRpcMethodName(rpcMethodName string){
|
||||
gate.defaultGateRpc = rpcMethodName
|
||||
}
|
||||
|
||||
|
||||
func (slf *GateProxyModule) send(clientId uint64,msgType uint16,msg []byte) error {
|
||||
func (gate *GateProxyModule) send(clientId uint64,msgType uint16,msg []byte) error {
|
||||
nodeId := tcpservice.GetNodeId(clientId)
|
||||
if nodeId <0 || nodeId>tcpservice.MaxNodeId {
|
||||
return fmt.Errorf("nodeid is error %d",nodeId)
|
||||
@@ -73,5 +69,5 @@ func (slf *GateProxyModule) send(clientId uint64,msgType uint16,msg []byte) erro
|
||||
replyMsg.Msg = msg
|
||||
replyMsg.ClientList = append(replyMsg.ClientList ,clientId)
|
||||
|
||||
return slf.GetService().GetRpcHandler().GoNode(nodeId,slf.defaultGateRpc,&replyMsg)
|
||||
return gate.GetService().GetRpcHandler().GoNode(nodeId, gate.defaultGateRpc,&replyMsg)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,6 @@ package tcpgateway
|
||||
type LoadBalance struct {
|
||||
}
|
||||
|
||||
func (slf *LoadBalance) SelectNode(serviceName string) int {
|
||||
func (balance *LoadBalance) SelectNode(serviceName string) int {
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -46,9 +46,9 @@ func NewRouter(loadBalance ILoadBalance,rpcHandler rpc.IRpcHandler,cfg interface
|
||||
return router
|
||||
}
|
||||
|
||||
func (slf *Router) loadCfg(cfg interface{}){
|
||||
slf.mapMsgRouterInfo = map[uint16]*MsgRouterInfo{}
|
||||
slf.mapEventRouterInfo = map[string]*EventRouterInfo{}
|
||||
func (r *Router) loadCfg(cfg interface{}){
|
||||
r.mapMsgRouterInfo = map[uint16]*MsgRouterInfo{}
|
||||
r.mapEventRouterInfo = map[string]*EventRouterInfo{}
|
||||
|
||||
mapRouter,ok := cfg.(map[string]interface{})
|
||||
if ok == false{
|
||||
@@ -100,7 +100,7 @@ func (slf *Router) loadCfg(cfg interface{}){
|
||||
continue
|
||||
}
|
||||
|
||||
slf.mapMsgRouterInfo[uint16(msgId)] = &MsgRouterInfo{ServiceName:strService[0],Rpc: iRpc.(string),LoadBalanceType: iLoadBalanceType.(string)}
|
||||
r.mapMsgRouterInfo[uint16(msgId)] = &MsgRouterInfo{ServiceName: strService[0],Rpc: iRpc.(string),LoadBalanceType: iLoadBalanceType.(string)}
|
||||
}
|
||||
|
||||
//parse EventRouter
|
||||
@@ -147,12 +147,12 @@ func (slf *Router) loadCfg(cfg interface{}){
|
||||
continue
|
||||
}
|
||||
|
||||
slf.mapEventRouterInfo[strEventType] = &EventRouterInfo{ServiceName:strService[0],Rpc: iRpc.(string),LoadBalanceType: iLoadBalanceType.(string)}
|
||||
r.mapEventRouterInfo[strEventType] = &EventRouterInfo{ServiceName: strService[0],Rpc: iRpc.(string),LoadBalanceType: iLoadBalanceType.(string)}
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Router) GetMsgRouterService(msgType uint16) *MsgRouterInfo{
|
||||
info,ok := slf.mapMsgRouterInfo[msgType]
|
||||
func (r *Router) GetMsgRouterService(msgType uint16) *MsgRouterInfo{
|
||||
info,ok := r.mapMsgRouterInfo[msgType]
|
||||
if ok == false {
|
||||
return nil
|
||||
}
|
||||
@@ -160,8 +160,8 @@ func (slf *Router) GetMsgRouterService(msgType uint16) *MsgRouterInfo{
|
||||
return info
|
||||
}
|
||||
|
||||
func (slf *Router) GetEventRouterService(eventType string) *EventRouterInfo{
|
||||
info,ok := slf.mapEventRouterInfo[eventType]
|
||||
func (r *Router) GetEventRouterService(eventType string) *EventRouterInfo{
|
||||
info,ok := r.mapEventRouterInfo[eventType]
|
||||
if ok == false {
|
||||
return nil
|
||||
}
|
||||
@@ -169,8 +169,8 @@ func (slf *Router) GetEventRouterService(eventType string) *EventRouterInfo{
|
||||
return info
|
||||
}
|
||||
|
||||
func (slf *Router) GetRouterId(clientId uint64,serviceName *string) int {
|
||||
mapServiceRouter,ok := slf.mapClientRouterCache[clientId]
|
||||
func (r *Router) GetRouterId(clientId uint64,serviceName *string) int {
|
||||
mapServiceRouter,ok := r.mapClientRouterCache[clientId]
|
||||
if ok == false{
|
||||
return 0
|
||||
}
|
||||
@@ -183,46 +183,46 @@ func (slf *Router) GetRouterId(clientId uint64,serviceName *string) int {
|
||||
return routerId
|
||||
}
|
||||
|
||||
func (slf *Router) SetRouterId(clientId uint64,serviceName *string,routerId int){
|
||||
slf.mapClientRouterCache[clientId][*serviceName] = routerId
|
||||
func (r *Router) SetRouterId(clientId uint64,serviceName *string,routerId int){
|
||||
r.mapClientRouterCache[clientId][*serviceName] = routerId
|
||||
}
|
||||
|
||||
func (slf *Router) RouterMessage(clientId uint64,msgType uint16,msg []byte) {
|
||||
routerInfo:= slf.GetMsgRouterService(msgType)
|
||||
func (r *Router) RouterMessage(clientId uint64,msgType uint16,msg []byte) {
|
||||
routerInfo:= r.GetMsgRouterService(msgType)
|
||||
if routerInfo==nil {
|
||||
log.Error("The message type is %d with no configured route!",msgType)
|
||||
return
|
||||
}
|
||||
|
||||
routerId := slf.GetRouterId(clientId,&routerInfo.ServiceName)
|
||||
routerId := r.GetRouterId(clientId,&routerInfo.ServiceName)
|
||||
if routerId ==0 {
|
||||
routerId = slf.loadBalance.SelectNode(routerInfo.ServiceName)
|
||||
slf.SetRouterId(clientId,&routerInfo.ServiceName,routerId)
|
||||
routerId = r.loadBalance.SelectNode(routerInfo.ServiceName)
|
||||
r.SetRouterId(clientId,&routerInfo.ServiceName,routerId)
|
||||
}
|
||||
|
||||
if routerId>0 {
|
||||
slf.rpcHandler.RawGoNode(rpc.RPC_PROCESSOR_PB,routerId,routerInfo.Rpc,msg,proto.Uint64(clientId))
|
||||
r.rpcHandler.RawGoNode(rpc.RpcProcessorPb,routerId,routerInfo.Rpc,msg,proto.Uint64(clientId))
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *Router) Load(){
|
||||
func (r *Router) Load(){
|
||||
}
|
||||
|
||||
func (slf *Router) RouterEvent(clientId uint64,eventType string) bool{
|
||||
routerInfo:= slf.GetEventRouterService(eventType)
|
||||
func (r *Router) RouterEvent(clientId uint64,eventType string) bool{
|
||||
routerInfo:= r.GetEventRouterService(eventType)
|
||||
if routerInfo==nil {
|
||||
log.Error("The event type is %s with no register!",eventType)
|
||||
return false
|
||||
}
|
||||
|
||||
routerId := slf.GetRouterId(clientId,&routerInfo.ServiceName)
|
||||
routerId := r.GetRouterId(clientId,&routerInfo.ServiceName)
|
||||
if routerId ==0 {
|
||||
routerId = slf.loadBalance.SelectNode(routerInfo.ServiceName)
|
||||
slf.SetRouterId(clientId,&routerInfo.ServiceName,routerId)
|
||||
routerId = r.loadBalance.SelectNode(routerInfo.ServiceName)
|
||||
r.SetRouterId(clientId,&routerInfo.ServiceName,routerId)
|
||||
}
|
||||
|
||||
if routerId>0 {
|
||||
slf.rpcHandler.RawGoNode(rpc.RPC_PROCESSOR_PB,routerId,routerInfo.Rpc,[]byte{},proto.Uint64(clientId))
|
||||
r.rpcHandler.RawGoNode(rpc.RpcProcessorPb,routerId,routerInfo.Rpc,[]byte{},proto.Uint64(clientId))
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -230,13 +230,13 @@ func (slf *Router) RouterEvent(clientId uint64,eventType string) bool{
|
||||
}
|
||||
|
||||
|
||||
func (slf *Router) OnDisconnected(clientId uint64){
|
||||
delete(slf.mapClientRouterCache,clientId)
|
||||
func (r *Router) OnDisconnected(clientId uint64){
|
||||
delete(r.mapClientRouterCache,clientId)
|
||||
//通知事件
|
||||
slf.RouterEvent(clientId,"DisConnect")
|
||||
r.RouterEvent(clientId,"DisConnect")
|
||||
}
|
||||
|
||||
func (slf *Router) OnConnected(clientId uint64){
|
||||
slf.mapClientRouterCache[clientId] = map[string]int{}
|
||||
slf.RouterEvent(clientId,"Connect")
|
||||
func (r *Router) OnConnected(clientId uint64){
|
||||
r.mapClientRouterCache[clientId] = map[string]int{}
|
||||
r.RouterEvent(clientId,"Connect")
|
||||
}
|
||||
|
||||
@@ -23,76 +23,75 @@ type TcpGateService struct {
|
||||
|
||||
processor processor.IRawProcessor
|
||||
tcpService *tcpservice.TcpService
|
||||
|
||||
loadBalance ILoadBalance
|
||||
router IRouter
|
||||
}
|
||||
|
||||
|
||||
func (slf *TcpGateService) OnInit() error {
|
||||
slf.OnLoad()
|
||||
func (gateService *TcpGateService) OnInit() error {
|
||||
gateService.OnLoad()
|
||||
|
||||
//注册监听客户连接断开事件
|
||||
slf.processor.SetDisConnectedHandler(slf.router.OnDisconnected)
|
||||
gateService.processor.SetDisConnectedHandler(gateService.router.OnDisconnected)
|
||||
//注册监听客户连接事件
|
||||
slf.processor.SetConnectedHandler(slf.router.OnConnected)
|
||||
gateService.processor.SetConnectedHandler(gateService.router.OnConnected)
|
||||
|
||||
//注册监听消息类型MsgType_MsgReq,并注册回调
|
||||
slf.processor.SetRawMsgHandler(slf.router.RouterMessage)
|
||||
gateService.processor.SetRawMsgHandler(gateService.router.RouterMessage)
|
||||
//将protobuf消息处理器设置到TcpService服务中
|
||||
slf.tcpService.SetProcessor(slf.processor,slf.GetEventHandler())
|
||||
gateService.tcpService.SetProcessor(gateService.processor, gateService.GetEventHandler())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *TcpGateService) OnLoad() {
|
||||
func (gateService *TcpGateService) OnLoad() {
|
||||
//设置默认LoadBalance
|
||||
if slf.loadBalance == nil {
|
||||
slf.loadBalance = &LoadBalance{}
|
||||
if gateService.loadBalance == nil {
|
||||
gateService.loadBalance = &LoadBalance{}
|
||||
}
|
||||
|
||||
//设置默认Router
|
||||
if slf.router == nil {
|
||||
slf.router = NewRouter(slf.loadBalance,slf,slf.GetServiceCfg())
|
||||
if gateService.router == nil {
|
||||
gateService.router = NewRouter(gateService.loadBalance, gateService, gateService.GetServiceCfg())
|
||||
}
|
||||
|
||||
//新建内置的protobuf处理器,您也可以自定义路由器,比如json
|
||||
if slf.processor == nil {
|
||||
slf.processor = processor.NewPBRawProcessor()
|
||||
if gateService.processor == nil {
|
||||
gateService.processor = processor.NewPBRawProcessor()
|
||||
}
|
||||
|
||||
//加载路由
|
||||
slf.router.Load()
|
||||
gateService.router.Load()
|
||||
|
||||
//设置默认的TcpService服务
|
||||
if slf.tcpService == nil {
|
||||
slf.tcpService = node.GetService("TcpService").(*tcpservice.TcpService)
|
||||
if gateService.tcpService == nil {
|
||||
gateService.tcpService = node.GetService("TcpService").(*tcpservice.TcpService)
|
||||
}
|
||||
|
||||
if slf.tcpService == nil {
|
||||
if gateService.tcpService == nil {
|
||||
panic("TcpService is not installed!")
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *TcpGateService) SetLoadBalance(loadBalance ILoadBalance){
|
||||
slf.loadBalance = loadBalance
|
||||
func (gateService *TcpGateService) SetLoadBalance(loadBalance ILoadBalance){
|
||||
gateService.loadBalance = loadBalance
|
||||
}
|
||||
|
||||
func (slf *TcpGateService) SetRouter(router IRouter){
|
||||
slf.router = router
|
||||
func (gateService *TcpGateService) SetRouter(router IRouter){
|
||||
gateService.router = router
|
||||
}
|
||||
|
||||
func (slf *TcpGateService) SetRawProcessor(processor processor.IRawProcessor){
|
||||
slf.processor = processor
|
||||
func (gateService *TcpGateService) SetRawProcessor(processor processor.IRawProcessor){
|
||||
gateService.processor = processor
|
||||
}
|
||||
|
||||
func (slf *TcpGateService) SetTcpGateService(tcpService *tcpservice.TcpService){
|
||||
slf.tcpService = tcpService
|
||||
func (gateService *TcpGateService) SetTcpGateService(tcpService *tcpservice.TcpService){
|
||||
gateService.tcpService = tcpService
|
||||
}
|
||||
|
||||
func (slf *TcpGateService) RPC_Dispatch(replyMsg *ReplyMessage) error {
|
||||
func (gateService *TcpGateService) RPC_Dispatch(replyMsg *ReplyMessage) error {
|
||||
for _,id := range replyMsg.ClientList {
|
||||
err := slf.tcpService.SendRawMsg(id,replyMsg.Msg)
|
||||
err := gateService.tcpService.SendRawMsg(id,replyMsg.Msg)
|
||||
if err != nil {
|
||||
log.Debug("SendRawMsg fail:%+v!",err)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ type TcpService struct {
|
||||
|
||||
mapClientLocker sync.RWMutex
|
||||
mapClient map[uint64] *Client
|
||||
//initClientId uint64
|
||||
process processor.IProcessor
|
||||
}
|
||||
|
||||
@@ -30,13 +29,6 @@ const(
|
||||
TPT_UnknownPack TcpPackType = 3
|
||||
)
|
||||
|
||||
type TcpPack struct {
|
||||
Type TcpPackType //0表示连接 1表示断开 2表示数据
|
||||
MsgProcessor processor.IProcessor
|
||||
ClientId uint64
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
const Default_MaxConnNum = 3000
|
||||
const Default_PendingWriteNum = 10000
|
||||
const Default_LittleEndian = false
|
||||
@@ -47,10 +39,24 @@ const (
|
||||
MaxNodeId = 1<<10 - 1 //Uint10
|
||||
MaxSeed = 1<<22 - 1 //MaxUint24
|
||||
)
|
||||
|
||||
var seed uint32
|
||||
var seedLocker sync.Mutex
|
||||
|
||||
func (slf *TcpService) genId() uint64 {
|
||||
type TcpPack struct {
|
||||
Type TcpPackType //0表示连接 1表示断开 2表示数据
|
||||
MsgProcessor processor.IProcessor
|
||||
ClientId uint64
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
id uint64
|
||||
tcpConn *network.TCPConn
|
||||
tcpService *TcpService
|
||||
}
|
||||
|
||||
func (tcpService *TcpService) genId() uint64 {
|
||||
if node.GetNodeId()>MaxNodeId{
|
||||
panic("nodeId exceeds the maximum!")
|
||||
}
|
||||
@@ -60,7 +66,6 @@ func (slf *TcpService) genId() uint64 {
|
||||
seedLocker.Unlock()
|
||||
|
||||
nowTime := uint64(time.Now().Second())
|
||||
|
||||
return (uint64(node.GetNodeId())<<54)|(nowTime<<22)|uint64(seed)
|
||||
}
|
||||
|
||||
@@ -68,49 +73,51 @@ func GetNodeId(agentId uint64) int {
|
||||
return int(agentId>>54)
|
||||
}
|
||||
|
||||
func (slf *TcpService) OnInit() error{
|
||||
iConfig := slf.GetServiceCfg()
|
||||
func (tcpService *TcpService) OnInit() error{
|
||||
iConfig := tcpService.GetServiceCfg()
|
||||
if iConfig == nil {
|
||||
return fmt.Errorf("%s service config is error!",slf.GetName())
|
||||
return fmt.Errorf("%s service config is error!", tcpService.GetName())
|
||||
}
|
||||
tcpCfg := iConfig.(map[string]interface{})
|
||||
addr,ok := tcpCfg["ListenAddr"]
|
||||
if ok == false {
|
||||
return fmt.Errorf("%s service config is error!",slf.GetName())
|
||||
return fmt.Errorf("%s service config is error!", tcpService.GetName())
|
||||
}
|
||||
slf.tcpServer.Addr = addr.(string)
|
||||
slf.tcpServer.MaxConnNum = Default_MaxConnNum
|
||||
slf.tcpServer.PendingWriteNum = Default_PendingWriteNum
|
||||
slf.tcpServer.LittleEndian = Default_LittleEndian
|
||||
slf.tcpServer.MinMsgLen = Default_MinMsgLen
|
||||
slf.tcpServer.MaxMsgLen = Default_MaxMsgLen
|
||||
|
||||
tcpService.tcpServer.Addr = addr.(string)
|
||||
tcpService.tcpServer.MaxConnNum = Default_MaxConnNum
|
||||
tcpService.tcpServer.PendingWriteNum = Default_PendingWriteNum
|
||||
tcpService.tcpServer.LittleEndian = Default_LittleEndian
|
||||
tcpService.tcpServer.MinMsgLen = Default_MinMsgLen
|
||||
tcpService.tcpServer.MaxMsgLen = Default_MaxMsgLen
|
||||
MaxConnNum,ok := tcpCfg["MaxConnNum"]
|
||||
if ok == true {
|
||||
slf.tcpServer.MaxConnNum = int(MaxConnNum.(float64))
|
||||
tcpService.tcpServer.MaxConnNum = int(MaxConnNum.(float64))
|
||||
}
|
||||
PendingWriteNum,ok := tcpCfg["PendingWriteNum"]
|
||||
if ok == true {
|
||||
slf.tcpServer.PendingWriteNum = int(PendingWriteNum.(float64))
|
||||
tcpService.tcpServer.PendingWriteNum = int(PendingWriteNum.(float64))
|
||||
}
|
||||
LittleEndian,ok := tcpCfg["LittleEndian"]
|
||||
if ok == true {
|
||||
slf.tcpServer.LittleEndian = LittleEndian.(bool)
|
||||
tcpService.tcpServer.LittleEndian = LittleEndian.(bool)
|
||||
}
|
||||
MinMsgLen,ok := tcpCfg["MinMsgLen"]
|
||||
if ok == true {
|
||||
slf.tcpServer.MinMsgLen = uint32(MinMsgLen.(float64))
|
||||
tcpService.tcpServer.MinMsgLen = uint32(MinMsgLen.(float64))
|
||||
}
|
||||
MaxMsgLen,ok := tcpCfg["MaxMsgLen"]
|
||||
if ok == true {
|
||||
slf.tcpServer.MaxMsgLen = uint32(MaxMsgLen.(float64))
|
||||
tcpService.tcpServer.MaxMsgLen = uint32(MaxMsgLen.(float64))
|
||||
}
|
||||
slf.mapClient = make( map[uint64] *Client,slf.tcpServer.MaxConnNum)
|
||||
slf.tcpServer.NewAgent =slf.NewClient
|
||||
slf.tcpServer.Start()
|
||||
tcpService.mapClient = make( map[uint64] *Client, tcpService.tcpServer.MaxConnNum)
|
||||
tcpService.tcpServer.NewAgent = tcpService.NewClient
|
||||
tcpService.tcpServer.Start()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *TcpService) TcpEventHandler(ev *event.Event) {
|
||||
func (tcpService *TcpService) TcpEventHandler(ev *event.Event) {
|
||||
pack := ev.Data.(*TcpPack)
|
||||
switch pack.Type {
|
||||
case TPT_Connected:
|
||||
@@ -124,25 +131,25 @@ func (slf *TcpService) TcpEventHandler(ev *event.Event) {
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *TcpService) SetProcessor(process processor.IProcessor,handler event.IEventHandler){
|
||||
slf.process = process
|
||||
slf.RegEventReciverFunc(event.Sys_Event_Tcp,handler,slf.TcpEventHandler)
|
||||
func (tcpService *TcpService) SetProcessor(process processor.IProcessor,handler event.IEventHandler){
|
||||
tcpService.process = process
|
||||
tcpService.RegEventReceiverFunc(event.Sys_Event_Tcp,handler, tcpService.TcpEventHandler)
|
||||
}
|
||||
|
||||
func (slf *TcpService) NewClient(conn *network.TCPConn) network.Agent {
|
||||
slf.mapClientLocker.Lock()
|
||||
defer slf.mapClientLocker.Unlock()
|
||||
func (tcpService *TcpService) NewClient(conn *network.TCPConn) network.Agent {
|
||||
tcpService.mapClientLocker.Lock()
|
||||
defer tcpService.mapClientLocker.Unlock()
|
||||
|
||||
for {
|
||||
clientId := slf.genId()
|
||||
_,ok := slf.mapClient[clientId]
|
||||
clientId := tcpService.genId()
|
||||
_,ok := tcpService.mapClient[clientId]
|
||||
if ok == true {
|
||||
continue
|
||||
}
|
||||
|
||||
pClient := &Client{tcpConn:conn, id:clientId}
|
||||
pClient.tcpService = slf
|
||||
slf.mapClient[clientId] = pClient
|
||||
pClient.tcpService = tcpService
|
||||
tcpService.mapClient[clientId] = pClient
|
||||
|
||||
return pClient
|
||||
}
|
||||
@@ -150,12 +157,6 @@ func (slf *TcpService) NewClient(conn *network.TCPConn) network.Agent {
|
||||
return nil
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
id uint64
|
||||
tcpConn *network.TCPConn
|
||||
tcpService *TcpService
|
||||
}
|
||||
|
||||
func (slf *Client) GetId() uint64 {
|
||||
return slf.id
|
||||
}
|
||||
@@ -188,27 +189,27 @@ func (slf *Client) OnClose(){
|
||||
delete (slf.tcpService.mapClient,slf.GetId())
|
||||
}
|
||||
|
||||
func (slf *TcpService) SendMsg(clientId uint64,msg interface{}) error{
|
||||
slf.mapClientLocker.Lock()
|
||||
client,ok := slf.mapClient[clientId]
|
||||
func (tcpService *TcpService) SendMsg(clientId uint64,msg interface{}) error{
|
||||
tcpService.mapClientLocker.Lock()
|
||||
client,ok := tcpService.mapClient[clientId]
|
||||
if ok == false{
|
||||
slf.mapClientLocker.Unlock()
|
||||
tcpService.mapClientLocker.Unlock()
|
||||
return fmt.Errorf("client %d is disconnect!",clientId)
|
||||
}
|
||||
|
||||
slf.mapClientLocker.Unlock()
|
||||
bytes,err := slf.process.Marshal(msg)
|
||||
tcpService.mapClientLocker.Unlock()
|
||||
bytes,err := tcpService.process.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.tcpConn.WriteMsg(bytes)
|
||||
}
|
||||
|
||||
func (slf *TcpService) Close(clientId uint64) {
|
||||
slf.mapClientLocker.Lock()
|
||||
defer slf.mapClientLocker.Unlock()
|
||||
func (tcpService *TcpService) Close(clientId uint64) {
|
||||
tcpService.mapClientLocker.Lock()
|
||||
defer tcpService.mapClientLocker.Unlock()
|
||||
|
||||
client,ok := slf.mapClient[clientId]
|
||||
client,ok := tcpService.mapClient[clientId]
|
||||
if ok == false{
|
||||
return
|
||||
}
|
||||
@@ -220,10 +221,10 @@ func (slf *TcpService) Close(clientId uint64) {
|
||||
return
|
||||
}
|
||||
|
||||
func (slf *TcpService) GetClientIp(clientid uint64) string{
|
||||
slf.mapClientLocker.Lock()
|
||||
defer slf.mapClientLocker.Unlock()
|
||||
pClient,ok := slf.mapClient[clientid]
|
||||
func (tcpService *TcpService) GetClientIp(clientid uint64) string{
|
||||
tcpService.mapClientLocker.Lock()
|
||||
defer tcpService.mapClientLocker.Unlock()
|
||||
pClient,ok := tcpService.mapClient[clientid]
|
||||
if ok == false{
|
||||
return ""
|
||||
}
|
||||
@@ -231,14 +232,13 @@ func (slf *TcpService) GetClientIp(clientid uint64) string{
|
||||
return pClient.tcpConn.GetRemoteIp()
|
||||
}
|
||||
|
||||
|
||||
func (slf *TcpService) SendRawMsg(clientId uint64,msg []byte) error{
|
||||
slf.mapClientLocker.Lock()
|
||||
client,ok := slf.mapClient[clientId]
|
||||
func (tcpService *TcpService) SendRawMsg(clientId uint64,msg []byte) error{
|
||||
tcpService.mapClientLocker.Lock()
|
||||
client,ok := tcpService.mapClient[clientId]
|
||||
if ok == false{
|
||||
slf.mapClientLocker.Unlock()
|
||||
tcpService.mapClientLocker.Unlock()
|
||||
return fmt.Errorf("client %d is disconnect!",clientId)
|
||||
}
|
||||
slf.mapClientLocker.Unlock()
|
||||
tcpService.mapClientLocker.Unlock()
|
||||
return client.tcpConn.WriteMsg(msg)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ type WSService struct {
|
||||
mapClientLocker sync.RWMutex
|
||||
mapClient map[uint64] *WSClient
|
||||
initClientId uint64
|
||||
process processor.Processor
|
||||
process processor.IProcessor
|
||||
}
|
||||
|
||||
type WSPackType int8
|
||||
@@ -28,55 +28,59 @@ const(
|
||||
WPT_UnknownPack WSPackType = 3
|
||||
)
|
||||
|
||||
type WSPack struct {
|
||||
Type WSPackType //0表示连接 1表示断开 2表示数据
|
||||
MsgProcessor processor.Processor
|
||||
ClientId uint64
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
|
||||
const Default_WS_MaxConnNum = 3000
|
||||
const Default_WS_PendingWriteNum = 10000
|
||||
const Default_WS_MaxMsgLen = 65535
|
||||
|
||||
type WSClient struct {
|
||||
id uint64
|
||||
wsConn *network.WSConn
|
||||
wsService *WSService
|
||||
}
|
||||
|
||||
func (slf *WSService) OnInit() error{
|
||||
iConfig := slf.GetServiceCfg()
|
||||
type WSPack struct {
|
||||
Type WSPackType //0表示连接 1表示断开 2表示数据
|
||||
MsgProcessor processor.IProcessor
|
||||
ClientId uint64
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
func (ws *WSService) OnInit() error{
|
||||
iConfig := ws.GetServiceCfg()
|
||||
if iConfig == nil {
|
||||
return fmt.Errorf("%s service config is error!",slf.GetName())
|
||||
return fmt.Errorf("%s service config is error!", ws.GetName())
|
||||
}
|
||||
wsCfg := iConfig.(map[string]interface{})
|
||||
addr,ok := wsCfg["ListenAddr"]
|
||||
if ok == false {
|
||||
return fmt.Errorf("%s service config is error!",slf.GetName())
|
||||
return fmt.Errorf("%s service config is error!", ws.GetName())
|
||||
}
|
||||
|
||||
slf.wsServer.Addr = addr.(string)
|
||||
slf.wsServer.MaxConnNum = Default_WS_MaxConnNum
|
||||
slf.wsServer.PendingWriteNum = Default_WS_PendingWriteNum
|
||||
slf.wsServer.MaxMsgLen = Default_WS_MaxMsgLen
|
||||
ws.wsServer.Addr = addr.(string)
|
||||
ws.wsServer.MaxConnNum = Default_WS_MaxConnNum
|
||||
ws.wsServer.PendingWriteNum = Default_WS_PendingWriteNum
|
||||
ws.wsServer.MaxMsgLen = Default_WS_MaxMsgLen
|
||||
MaxConnNum,ok := wsCfg["MaxConnNum"]
|
||||
if ok == true {
|
||||
slf.wsServer.MaxConnNum = int(MaxConnNum.(float64))
|
||||
ws.wsServer.MaxConnNum = int(MaxConnNum.(float64))
|
||||
}
|
||||
PendingWriteNum,ok := wsCfg["PendingWriteNum"]
|
||||
if ok == true {
|
||||
slf.wsServer.PendingWriteNum = int(PendingWriteNum.(float64))
|
||||
ws.wsServer.PendingWriteNum = int(PendingWriteNum.(float64))
|
||||
}
|
||||
|
||||
MaxMsgLen,ok := wsCfg["MaxMsgLen"]
|
||||
if ok == true {
|
||||
slf.wsServer.MaxMsgLen = uint32(MaxMsgLen.(float64))
|
||||
ws.wsServer.MaxMsgLen = uint32(MaxMsgLen.(float64))
|
||||
}
|
||||
|
||||
slf.mapClient = make( map[uint64] *WSClient,slf.wsServer.MaxConnNum)
|
||||
slf.wsServer.NewAgent =slf.NewWSClient
|
||||
slf.wsServer.Start()
|
||||
ws.mapClient = make( map[uint64] *WSClient, ws.wsServer.MaxConnNum)
|
||||
ws.wsServer.NewAgent = ws.NewWSClient
|
||||
ws.wsServer.Start()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (slf *WSService) WSEventHandler(ev *event.Event) {
|
||||
func (ws *WSService) WSEventHandler(ev *event.Event) {
|
||||
pack := ev.Data.(*WSPack)
|
||||
switch pack.Type {
|
||||
case WPT_Connected:
|
||||
@@ -90,37 +94,31 @@ func (slf *WSService) WSEventHandler(ev *event.Event) {
|
||||
}
|
||||
}
|
||||
|
||||
func (slf *WSService) SetProcessor(process processor.Processor,handler event.IEventHandler){
|
||||
slf.process = process
|
||||
slf.RegEventReciverFunc(event.Sys_Event_WebSocket,handler,slf.WSEventHandler)
|
||||
func (ws *WSService) SetProcessor(process processor.IProcessor,handler event.IEventHandler){
|
||||
ws.process = process
|
||||
ws.RegEventReceiverFunc(event.Sys_Event_WebSocket,handler, ws.WSEventHandler)
|
||||
}
|
||||
|
||||
func (slf *WSService) NewWSClient(conn *network.WSConn) network.Agent {
|
||||
slf.mapClientLocker.Lock()
|
||||
defer slf.mapClientLocker.Unlock()
|
||||
func (ws *WSService) NewWSClient(conn *network.WSConn) network.Agent {
|
||||
ws.mapClientLocker.Lock()
|
||||
defer ws.mapClientLocker.Unlock()
|
||||
|
||||
for {
|
||||
slf.initClientId+=1
|
||||
_,ok := slf.mapClient[slf.initClientId]
|
||||
ws.initClientId+=1
|
||||
_,ok := ws.mapClient[ws.initClientId]
|
||||
if ok == true {
|
||||
continue
|
||||
}
|
||||
|
||||
pClient := &WSClient{wsConn:conn, id:slf.initClientId}
|
||||
pClient.wsService = slf
|
||||
slf.mapClient[slf.initClientId] = pClient
|
||||
pClient := &WSClient{wsConn:conn, id: ws.initClientId}
|
||||
pClient.wsService = ws
|
||||
ws.mapClient[ws.initClientId] = pClient
|
||||
return pClient
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type WSClient struct {
|
||||
id uint64
|
||||
wsConn *network.WSConn
|
||||
wsService *WSService
|
||||
}
|
||||
|
||||
func (slf *WSClient) GetId() uint64 {
|
||||
return slf.id
|
||||
}
|
||||
@@ -149,27 +147,27 @@ func (slf *WSClient) OnClose(){
|
||||
delete (slf.wsService.mapClient,slf.GetId())
|
||||
}
|
||||
|
||||
func (slf *WSService) SendMsg(clientid uint64,msg interface{}) error{
|
||||
slf.mapClientLocker.Lock()
|
||||
client,ok := slf.mapClient[clientid]
|
||||
func (ws *WSService) SendMsg(clientid uint64,msg interface{}) error{
|
||||
ws.mapClientLocker.Lock()
|
||||
client,ok := ws.mapClient[clientid]
|
||||
if ok == false{
|
||||
slf.mapClientLocker.Unlock()
|
||||
ws.mapClientLocker.Unlock()
|
||||
return fmt.Errorf("client %d is disconnect!",clientid)
|
||||
}
|
||||
|
||||
slf.mapClientLocker.Unlock()
|
||||
bytes,err := slf.process.Marshal(msg)
|
||||
ws.mapClientLocker.Unlock()
|
||||
bytes,err := ws.process.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.wsConn.WriteMsg(bytes)
|
||||
}
|
||||
|
||||
func (slf *WSService) Close(clientid uint64) {
|
||||
slf.mapClientLocker.Lock()
|
||||
defer slf.mapClientLocker.Unlock()
|
||||
func (ws *WSService) Close(clientid uint64) {
|
||||
ws.mapClientLocker.Lock()
|
||||
defer ws.mapClientLocker.Unlock()
|
||||
|
||||
client,ok := slf.mapClient[clientid]
|
||||
client,ok := ws.mapClient[clientid]
|
||||
if ok == false{
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user