docker 配置 kafka+zookeeper,golang接入示例

1 非docker 安装

https://www-eu.apache.org/dist/kafka/2.3.0/kafka_2.11-2.3.0.tgz
tar -zxvf kafka_2.11-2.3.0.tgz
mv kafka_2.11-2.3.0 /usr/local/kafka
vim /usr/local/kafka/config/server.properties

broker.id=1
log.dir=/data/kafka/logs

配置zookeeper 使用kafka/bin/下自带的zk

bin/zookeeper-server-start.sh -daemon config/zookeeper.properties
kafka-zk 需要依赖java环境
apt-get install openjdk-8-jdk

运行 报错 卒。配置低了

bin/kafka-server-start.sh  config/server.properties

OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x00000000c0000000, 1073741824, 0) failed; error='Cannot allocate memory' (errno=12)
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 1073741824 bytes for committing reserved memory.
# An error report file with more information is saved as:
# /usr/local/kafka/hs_err_pid25796.log

2 重新开始
使用docker安装

sudo docker pull wurstmeister/kafka
sudo docker pull wurstmeister/zookeeper

docker-compose.yml

version: "3"
services:
  zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka
    depends_on: [ zookeeper ]
    ports:
      - "9092:9092"
    environment:
      KAFKA_ADVERTISED_HOST_NAME: 10.1.1.1
      KAFKA_CREATE_TOPICS: "test:1:1"
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
sudo docker-compose up  

报错

Creating kafka_zookeeper_1 ... error

ERROR: for kafka_zookeeper_1  Cannot start service zookeeper: no status provided on response: unknown

ERROR: for zookeeper  Cannot start service zookeeper: no status provided on response: unknown
ERROR: Encountered errors while bringing up the project.

换云搬瓦工的机器试一下

docker-compose up -d
Creating network "kafka_default" with the default driver
Creating kafka_zookeeper_1 ... done
Creating kafka_kafka_1     ... done

但是docker ps -a 发现只有zookeeper启动了,kafka失败, 检查日志 发现kafka运行需要java环境,而且对内存有要求,搬瓦工的vps不足够

docker-compose logs -f | grep "kafka"
Attaching to kafka_kafka_1, kafka_zookeeper_1
kafka_1      | waiting for kafka to be ready
kafka_1      | [Configuring] 'advertised.port' in '/opt/kafka/config/server.properties'
kafka_1      | Excluding KAFKA_HOME from broker config
kafka_1      | [Configuring] 'advertised.host.name' in '/opt/kafka/config/server.properties'
kafka_1      | [Configuring] 'port' in '/opt/kafka/config/server.properties'
kafka_1      | [Configuring] 'broker.id' in '/opt/kafka/config/server.properties'
kafka_1      | Excluding KAFKA_VERSION from broker config
kafka_1      | [Configuring] 'zookeeper.connect' in '/opt/kafka/config/server.properties'
kafka_1      | [Configuring] 'log.dirs' in '/opt/kafka/config/server.properties'
kafka_1      | #
kafka_1      | # There is insufficient memory for the Java Runtime Environment to continue.
kafka_1      | # Native memory allocation (mmap) failed to map 1073741824 bytes for committing reserved memory.
kafka_1      | # An error report file with more information is saved as:
kafka_1      | # //hs_err_pid1.log
kafka_1      | OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x00000000c0000000, 1073741824, 0) failed; error='Out of memory' (errno=12)
kafka_1      | waiting for kafka to be ready
kafka_1      | [Configuring] 'advertised.port' in '/opt/kafka/config/server.properties'
kafka_1      | Excluding KAFKA_HOME from broker config
kafka_1      | [Configuring] 'advertised.host.name' in '/opt/kafka/config/server.properties'
kafka_1      | [Configuring] 'port' in '/opt/kafka/config/server.properties'
kafka_1      | [Configuring] 'broker.id' in '/opt/kafka/config/server.properties'
kafka_1      | Excluding KAFKA_VERSION from broker config
kafka_1      | [Configuring] 'zookeeper.connect' in '/opt/kafka/config/server.properties'
kafka_1      | [Configuring] 'log.dirs' in '/opt/kafka/config/server.properties'
kafka_1      | OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x00000000c0000000, 1073741824, 0) failed; error='Out of memory' (errno=12)
kafka_1      | #
kafka_1      | # There is insufficient memory for the Java Runtime Environment to continue.
kafka_1      | # Native memory allocation (mmap) failed to map 1073741824 bytes for committing reserved memory.
kafka_1      | # An error report file with more information is saved as:
kafka_1      | # /tmp/hs_err_pid1.log
kafka_kafka_1 exited with code 1
^CERROR: Aborting.

