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. 关于Xmanager使用问题的总结

    做大数据的人对Xmanager这类远程连接工具应该都不陌生,我在使用Xmanager时遇到了一些问题并经过google和亲测解决,写在这里与大家分享. 1. [问题描述] 在windows上使用Xma ...

  2. C#:查询某年(1900-2100)某月的日历

    using System;using System.Collections.Generic;public class Program    {     /********************主函数 ...

  3. 读书笔记 effective c++ Item 31 把文件之间的编译依赖降到最低

    1. 牵一发而动全身 现在开始进入你的C++程序,你对你的类实现做了一个很小的改动.注意,不是接口,只是实现:一个私有的stuff.然后你需要rebuild你的程序,计算着这个build应该几秒钟就足 ...

  4. Isomorphic Strings leetcode

    Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the chara ...

  5. 队列工厂之RedisMQ

    本次和大家分享的是RedisMQ队列的用法,前两篇文章队列工厂之(MSMQ)和队列工厂之RabbitMQ分别简单介绍对应队列环境的搭建和常用方法的使用,加上本篇分享的RedisMQ那么就完成了咋们队列 ...

  6. PMS5003ST+Arduino Nano 串口读取数据

    先上代码: 库文件是在guihub上的大神写的https://github.com/jbanaszczyk,我拿来小改下用以支持5003ST #include <Arduino.h> #i ...

  7. .net平台的MongoDB使用

    前言 最近花了点时间玩了下MongoDB.Driver,进行封装了工具库,平常也会经常用到MongoDB,因此写一篇文章梳理知识同时把自己的成果分享给大家. 本篇会设计到Lambda表达式的解析,有兴 ...

  8. waypoints

    http://imakewebthings.com/waypoints waypoints 滑冰122分钟 Cygwin http:/nxutils.sourceforge.net http://ba ...

  9. 用webstorm自动编译less产出css和sourcemap

    css产出sourcemap有什么用呢,可能大家要问这个问题了. 请移步这里 https://developers.google.com/chrome-developer-tools/docs/css ...

  10. Spring 框架原理

    [spring框架原理] Spring框架原理 [博主]高瑞林 [博客地址]http://www.cnblogs.com/grl214 写给读者的话 ------亲爱的读者感谢您对小编的支持,当我正值 ...