3 Star 5 Fork 3

三三物联网/ssiot-core

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
memory.go 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
zliu 提交于 2023-03-24 10:03 . 改名ssiot-core、合并msg-sdk
package queue
import (
"sync"
"github.com/google/uuid"
"gitee.com/sansaniot/ssiot-core/storage"
)
type queue chan storage.Messager
// NewMemory 内存模式
func NewMemory(poolNum uint) *Memory {
return &Memory{
queue: new(sync.Map),
PoolNum: poolNum,
}
}
type Memory struct {
queue *sync.Map
wait sync.WaitGroup
mutex sync.RWMutex
PoolNum uint
}
func (*Memory) String() string {
return "memory"
}
func (m *Memory) makeQueue() queue {
if m.PoolNum <= 0 {
return make(queue)
}
return make(queue, m.PoolNum)
}
func (m *Memory) Append(message storage.Messager) error {
m.mutex.RLock()
defer m.mutex.RUnlock()
memoryMessage := new(Message)
memoryMessage.SetID(message.GetID())
memoryMessage.SetStream(message.GetStream())
memoryMessage.SetValues(message.GetValues())
v, ok := m.queue.Load(message.GetStream())
if !ok {
v = m.makeQueue()
m.queue.Store(message.GetStream(), v)
}
var q queue
switch v.(type) {
case queue:
q = v.(queue)
default:
q = m.makeQueue()
m.queue.Store(message.GetStream(), q)
}
go func(gm storage.Messager, gq queue) {
gm.SetID(uuid.New().String())
gq <- gm
}(memoryMessage, q)
return nil
}
func (m *Memory) Register(name string, f storage.ConsumerFunc) {
m.mutex.RLock()
defer m.mutex.RUnlock()
v, ok := m.queue.Load(name)
if !ok {
v = m.makeQueue()
m.queue.Store(name, v)
}
var q queue
switch v.(type) {
case queue:
q = v.(queue)
default:
q = m.makeQueue()
m.queue.Store(name, q)
}
go func(out queue, gf storage.ConsumerFunc) {
var err error
for message := range q {
err = gf(message)
if err != nil {
out <- message
err = nil
}
}
}(q, f)
}
func (m *Memory) Run() {
m.wait.Add(1)
m.wait.Wait()
}
func (m *Memory) Shutdown() {
m.wait.Done()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/sansaniot/ssiot-core.git
git@gitee.com:sansaniot/ssiot-core.git
sansaniot
ssiot-core
ssiot-core
v1.6.6

搜索帮助