fox/rmq/rmq_test.go

83 lines
1.8 KiB
Go
Raw Normal View History

2025-05-25 20:02:15 +08:00
package rmq
import (
2025-08-27 23:02:26 +08:00
"context"
2025-09-03 22:40:27 +08:00
"fmt"
2025-08-27 23:02:26 +08:00
"github.com/fox/fox/log"
"os"
"os/signal"
"syscall"
2025-05-25 20:02:15 +08:00
"testing"
"time"
)
2025-09-03 22:21:30 +08:00
//const url = "amqp://admin:password@114.132.124.145:5672/vh_game_dev"
2025-08-27 23:02:26 +08:00
//const exchangeName = "test_e"
//const queueName = "test_q"
2025-05-25 20:02:15 +08:00
2025-08-27 23:02:26 +08:00
func initLog() {
log.Open("test.log", log.DebugL)
2025-05-25 20:02:15 +08:00
}
2025-08-27 23:02:26 +08:00
func TestRabbitmq(t *testing.T) {
initLog()
// 加载配置
rabbitConfig := LoadRabbitMQConfig()
// 创建连接
conn, err := NewConnection(rabbitConfig)
2025-05-25 20:02:15 +08:00
if err != nil {
2025-08-27 23:02:26 +08:00
log.ErrorF("Failed to create RabbitMQ connection: %v", err)
return
2025-05-25 20:02:15 +08:00
}
2025-08-27 23:02:26 +08:00
defer func() { _ = conn.Close() }()
2025-05-25 20:02:15 +08:00
2025-08-27 23:02:26 +08:00
// 启动重连监控
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go conn.Reconnect(ctx)
// 创建生产者
producer := NewProducer(conn, rabbitConfig)
defer func() { _ = producer.Close() }()
// 创建消费者处理器
handler := func(ctx context.Context, msg string) error {
log.InfoF("Processing message: %s", msg)
// 这里实现具体的业务逻辑
time.Sleep(1 * time.Second) // 模拟处理时间
return nil
2025-05-25 20:02:15 +08:00
}
2025-08-27 23:02:26 +08:00
// 创建消费者
consumer := NewConsumer(conn, rabbitConfig, handler)
defer func() { _ = consumer.Close() }()
// 启动消费者
if err = consumer.StartConsuming(ctx); err != nil {
log.ErrorF("Failed to start consumer: %v", err)
return
2025-05-25 20:02:15 +08:00
}
2025-08-27 23:02:26 +08:00
// 示例:发送测试消息
go func() {
time.Sleep(2 * time.Second) // 等待消费者启动
2025-09-03 22:40:27 +08:00
for i := 0; i < 10; i++ {
testMessage := fmt.Sprintf("hello world %d", i)
if err = producer.Publish(ctx, testMessage); err != nil {
log.ErrorF("Failed to publish test message: %v", err)
} else {
log.Info("Test message published successfully")
}
2025-08-27 23:02:26 +08:00
}
}()
// 等待中断信号
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Info("Shutting down...")
cancel()
2025-05-25 20:02:15 +08:00
}