24
24
pushOptions struct {
25
25
// kafka.Writer options
26
26
allowAutoTopicCreation bool
27
+ balancer kafka.Balancer
27
28
28
29
// executors.ChunkExecutor options
29
30
chunkSize int
@@ -50,6 +51,9 @@ func NewPusher(addrs []string, topic string, opts ...PushOption) *Pusher {
50
51
51
52
// apply kafka.Writer options
52
53
producer .AllowAutoTopicCreation = options .allowAutoTopicCreation
54
+ if options .balancer != nil {
55
+ producer .Balancer = options .balancer
56
+ }
53
57
54
58
pusher := & Pusher {
55
59
producer : producer ,
@@ -134,6 +138,26 @@ func (p *Pusher) PushWithKey(ctx context.Context, key, v string) error {
134
138
}
135
139
}
136
140
141
+ // SetWriterBalancer set kafka-go custom writer balancer.
142
+ func (p * Pusher ) SetWriterBalancer (balancer kafka.Balancer ) {
143
+ if p .producer != nil {
144
+ p .producer .Balancer = balancer
145
+ }
146
+ }
147
+
148
+ // PushWithKey sends a message to the Kafka topic with custom message key.
149
+ func (p * Pusher ) PushWithKey (k , v string ) error {
150
+ msg := kafka.Message {
151
+ Key : []byte (k ), // custom message key
152
+ Value : []byte (v ),
153
+ }
154
+ if p .executor != nil {
155
+ return p .executor .Add (msg , len (v ))
156
+ } else {
157
+ return p .producer .WriteMessages (context .Background (), msg )
158
+ }
159
+ }
160
+
137
161
// WithChunkSize customizes the Pusher with the given chunk size.
138
162
func WithChunkSize (chunkSize int ) PushOption {
139
163
return func (options * pushOptions ) {
@@ -155,6 +179,13 @@ func WithAllowAutoTopicCreation() PushOption {
155
179
}
156
180
}
157
181
182
+ // WithBalancer customizes the Pusher with the given balancer.
183
+ func WithBalancer (balancer kafka.Balancer ) PushOption {
184
+ return func (options * pushOptions ) {
185
+ options .balancer = balancer
186
+ }
187
+ }
188
+
158
189
// WithSyncPush enables the Pusher to push messages synchronously.
159
190
func WithSyncPush () PushOption {
160
191
return func (options * pushOptions ) {
0 commit comments