修改: 包名称为 zbus

This commit is contained in:
2023-07-22 02:48:46 +08:00
parent ced640ffa1
commit f7360c45d8
9 changed files with 66 additions and 66 deletions

2
go.mod
View File

@@ -51,5 +51,5 @@ replace (
zhub/cmd => ./zhub/cmd zhub/cmd => ./zhub/cmd
zhub/internal/config => ./zhub/internal/config zhub/internal/config => ./zhub/internal/config
zhub/internal/monitor => ./zhub/internal/monitor zhub/internal/monitor => ./zhub/internal/monitor
zhub/internal/zsub => ./zhub/internal/zsub zhub/internal/zbus => ./zhub/internal/zbus
) )

View File

@@ -3,7 +3,7 @@ package monitor
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
"zhub/internal/zsub" "zhub/internal/zbus"
) )
func init() { func init() {
@@ -22,22 +22,22 @@ func StartWatch() {
}) })
r.GET("/info", func(c *gin.Context) { r.GET("/info", func(c *gin.Context) {
c.JSON(http.StatusOK, zsub.Info()) c.JSON(http.StatusOK, zbus.Info())
}) })
r.GET("/cleanup", func(c *gin.Context) { r.GET("/cleanup", func(c *gin.Context) {
zsub.Hub.Clearup() zbus.Bus.Clearup()
c.JSON(http.StatusOK, "+OK") c.JSON(http.StatusOK, "+OK")
}) })
r.GET("/timer/reload", func(c *gin.Context) { r.GET("/timer/reload", func(c *gin.Context) {
zsub.Hub.ReloadTimer() zbus.Bus.ReloadTimer()
c.JSON(http.StatusOK, "+reload timer ok") c.JSON(http.StatusOK, "+reload timer ok")
}) })
r.GET("/topic/publish", func(c *gin.Context) { r.GET("/topic/publish", func(c *gin.Context) {
topic := c.Query("topic") topic := c.Query("topic")
value := c.Query("value") value := c.Query("value")
zsub.Hub.Publish(topic, value) zbus.Bus.Publish(topic, value)
c.JSON(http.StatusOK, "+OK") c.JSON(http.StatusOK, "+OK")
}) })
r.GET("/topic/delay", func(c *gin.Context) { r.GET("/topic/delay", func(c *gin.Context) {
@@ -45,16 +45,16 @@ func StartWatch() {
value := c.Query("value") value := c.Query("value")
delay := c.Query("delay") delay := c.Query("delay")
zsub.Hub.Delay([]string{"delay", topic, value, delay}) zbus.Bus.Delay([]string{"delay", topic, value, delay})
c.JSON(http.StatusOK, "+OK") c.JSON(http.StatusOK, "+OK")
}) })
// reload the auth configuration // reload the auth configuration
r.GET("/auth/reload", func(c *gin.Context) { r.GET("/auth/reload", func(c *gin.Context) {
zsub.AuthManager.Reload() zbus.AuthManager.Reload()
c.JSON(http.StatusOK, "+OK") c.JSON(http.StatusOK, "+OK")
}) })
watchAddr := zsub.Conf.Service.Watch watchAddr := zbus.Conf.Service.Watch
r.Run(watchAddr) r.Run(watchAddr)
} }

View File

