golang kafka – hello world

https://github.com/Shopify/sarama

https://shopify.github.io/sarama/

 

consumer.go

package main
 
import (
    "fmt"
    "github.com/Shopify/sarama"
    "log"
    "os"
    "strings"
    "sync"
)
 
var (
    wg     sync.WaitGroup
    logger = log.New(os.Stderr, "[srama]", log.LstdFlags)
)
 
func main() {
 
    sarama.Logger = logger
 
    consumer, err := sarama.NewConsumer(strings.Split("localhost:9092", ","), nil)
    if err != nil {
        logger.Println("Failed to start consumer: %s", err)
    }
 
    partitionList, err := consumer.Partitions("hello")
    if err != nil {
        logger.Println("Failed to get the list of partitions: ", err)
    }
 
    for partition := range partitionList {
        pc, err := consumer.ConsumePartition("hello", int32(partition), sarama.OffsetNewest)
        if err != nil {
            logger.Printf("Failed to start consumer for partition %d: %s\n", partition, err)
        }
        defer pc.AsyncClose()
 
        wg.Add(1)
 
        go func(sarama.PartitionConsumer) {
            defer wg.Done()
            for msg := range pc.Messages() {
                fmt.Printf("Partition:%d, Offset:%d, Key:%s, Value:%s", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value))
                fmt.Println()
            }
        }(pc)
    }
 
    wg.Wait()
 
    logger.Println("Done consuming topic hello")
    consumer.Close()
}

producer.go

package main
 
import (
    "github.com/Shopify/sarama"
    "log"
    "os"
    "strings"
)
 
var (
    logger = log.New(os.Stderr, "[srama]", log.LstdFlags)
)
 
func main() {
    sarama.Logger = logger
 
    config := sarama.NewConfig()
    config.Producer.RequiredAcks = sarama.WaitForAll
    config.Producer.Partitioner = sarama.NewRandomPartitioner
 
    msg := &sarama.ProducerMessage{}
    msg.Topic = "hello"
    msg.Partition = int32(-1)
    msg.Key = sarama.StringEncoder("key")
    msg.Value = sarama.ByteEncoder("你好, 世界!")
 
    producer, err := sarama.NewSyncProducer(strings.Split("localhost:9092", ","), config)
    if err != nil {
        logger.Println("Failed to produce message: %s", err)
        os.Exit(500)
    }
    defer producer.Close()
 
    partition, offset, err := producer.SendMessage(msg)
    if err != nil {
        logger.Println("Failed to produce message: ", err)
    }
    logger.Printf("partition=%d, offset=%d\n", partition, offset)
}
此条目发表在Golang, Linux分类目录。将固定链接加入收藏夹。

golang kafka的更多相关文章

  1. [Golang] kafka集群搭建和golang版生产者和消费者

    一.kafka集群搭建 至于kafka是什么我都不多做介绍了,网上写的已经非常详尽了. 1. 下载zookeeper  https://zookeeper.apache.org/releases.ht ...

  2. golang kafka client

    针对golang的 kafka client 有很多开源package,例如sarama, confluent等等.在使用sarama 包时,高并发中偶尔遇到crash.于是改用confluent-k ...

  3. golang kafka clinet 内存泄露问题处理

    go 内存泄露 新版本服务跑上一天内存占用20g,显然是内存泄露 内存泄露的问题难在定位 技术上的定位 主要靠 pprof 生成统计文件 之前写web项目 基于net/http/pprof 可以看到运 ...

  4. panic: interface conversion: interface {} is nil, not chan *sarama.ProducerError

    使用golang kafka sarama 包时,遇到如下问题: 高并发情况下使用同步sync producer,偶尔遇到crash: panic: interface conversion: int ...

  5. Spring Boot(十三)RabbitMQ安装与集成

    一.前言 RabbitMQ是一个开源的消息代理软件(面向消息的中间件),它的核心作用就是创建消息队列,异步接收和发送消息,MQ的全程是:Message Queue中文的意思是消息队列. 1.1 使用场 ...

  6. Shell 字符串处理

    字符串处理方式 计算字符串长度 获取子串在字符串中的索引位置 计算子串长度 抽取(截取)字串 1.计算字符串长度,有两种方式 $ ${#string} $ expr length "$str ...

  7. 基于 MySQL Binlog 的 Elasticsearch 数据同步实践 原

    一.背景 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品.订单等数据的多维度检索. 使用 Elasticsearch 存储业务数据可以 ...

  8. (转载)rabbitmq与springboot的安装与集成

    原文地址:https://segmentfault.com/a/1190000016991529 一.前言 RabbitMQ是一个开源的消息代理软件(面向消息的中间件),它的核心作用就是创建消息队列, ...

  9. shell编程:字符串处理方式

    字符串处理方式 计算字符串长度 获取子串在字符串中的索引位置 计算子串长度 抽取(截取)字串 1.计算字符串长度,有两种方式 $ ${#string} $ expr length "$str ...

随机推荐

  1. ASP渲染下拉框使时间依次减少

    <%    x=year(now())    y=year(now())-1    Do While  y>2002%><li><a href="#201 ...

  2. gulp折腾日记——gulp-livereload

    大家好,虽然在博客园注册了很长一段时间,但我还没在博客园写过博客,这是在博客园的第一篇博客,希望能养成每周写博客的好习惯 O(∩∩)O~~) 今天要聊得是gulp的一个实时刷新的插件gulp-live ...

  3. redux-form的学习笔记二--实现表单的同步验证

    (注:这篇博客参考自redux-form的官方英文文档)左转http://redux-form.com/6.5.0/examples/syncValidation/ 在这篇博客里,我将用redux-f ...

  4. 3396: [Usaco2009 Jan]Total flow 水流

    3396: [Usaco2009 Jan]Total flow 水流 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 179  Solved: 73[Su ...

  5. UINavigationBar统一修改导航条样式

    #pragma mark -- 统一导航条样式 //统一导航条样式 UIFont *font = [UIFont systemFontOfSize:19.f]; NSDictionary *textA ...

  6. spring mvc中的拦截器小结 .

    在spring mvc中,拦截器其实比较简单了,下面简单小结并demo下. preHandle:预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器(如我们上一章的Control ...

  7. ASP.NET MVC 创建控制器类过程

    MvcHandler.ProcessRequestInit()方法: 1.1获取控制器的名称string requiredString = this.RequestContext.RouteData. ...

  8. 源码分析Android Handler是如何实现线程间通信的

    源码分析Android Handler是如何实现线程间通信的 Handler作为Android消息通信的基础,它的使用是每一个开发者都必须掌握的.开发者从一开始就被告知必须在主线程中进行UI操作.但H ...

  9. HBuilder的webview操作

    HBuilder的webview操作 webviewAPI文档:http://www.html5plus.org/doc/zh_cn/webview.html 创建新的webview窗口: Webvi ...

  10. iwebshop中的增删改查

    <?php class Text extends IController { public function hello() { $this->redirect('hello'); } p ...