电商评论数据蕴含用户情感与产品改进方向。本文基于[Go语言]+[NSQ消息队列],实现每秒万级评论数据的实时抓取与情感分析。
1. 系统架构与核心代码
go
package main
import (
"github.com/nsqio/go-nsq"
"encoding/json"
)
// 评论数据模型
type Comment struct {
Content string `json:"content"`
Platform string `json:"platform"`
Rating int `json:"rating"`
}
func main() {
// 创建NSQ消费者
config := nsq.NewConfig()
consumer, _ := nsq.NewConsumer("comments", "analysis", config)
// 注册处理函数
consumer.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error {
var comment Comment
if err := json.Unmarshal(message.Body, &comment); err != nil {
return err
}
// 情感分析执行
score := sentimentAnalysis(comment.Content)
if score < 0.3 && comment.Rating <= 3 {
saveToAlertDB(comment) // 存储负面评论
}
return nil
}))
// 连接NSQD服务
consumer.ConnectToNSQD("127.0.0.1:4150")
<-consumer.StopChan
}
关键技术:
- NSQ消息队列实现生产-消费解耦
- 协程池控制并发粒度(推荐使用
ants库) - [SnowNLP库]中文情感分析
[![]Mango:item_review - 获得淘宝商品评论0 赞同 · 0 评论 ][文章(_)
2. 性能压测对比
| 方案 | 单机QPS | CPU占用 | 内存消耗 |
|---|---|---|---|
| Python+Redis | 1,200 | 85% | 2.3GB |
| Go+NSQ | 9,800 | 62% | 680MB |
优化建议:
- 使用
sync.Pool减少GC压力 - 采用Protocol Buffers替代JSON序列化
3. 数据可视化([Grafana]示例)
sql
-- 负面评论统计SQL
SELECT
platform,
COUNT(*) AS total,
AVG(rating) AS avg_score
FROM
alert_comments
WHERE
create_time >= NOW() - INTERVAL '1 DAY'
GROUP BY
platform
example.com/path/to/ima…
图表说明:实时展示各平台负面评论占比、情感分分布与高频关键词