@@ -1,4 +1,4 @@
package zsub package zbus
import ( import (
"encoding/json" "encoding/json"
@@ -118,13 +118,13 @@ func handleMessage(v Message) {
return return
case "rpc": case "rpc":
// if rpc and no sub back error // if rpc and no sub back error
if Hub.noSubscribe(rcmd[1]) { if Bus.noSubscribe(rcmd[1]) {
rpcBody := make(map[string]string) rpcBody := make(map[string]string)
json.Unmarshal([]byte(rcmd[2]), &rpcBody) json.Unmarshal([]byte(rcmd[2]), &rpcBody)
log.Println("rpc no subscribe: ", rcmd[1]) log.Println("rpc no subscribe: ", rcmd[1])
ruk := rpcBody["ruk"] ruk := rpcBody["ruk"]
Hub.Publish(strings.Split(ruk, "::")[0], "{'retcode': 404, 'retinfo': '服务离线!', 'ruk': '"+ruk+"'}") Bus.Publish(strings.Split(ruk, "::")[0], "{'retcode': 404, 'retinfo': '服务离线!', 'ruk': '"+ruk+"'}")
return return
} }
@@ -134,7 +134,7 @@ func handleMessage(v Message) {
/*if len(topicChan) < cap(topicChan) { /*if len(topicChan) < cap(topicChan) {
topicChan <- rcmd topicChan <- rcmd
}*/ }*/
Hub.Publish(rcmd[1], rcmd[2]) Bus.Publish(rcmd[1], rcmd[2])
} }
return return
case "publish": case "publish":
@@ -144,13 +144,13 @@ func handleMessage(v Message) {
/*if len(topicChan) < cap(topicChan) { /*if len(topicChan) < cap(topicChan) {
topicChan <- rcmd topicChan <- rcmd
}*/ }*/
Hub.Publish(rcmd[1], rcmd[2]) Bus.Publish(rcmd[1], rcmd[2])
} }
return return
case "broadcast": case "broadcast":
Hub.broadcast(rcmd[1], rcmd[2]) Bus.broadcast(rcmd[1], rcmd[2])
case "delay": case "delay":
Hub.Delay(rcmd) Bus.Delay(rcmd)
default: default:
} }
@@ -178,7 +178,7 @@ func handleMessage(v Message) {
} }
case "timer": case "timer":
for _, name := range rcmd[1:] { for _, name := range rcmd[1:] {
Hub.timer([]string{"timer", name}, c) // append to timers Bus.timer([]string{"timer", name}, c) // append to timers
c.timers = append(c.timers, name) // append to conns c.timers = append(c.timers, name) // append to conns
} }
case "cmd": case "cmd":
@@ -187,12 +187,12 @@ func handleMessage(v Message) {
} }
switch rcmd[1] { switch rcmd[1] {
case "reload-timer": case "reload-timer":
Hub.ReloadTimer() Bus.ReloadTimer()
case "shutdown": case "shutdown":
if AuthManager.IsAdmin(c.user) { if AuthManager.IsAdmin(c.user) {
return return
} }
Hub.shutdown() Bus.shutdown()
} }
case "lock": case "lock":
// lock key uuid 5 // lock key uuid 5
@@ -201,14 +201,14 @@ func handleMessage(v Message) {
return return
} }
d, _ := strconv.Atoi(rcmd[3]) d, _ := strconv.Atoi(rcmd[3])
Hub._lock(&Lock{key: rcmd[1], uuid: rcmd[2], duration: d}) Bus._lock(&Lock{key: rcmd[1], uuid: rcmd[2], duration: d})
case "unlock": case "unlock":
// unlock key uuid // unlock key uuid
if len(rcmd) != 3 { if len(rcmd) != 3 {
c.send("-Error: unlock para number![" + strings.Join(rcmd, " ") + "]") c.send("-Error: unlock para number![" + strings.Join(rcmd, " ") + "]")
return return
} }
Hub._unlock(Lock{key: rcmd[1], uuid: rcmd[2]}) Bus._unlock(Lock{key: rcmd[1], uuid: rcmd[2]})
default: default:
c.send("-Error: default not supported:[" + strings.Join(rcmd, " ") + "]") c.send("-Error: default not supported:[" + strings.Join(rcmd, " ") + "]")
return return

View File

