李伟乐 2 years ago
parent c8d4d3b0fe
commit 9291e6faf9
  1. 31
      log/mq/nsq.go
  2. 4
      pkg/captcha/captcha_test.go
  3. 12
      pkg/xgo/xgo.go

@ -1,9 +1,11 @@
package mq package mq
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"git.diulo.com/mogfee/protoc-gen-kit/log" "git.diulo.com/mogfee/protoc-gen-kit/log"
"git.diulo.com/mogfee/protoc-gen-kit/pkg/xgo"
"github.com/nsqio/go-nsq" "github.com/nsqio/go-nsq"
"sync" "sync"
"sync/atomic" "sync/atomic"
@ -11,28 +13,34 @@ import (
type nsqLogger struct { type nsqLogger struct {
topic string topic string
host string client *nsq.Producer
list chan []byte list chan []byte
wg sync.WaitGroup wg sync.WaitGroup
stop atomic.Bool stop atomic.Bool
} }
func (s *nsqLogger) Run(client *nsq.Producer) { func (s *nsqLogger) Start() error {
s.wg.Add(1) xgo.Go(func() {
defer s.wg.Done()
for { for {
if s.stop.Load() { if s.stop.Load() {
break break
} }
for v := range s.list { for v := range s.list {
if err := client.Publish(s.topic, v); err != nil { fmt.Println(string(v))
func(v []byte) {
s.wg.Add(1)
defer s.wg.Done()
if err := s.client.Publish(s.topic, v); err != nil {
fmt.Println(err) fmt.Println(err)
continue
} }
}(v)
} }
} }
})
return nil
} }
func (s *nsqLogger) Shutdown() error {
func (s *nsqLogger) Shutdown(ctx context.Context) error {
if s.stop.Load() { if s.stop.Load() {
return nil return nil
} }
@ -40,6 +48,11 @@ func (s *nsqLogger) Shutdown() error {
s.wg.Wait() s.wg.Wait()
return nil return nil
} }
func (s *nsqLogger) Name() string {
return "app_log"
}
func NewNsqLogger(host string, topic string) log.Logger { func NewNsqLogger(host string, topic string) log.Logger {
client, err := nsq.NewProducer(host, nsq.NewConfig()) client, err := nsq.NewProducer(host, nsq.NewConfig())
if err != nil { if err != nil {
@ -48,13 +61,11 @@ func NewNsqLogger(host string, topic string) log.Logger {
std := &nsqLogger{ std := &nsqLogger{
topic: topic, topic: topic,
host: host, client: client,
list: make(chan []byte, 1000), list: make(chan []byte, 1000),
wg: sync.WaitGroup{}, wg: sync.WaitGroup{},
} }
go std.Run(client)
return std return std
} }
func (l *nsqLogger) Log(level log.Level, keyvals ...any) error { func (l *nsqLogger) Log(level log.Level, keyvals ...any) error {

@ -8,8 +8,8 @@ import (
func TestGenerateKey(t *testing.T) { func TestGenerateKey(t *testing.T) {
client := redis.NewClient(&redis.Options{}) client := redis.NewClient(&redis.Options{})
store := NewRedisStore("user", client) store := NewRedisStore(client)
id, _, err := Generate(store) id, _, err := Generate()
fmt.Println(id, err) fmt.Println(id, err)
fmt.Println(store.Verify(id, "aa", false)) fmt.Println(store.Verify(id, "aa", false))
} }

@ -0,0 +1,12 @@
package xgo
import "fmt"
func Go(fun func()) {
go func() {
if err := recover(); err != nil {
fmt.Println(err)
}
fun()
}()
}
Loading…
Cancel
Save