github.com/erda-project/erda-infra@v1.0.9/providers/kafka/examples/consumer/main.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "context" 19 "fmt" 20 "os" 21 "time" 22 23 "github.com/erda-project/erda-infra/base/logs" 24 "github.com/erda-project/erda-infra/base/servicehub" 25 "github.com/erda-project/erda-infra/providers/kafka" 26 ) 27 28 type config struct { 29 Input kafka.ConsumerConfig `file:"input"` 30 } 31 32 type provider struct { 33 Cfg *config 34 Log logs.Logger 35 Kafka kafka.Interface `autowired:"kafka-consumer"` 36 } 37 38 func (p *provider) Run(ctx context.Context) error { 39 p.Kafka.NewConsumer(&p.Cfg.Input, p.invoke) 40 for { 41 select { 42 case <-ctx.Done(): 43 return nil 44 } 45 } 46 } 47 48 func (p *provider) invoke(key []byte, value []byte, topic *string, timestamp time.Time) error { 49 fmt.Println(string(value)) 50 return nil 51 } 52 53 func init() { 54 servicehub.Register("examples", &servicehub.Spec{ 55 Services: []string{"hello"}, 56 ConfigFunc: func() interface{} { return &config{} }, 57 Creator: func() servicehub.Provider { 58 return &provider{} 59 }, 60 }) 61 } 62 63 func main() { 64 hub := servicehub.New() 65 hub.Run("examples", "", os.Args...) 66 }