File tree 2 files changed +22
-3
lines changed
2 files changed +22
-3
lines changed Original file line number Diff line number Diff line change 1
1
package main
2
2
3
3
import (
4
+ "context"
4
5
"encoding/json"
5
6
"fmt"
6
7
"log"
@@ -41,7 +42,12 @@ func main() {
41
42
}
42
43
43
44
fmt .Println (string (body ))
44
- if err := pusher .Push (string (body )); err != nil {
45
+ if err := pusher .Push (context .Background (), string (body )); err != nil {
46
+ log .Fatal (err )
47
+ }
48
+
49
+ fmt .Println (string (body ))
50
+ if err := pusher .KPush (context .Background (), "test" , string (body )); err != nil {
45
51
log .Fatal (err )
46
52
}
47
53
}
Original file line number Diff line number Diff line change @@ -86,16 +86,29 @@ func (p *Pusher) Name() string {
86
86
return p .topic
87
87
}
88
88
89
+ // KPush sends a message to the Kafka topic.
90
+ func (p * Pusher ) KPush (ctx context.Context , k , v string ) error {
91
+ msg := kafka.Message {
92
+ Key : []byte (k ), // current timestamp
93
+ Value : []byte (v ),
94
+ }
95
+ if p .executor != nil {
96
+ return p .executor .Add (msg , len (v ))
97
+ } else {
98
+ return p .producer .WriteMessages (ctx , msg )
99
+ }
100
+ }
101
+
89
102
// Push sends a message to the Kafka topic.
90
- func (p * Pusher ) Push (v string ) error {
103
+ func (p * Pusher ) Push (ctx context. Context , v string ) error {
91
104
msg := kafka.Message {
92
105
Key : []byte (strconv .FormatInt (time .Now ().UnixNano (), 10 )), // current timestamp
93
106
Value : []byte (v ),
94
107
}
95
108
if p .executor != nil {
96
109
return p .executor .Add (msg , len (v ))
97
110
} else {
98
- return p .producer .WriteMessages (context . Background () , msg )
111
+ return p .producer .WriteMessages (ctx , msg )
99
112
}
100
113
}
101
114
You can’t perform that action at this time.
0 commit comments