@@ -1,4 +1,4 @@
package zsub package zbus
import ( import (
"bufio" "bufio"
@@ -34,7 +34,7 @@ func Append(str string, fileName string) {
} }
} }
func (s *ZSub) SaveData() { func (s *ZBus) SaveData() {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
log.Println("SaveData Recovered:", r) log.Println("SaveData Recovered:", r)
@@ -89,12 +89,12 @@ func (s *ZSub) SaveData() {
}() }()
} }
func (s *ZSub) LoadData() { func (s *ZBus) LoadData() {
s.loadDelay() s.loadDelay()
// s.loadLock() // s.loadLock()
} }
func (s *ZSub) loadDelay() { func (s *ZBus) loadDelay() {
f, err := os.Open(datadir + "/delay.z") f, err := os.Open(datadir + "/delay.z")
if err != nil { if err != nil {
return return
@@ -129,7 +129,7 @@ func (s *ZSub) loadDelay() {
} }
} }
func (s *ZSub) loadLock() { func (s *ZBus) loadLock() {
f, err := os.Open(datadir + "/lock.z") f, err := os.Open(datadir + "/lock.z")
if err != nil { if err != nil {
return return

View File

@@ -1,4 +1,4 @@
package zsub package zbus
import ( import (
"log" "log"

View File

@@ -1,4 +1,4 @@
package zsub package zbus
import ( import (
"bufio" "bufio"
@@ -17,7 +17,7 @@ import (
var ( var (
Conf config.Config Conf config.Config
Hub = &ZSub{ Bus = &ZBus{
topics: make(map[string]*ZTopic), topics: make(map[string]*ZTopic),
timers: make(map[string]*ZTimer), timers: make(map[string]*ZTimer),
delays: make(map[string]*ZDelay), delays: make(map[string]*ZDelay),
@@ -41,7 +41,7 @@ func init() {
} }
}() }()
conns := make([]*ZConn, 0) // 需要关闭的连接 conns := make([]*ZConn, 0) // 需要关闭的连接
for _, c := range Hub.conns { for _, c := range Bus.conns {
if c.ping > 0 && c.ping-c.pong > 19 { if c.ping > 0 && c.ping-c.pong > 19 {
conns = c.appendTo(conns) conns = c.appendTo(conns)
continue continue
@@ -63,12 +63,12 @@ func init() {
} }
Hub.SaveData() Bus.SaveData()
} }
}() }()
} }
type ZSub struct { type ZBus struct {
sync.RWMutex sync.RWMutex
topics map[string]*ZTopic topics map[string]*ZTopic
timers map[string]*ZTimer timers map[string]*ZTimer
@@ -119,9 +119,9 @@ func NewZConn(conn *net.Conn) *ZConn {
3若有待消费消息启动消费 3若有待消费消息启动消费
*/ */
func (c *ZConn) subscribe(topic string) { // 新增订阅 zconn{} func (c *ZConn) subscribe(topic string) { // 新增订阅 zconn{}
Hub.Lock() Bus.Lock()
defer Hub.Unlock() defer Bus.Unlock()
ztopic := Hub.topics[topic] //ZTopic ztopic := Bus.topics[topic] //ZTopic
if ztopic == nil { if ztopic == nil {
ztopic = &ZTopic{ ztopic = &ZTopic{
groups: map[string]*ZGroup{}, groups: map[string]*ZGroup{},
@@ -129,7 +129,7 @@ func (c *ZConn) subscribe(topic string) { // 新增订阅 zconn{}
chMsg: make(chan string, 500), chMsg: make(chan string, 500),
} }
ztopic.init() ztopic.init()
Hub.topics[topic] = ztopic Bus.topics[topic] = ztopic
} }
zgroup := ztopic.groups[c.groupid] //ZGroup zgroup := ztopic.groups[c.groupid] //ZGroup
@@ -159,7 +159,7 @@ func (c *ZConn) unsubscribe(topic string) { // 取消订阅 zconn{}
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
close(c.substoped[topic]) close(c.substoped[topic])
ztopic := Hub.topics[topic] //ZTopic ztopic := Bus.topics[topic] //ZTopic
if ztopic == nil { if ztopic == nil {
return return
} }
@@ -205,10 +205,10 @@ func (c *ZConn) close() {
} }
// timer conn close // timer conn close
Hub.Lock() Bus.Lock()
defer Hub.Unlock() defer Bus.Unlock()
for _, topic := range c.timers { // fixme: 数据逻辑交叉循环 for _, topic := range c.timers { // fixme: 数据逻辑交叉循环
timer := Hub.timers[topic] timer := Bus.timers[topic]
if timer == nil { if timer == nil {
continue continue
} }
@@ -267,8 +267,8 @@ func StartServer(addr string, conf config.Config) {
}() }()
// 重新加载[定时、延时] // 重新加载[定时、延时]
go Hub.ReloadTimer() go Bus.ReloadTimer()
go Hub.LoadData() go Bus.LoadData()
// 启动服务监听 // 启动服务监听
listen, err := net.Listen("tcp", addr) listen, err := net.Listen("tcp", addr)
@@ -286,12 +286,12 @@ func StartServer(addr string, conf config.Config) {
zConn := NewZConn(&conn) zConn := NewZConn(&conn)
log.Printf("conn start: %s [%d]\n", conn.RemoteAddr(), zConn.sn) log.Printf("conn start: %s [%d]\n", conn.RemoteAddr(), zConn.sn)
go Hub.handlerConn(zConn) go Bus.handlerConn(zConn)
} }
} }
// 连接处理 // 连接处理
func (s *ZSub) handlerConn(c *ZConn) { func (s *ZBus) handlerConn(c *ZConn) {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
log.Println("handlerConn Recovered:", r) log.Println("handlerConn Recovered:", r)
@@ -301,7 +301,7 @@ func (s *ZSub) handlerConn(c *ZConn) {
defer func() { defer func() {
// conn remove to conns // conn remove to conns
funChan <- func() { funChan <- func() {
Hub.conns = c.removeTo(Hub.conns) Bus.conns = c.removeTo(Bus.conns)
} }
// close ZConn // close ZConn
@@ -310,7 +310,7 @@ func (s *ZSub) handlerConn(c *ZConn) {
// conn add to conns // conn add to conns
funChan <- func() { funChan <- func() {
Hub.conns = c.appendTo(Hub.conns) Bus.conns = c.appendTo(Bus.conns)
} }
reader := bufio.NewReader(*c.conn) reader := bufio.NewReader(*c.conn)
@@ -365,7 +365,7 @@ Publish topic message
1send message to topic's chan 1send message to topic's chan
2feedback send success to sender, and sending message to topic's subscripts 2feedback send success to sender, and sending message to topic's subscripts
*/ */
func (s *ZSub) Publish(topic, msg string) { func (s *ZBus) Publish(topic, msg string) {
s.RLock() s.RLock()
defer s.RUnlock() defer s.RUnlock()
ztopic := s.topics[topic] //ZTopic ztopic := s.topics[topic] //ZTopic
@@ -386,7 +386,7 @@ func (s *ZSub) Publish(topic, msg string) {
/* /*
send broadcast message send broadcast message
*/ */
func (s *ZSub) broadcast(topic, msg string) { func (s *ZBus) broadcast(topic, msg string) {
s.RLock() s.RLock()
defer s.RUnlock() defer s.RUnlock()
if strings.EqualFold(topic, "lock") { if strings.EqualFold(topic, "lock") {
@@ -409,7 +409,7 @@ func (s *ZSub) broadcast(topic, msg string) {
lock: lock key uuid t lock: lock key uuid t
unlock: unlock key uuid unlock: unlock key uuid
*/ */
func (s *ZSub) _lock(lock *Lock) { func (s *ZBus) _lock(lock *Lock) {
locks := s.locks[lock.key] locks := s.locks[lock.key]
if locks == nil { if locks == nil {
locks = make([]*Lock, 0) locks = make([]*Lock, 0)
@@ -432,7 +432,7 @@ func (s *ZSub) _lock(lock *Lock) {
s.locks[lock.key] = append(locks, lock) s.locks[lock.key] = append(locks, lock)
} }
} }
func (s *ZSub) _unlock(l Lock) { func (s *ZBus) _unlock(l Lock) {
locks := s.locks[l.key] locks := s.locks[l.key]
if locks == nil || len(locks) == 0 { if locks == nil || len(locks) == 0 {
return return
@@ -455,7 +455,7 @@ func (s *ZSub) _unlock(l Lock) {
} }
} }
func (s *ZSub) shutdown() { func (s *ZBus) shutdown() {
s.SaveData() s.SaveData()
os.Exit(0) os.Exit(0)
} }
@@ -463,7 +463,7 @@ func (s *ZSub) shutdown() {
func Info() map[string]interface{} { func Info() map[string]interface{} {
// topics // topics
topics := map[string]interface{}{} topics := map[string]interface{}{}
for s, topic := range Hub.topics { for s, topic := range Bus.topics {
// {groups:[{name:xxx,size:xx}]} // {groups:[{name:xxx,size:xx}]}
arr := make([]map[string]interface{}, 0) arr := make([]map[string]interface{}, 0)
@@ -480,7 +480,7 @@ func Info() map[string]interface{} {
// conns // conns
conns := make([]interface{}, 0) conns := make([]interface{}, 0)
for _, c := range Hub.conns { for _, c := range Bus.conns {
m := make(map[string]interface{}, 0) m := make(map[string]interface{}, 0)
m["remoteaddr"] = (*c.conn).RemoteAddr() m["remoteaddr"] = (*c.conn).RemoteAddr()
m["groupid"] = c.groupid m["groupid"] = c.groupid
@@ -493,14 +493,14 @@ func Info() map[string]interface{} {
info := map[string]interface{}{ info := map[string]interface{}{
"topics": topics, "topics": topics,
"topicsize": len(topics), "topicsize": len(topics),
"timersize": len(Hub.timers), "timersize": len(Bus.timers),
"conns": conns, "conns": conns,
"connsize": len(Hub.conns), "connsize": len(Bus.conns),
} }
return info return info
} }
func (s *ZSub) Clearup() { func (s *ZBus) Clearup() {
for tn, topic := range s.topics { for tn, topic := range s.topics {
for _, group := range topic.groups { for _, group := range topic.groups {
if len(group.conns) > 0 || topic.mcount > group.offset { if len(group.conns) > 0 || topic.mcount > group.offset {
@@ -513,7 +513,7 @@ func (s *ZSub) Clearup() {
} }
} }
func (s *ZSub) noSubscribe(topic string) bool { func (s *ZBus) noSubscribe(topic string) bool {
zTopic := s.topics[topic] zTopic := s.topics[topic]
if zTopic == nil || len(zTopic.groups) == 0 { if zTopic == nil || len(zTopic.groups) == 0 {
return true return true

View File

@@ -1,4 +1,4 @@
package zsub package zbus
import ( import (
"database/sql" "database/sql"
@@ -29,7 +29,7 @@ type ZDelay struct {
} }
// Delay : delay topic value 100 -> publish topic value // Delay : delay topic value 100 -> publish topic value
func (s *ZSub) Delay(rcmd []string) { func (s *ZBus) Delay(rcmd []string) {
s.Lock() s.Lock()
defer func() { defer func() {
s.Unlock() s.Unlock()
@@ -70,7 +70,7 @@ func (s *ZSub) Delay(rcmd []string) {
select { select {
case <-delay.Timer.C: case <-delay.Timer.C:
log.Println("delay send:", rcmd[1], rcmd[2]) log.Println("delay send:", rcmd[1], rcmd[2])
Hub.Publish(rcmd[1], rcmd[2]) Bus.Publish(rcmd[1], rcmd[2])
funChan <- func() { funChan <- func() {
delete(s.delays, rcmd[1]+"-"+rcmd[2]) delete(s.delays, rcmd[1]+"-"+rcmd[2])
} }
@@ -82,7 +82,7 @@ func (s *ZSub) Delay(rcmd []string) {
/* /*
["Timer", Topic, expr, 0|1] ["Timer", Topic, expr, 0|1]
*/ */
func (s *ZSub) timer(rcmd []string, c *ZConn) { func (s *ZBus) timer(rcmd []string, c *ZConn) {
s.Lock() s.Lock()
defer s.Unlock() defer s.Unlock()
timer := s.timers[rcmd[1]] timer := s.timers[rcmd[1]]
@@ -155,7 +155,7 @@ func (s *ZSub) timer(rcmd []string, c *ZConn) {
} }
} }
func (s *ZSub) ReloadTimer() { func (s *ZBus) ReloadTimer() {
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
Conf.Ztimer.Db.User, Conf.Ztimer.Db.User,
Conf.Ztimer.Db.Password, Conf.Ztimer.Db.Password,

View File

@@ -1,4 +1,4 @@
package zsub package zbus
import ( import (
"fmt" "fmt"

View File

@@ -6,7 +6,7 @@ import (
"zhub/cmd" "zhub/cmd"
"zhub/internal/config" "zhub/internal/config"
"zhub/internal/monitor" "zhub/internal/monitor"
"zhub/internal/zsub" "zhub/internal/zbus"
) )
func main() { func main() {
@@ -30,7 +30,7 @@ func main() {
} }
if rcmd != "" { // 如果指定了客户端命令 if rcmd != "" { // 如果指定了客户端命令
adminToken, err := zsub.AuthManager.AdminToken() // 认证信息 adminToken, err := zbus.AuthManager.AdminToken() // 认证信息
if err != nil { if err != nil {
log.Fatal(err) // Configuration error, stop the client from running. log.Fatal(err) // Configuration error, stop the client from running.
return return
@@ -54,6 +54,6 @@ func main() {
cmd.ClientRun(addr) // 客户端运行 cmd.ClientRun(addr) // 客户端运行
} else { } else {
go monitor.StartWatch() // 启动监控协程 go monitor.StartWatch() // 启动监控协程
zsub.StartServer(addr, conf) // 启动服务进程 zbus.StartServer(addr, conf) // 启动服务进程
} }
} }