因此修改docker-compose.yml 加入以下

KAFKA_HEAP_OPTS: "-Xmx256M -Xms128M"

stop 再启动

docker-compose stop
docker-compose up -d

完美

CONTAINER ID        IMAGE                                               COMMAND                  CREATED             STATUS                  PORTS                                                NAMES
08a4907a4ada        wurstmeister/kafka                                  "start-kafka.sh"         22 minutes ago      Up 22 minutes           0.0.0.0:9092->9092/tcp                               kafka_kafka_1
162253966fde        wurstmeister/zookeeper                              "/bin/sh -c '/usr/sb…"   About an hour ago   Up 22 minutes           22/tcp, 2888/tcp, 3888/tcp, 0.0.0.0:2181->2181/tcp   kafka_zookeeper_1

测试
进入容器

docker exec -it kafka_kafka_1 bash

查看已经建好的topic (docker-compose.yml)

$KAFKA_HOME/bin/kafka-topics.sh --list --zookeeper kafka_zookeeper_1:2181

test

发送消息

$KAFKA_HOME/bin/kafka-console-producer.sh --topic=test --broker-list kafka_kafka_1:9092
>
>xx
>yy
>zz

接收消息

$KAFKA_HOME/bin/kafka-console-consumer.sh --bootstrap-server kafka_kafka_1:9092 --from-beginning --topic test

xx
yy
zz

接下来是golang接入kafka了

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/segmentio/kafka-go"
)

var (
    addr  = "10.1.1.1:9092"
    topic = "test"
)

func main() {
    go Receive()
    go Publish()
    time.Sleep(time.Second * 100000)
}

func Receive() {
    // make a new reader that consumes from topic-A, partition 0, at offset 42
    fmt.Println("receive connecting ...")
    r := kafka.NewReader(kafka.ReaderConfig{
        Brokers:   []string{addr},
        Topic:     topic,
        Partition: 0,
        MinBytes:  10e3, // 10KB
        MaxBytes:  10e6, // 10MB
        //MaxWait:   time.Hour,
    })
    //r.SetOffset(42)
    ctx, _ := context.WithTimeout(context.Background(), time.Second*2)
    for {
        fmt.Println("receive start ...")
        m, err := r.ReadMessage(ctx)
        fmt.Println("receive one ...")
        if err != nil {
            fmt.Println("readmessave error", err)
            break
        }
        fmt.Printf("message at offset %d: %s = %s\n", m.Offset, string(m.Key), string(m.Value))
    }
    fmt.Println("receive close")
    r.Close()
}

func Publish() {
    fmt.Println("publish connecting ...")
    w := kafka.NewWriter(kafka.WriterConfig{
        Brokers:  []string{addr},
        Topic:    topic,
        Balancer: &kafka.LeastBytes{},
    })

    fmt.Println("publish start ...")
    for {
        message := "msg" + time.Now().String()
        err := w.WriteMessages(context.Background(),
            kafka.Message{
                Key:   []byte("Key-A"),
                Value: []byte(message),
            },
        )

        if err != nil {
            print("publish err:", err)
            return
        } else {
            fmt.Println("publish sucess")
        }

        time.Sleep(time.Second)
    }
    fmt.Println("public close")
    w.Close()
}

运行

go run main.go
receive connecting ...
publish connecting ...
publish start ...
receive start ...
message at offset 0:  = 
message at offset 1:  = xx
message at offset 2:  = yy
message at offset 3:  = zz
message at offset 4: Key-A = msg2019-10-11 17:51:32.305919841 +0800 CST m=+0.000266091
message at offset 5: Key-A = msg2019-10-11 17:53:22.818207089 +0800 CST m=+0.000368552
message at offset 6: Key-A = msg2019-10-11 17:53:26.847210435 +0800 CST m=+4.029372111
message at offset 7: Key-A = msg2019-10-11 17:53:42.670721312 +0800 CST m=+0.000364712

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容