-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcollections.go
236 lines (202 loc) · 5.36 KB
/
collections.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package service
import (
"context"
"encoding/json"
"fmt"
"github.com/rabbitmq/amqp091-go"
"github.com/redis/go-redis/v9"
"log"
"novaro-server/dao"
"novaro-server/model"
"time"
)
type CollectionsService struct {
dao *dao.CollectionsDao
rdb *redis.Client
mq *amqp091.Connection
userDao *dao.UsersDao
postDao *dao.PostsDao
}
func NewCollectionsService() *CollectionsService {
db := model.GetDB()
return &CollectionsService{
dao: dao.NewCollectionsDao(db),
rdb: model.GetRedisCli(),
mq: model.GetRabbitMqCli(),
userDao: dao.NewUsersDao(db),
postDao: dao.NewPostsDao(db),
}
}
func (s *CollectionsService) AddOrRemove(c *model.Collections) error {
exist, err := s.userDao.UserExists(c.UserId)
if err != nil || exist == false {
return fmt.Errorf("userId is not exist")
}
postExist, err := s.postDao.PostExists(c.PostId)
if err != nil || postExist == false {
return fmt.Errorf("postId is not exist")
}
var errs error
if collectionsExist := s.CollectionsExist(c.UserId, c.PostId); collectionsExist == true {
errs = s.unCollectionsTweet(c)
} else {
errs = s.collectionsTweet(c)
}
return errs
}
// 获取用户收藏的推文
func (s *CollectionsService) collectionsTweet(c *model.Collections) error {
ctx := context.Background()
pipeline := s.rdb.Pipeline()
// 将用户添加到推文的收藏集合中
key := fmt.Sprintf("tweet:%s:collections", c.PostId)
pipeline.SAdd(ctx, key, c.UserId)
pipeline.Expire(ctx, key, 5*time.Minute)
// 计数
pipeline.ZIncrBy(ctx, "tweet:collections:count", 1, c.PostId)
_, err := pipeline.Exec(ctx)
q := model.Queue{
Collections: *c,
Operation: "add",
}
go func() {
err := s.sendToRabbitMQ(q)
if err != nil {
// 在这里处理错误,可以记录日志或者重试
fmt.Printf("Error sending to RabbitMQ: %v\n", err)
}
}()
return err
}
// 从收藏中移除推文
func (s *CollectionsService) unCollectionsTweet(c *model.Collections) error {
// 删除redis缓存
ctx := context.Background()
pipeline := s.rdb.Pipeline()
// 将用户移除推文的收藏集合中
key := fmt.Sprintf("tweet:%s:collections", c.PostId)
pipeline.SRem(ctx, key, c.UserId)
pipeline.ZIncrBy(ctx, "tweet:collections:count", -1, c.PostId)
_, err := pipeline.Exec(ctx)
q := model.Queue{
Collections: *c,
Operation: "remove",
}
go func() {
err := s.sendToRabbitMQ(q)
if err != nil {
// 在这里处理错误,可以记录日志或者重试
fmt.Printf("Error sending to RabbitMQ: %v\n", err)
}
}()
return err
}
func (s *CollectionsService) CollectionsExist(userId string, postId string) bool {
key := fmt.Sprintf("tweet:%s:collections", postId)
result, err := s.rdb.SIsMember(context.Background(), key, userId).Result()
if err != nil {
e, _ := s.dao.CollectionsExist(userId, postId)
return e
}
return result
}
// 发送消息到RabbitMQ
func (s *CollectionsService) sendToRabbitMQ(q model.Queue) error {
ch, err := s.mq.Channel()
if err != nil {
return err
}
defer ch.Close()
body, err := json.Marshal(q)
if err != nil {
return err
}
err = ch.PublishWithContext(
context.Background(),
"", // exchange
"collections_queue", // routing key
false, // mandatory
false, // immediate
amqp091.Publishing{
ContentType: "application/json",
Body: body,
})
log.Println("发送成功")
return err
}
// 从RabbitMQ中消费消息
func (s *CollectionsService) consumeFromRabbitMQ() ([]model.Queue, error) {
ch, err := s.mq.Channel()
if err != nil {
return nil, fmt.Errorf("无法打开通道: %v", err)
}
defer ch.Close()
q, err := ch.QueueDeclare(
"collections_queue", // 队列名
true, // 持久化
false, // 不自动删除
false, // 非排他
false, // 不等待
nil, // 无额外参数
)
if err != nil {
return nil, fmt.Errorf("无法声明队列: %v", err)
}
err = ch.Qos(
1, // prefetch count
0, // prefetch size
false, // global
)
if err != nil {
return nil, fmt.Errorf("无法设置 QoS: %v", err)
}
// 开始消费消息
msgs, err := ch.Consume(
q.Name, // 队列
"", // 消费者
false, // 手动确认
false, // 非排他
false, // 不等待
false, // 无额外参数
nil,
)
if err != nil {
return nil, fmt.Errorf("无法注册消费者: %v", err)
}
var collections []model.Queue
timeout := time.After(5 * time.Second) // 设置5秒超时
for {
select {
case msg, ok := <-msgs:
log.Println("消费信息:", msg)
if !ok {
return collections, nil // 通道已关闭,返回已收集的数据
}
var qu model.Queue
err := json.Unmarshal(msg.Body, &qu)
if err != nil {
log.Printf("解析消息失败: %v", err)
msg.Nack(false, true) // 消息解析失败,重新入队
continue
}
collections = append(collections, qu)
msg.Ack(false) // 手动确认消息
case <-timeout:
return collections, nil // 超时,返回已收集的数据
}
}
}
// 将记录同步到数据库
func (s *CollectionsService) SyncToDatabase() {
messages, err := s.consumeFromRabbitMQ()
if messages == nil || err != nil {
log.Println("Failed to consumer from rabbitmq:", err)
return
}
err = s.loadingData(messages)
}
// 刷新数据
func (s *CollectionsService) loadingData(operations []model.Queue) error {
err := s.dao.RefreshData(operations)
return err
}