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)
}
此条目发表在GolangLinux分类目录。将固定链接加入收藏夹。

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. github学习(二)

    Git学习(一) 学习github一定要学会git,否则在后续的github运用中会出现很多问题. 1.安装Git: Mac自带Git,Windows需要自己安装. 2.配置git: 配置user.n ...

  2. UI设计学习路线图

    文章转载自「开发者圆桌」一个关于开发者入门.进阶.踩坑的微信公众号 这里整理的UI设计学习路线图包含初中高三个部分,你可以通过百度云盘下载观看对应的视频 链接: http://pan.baidu.co ...

  3. wemall app商城源码Android 获取XML网络数据并绑定到ListView

    wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享Android 获取XML网络数据并绑定到Li ...

  4. 1634: [Usaco2007 Jan]Protecting the Flowers 护花

    1634: [Usaco2007 Jan]Protecting the Flowers 护花 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 493  So ...

  5. Maven项目搭建(一):Maven初体验

    今天给大家介绍一个项目管理和综合工具:Maven. Maven: maven读作 ['meivin],本意是指可以被信任的领域专家,致力于传播知识(来自于http://en.wikipedia.org ...

  6. eclipse和myeclipse设置默认编码格式为UTF-8

    1:jsp页面设置默认为utf-8 以eclipse为例 2:java界面设置: Window->Preferences->General->Workspace 面板Text fil ...

  7. iOS开发之清除缓存

    NSFileManager *mgr = [NSFileManager defaultManager]; NSString *cachePath = [NSSearchPathForDirectori ...

  8. Windows 10 Creaters Update 新功能——画中画模式和窗口高斯模糊

    在Windows 10 Creaters Update中,可以给窗口设置高斯模糊了,只要几行代码! <Grid Loaded="Grid_Loaded"> <Gr ...

  9. pyqt系列原创入门教程

    pyqt4入门教程 python pyqt4 PyQt是一个创建GUI应用程序的工具包.它是Python编程语言和Qt库的成功融合.Qt库是目前最强大的库之一. 通过pyqt可以实现很多我们想要的功能 ...

  10. CoreCLR源码探索(四) GC内存收集器的内部实现 分析篇

    在这篇中我将讲述GC Collector内部的实现, 这是CoreCLR中除了JIT以外最复杂部分,下面一些概念目前尚未有公开的文档和书籍讲到. 为了分析这部分我花了一个多月的时间,期间也多次向Cor ...