github.com/erda-project/erda-infra@v1.0.9/providers/kafkav2/examples/producer/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  	"os"
    20  	"time"
    21  
    22  	"github.com/erda-project/erda-infra/base/logs"
    23  	"github.com/erda-project/erda-infra/base/servicehub"
    24  	"github.com/erda-project/erda-infra/providers/kafkav2"
    25  )
    26  
    27  type config struct {
    28  	Output kafkav2.ProducerConfig `file:"output"`
    29  }
    30  
    31  type provider struct {
    32  	Cfg   *config
    33  	Log   logs.Logger
    34  	Kafka kafkav2.Interface `autowired:"kafka-v2"`
    35  }
    36  
    37  func (p *provider) Run(ctx context.Context) error {
    38  	w, err := p.Kafka.NewProducer(p.Cfg.Output)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	ticker := time.NewTicker(time.Second)
    43  	defer ticker.Stop()
    44  	for {
    45  		select {
    46  		case <-ctx.Done():
    47  			return nil
    48  		case <-ticker.C:
    49  			err := w.Write(kafkav2.Message{
    50  				Topic: "test",
    51  				Data:  []byte("hello world"),
    52  			})
    53  			if err != nil {
    54  				p.Log.Errorf("write err: %w", err)
    55  			}
    56  		}
    57  	}
    58  }
    59  
    60  func init() {
    61  	servicehub.Register("examples", &servicehub.Spec{
    62  		Services:   []string{"hello"},
    63  		ConfigFunc: func() interface{} { return &config{} },
    64  		Creator: func() servicehub.Provider {
    65  			return &provider{}
    66  		},
    67  	})
    68  }
    69  
    70  func main() {
    71  	hub := servicehub.New()
    72  	hub.Run("examples", "", os.Args...)
    73  }