4

Golang ZeroMQ PUB/SUB

 2 years ago
source link: https://ahaedgar.github.io/2018/10/10/Golang-ZeroMQ-PUBSUB/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Golang ZeroMQ PUB/SUB

发表于 2018-10-10

| 分类于 Golang

| 0

| 阅读次数:

字数统计: 480

近期研究了golang实现的zeromq的zmq4库,使用zmq4是实现了简单的发布/订阅模型。具体步骤如下:

  1. centos下安装zeromq

执行setup-zeromq.sh脚本

#!/usr/bin/bash

# Download zeromq
# Ref http://zeromq.org/intro:get-the-software
wget https://github.com/zeromq/libzmq/releases/download/v4.2.2/zeromq-4.2.2.tar.gz

# Unpack tarball package
tar xvzf zeromq-4.2.2.tar.gz

# Install dependency
sudo yum update -n && \
sudo yum install -y libtool pkg-config build-essential autoconf automake uuid-dev

# Create make file
cd zeromq-4.2.2
./configure

# Build and install(root permission only)
sudo make install

# Install zeromq driver on linux
sudo ldconfig

# Check installed
ldconfig -p | grep zmq

# Expected
############################################################
# libzmq.so.5 (libc6,x86-64) => /usr/local/lib/libzmq.so.5
# libzmq.so (libc6,x86-64) => /usr/local/lib/libzmq.so
############################################################

编译完成后:
需要在/etc/profile中添加:

export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

然后,运行source /etc/profile

此外,还需要将在/etc/ld.so.conf.d 中新建一个zeromq.conf文件,在此文件中写入:

/usr/local/lib

保存此次文件写入。

至此,zeromq安装完毕,可通过ldconfig -p | grep zeromq 验证是否已经安装完成。

  1. 安装go环境(忽略),拉去zmq4库
go get https://github.com/pebbe/zmq4
  1. 在$GOPATH/src 中创建两个go文件

zeromq_pub.go


package main

import (
zmq "github.com/pebbe/zmq4"
)

func main() {

newPublisher, _ := zmq.NewSocket(zmq.PUB)
newPublisher.Bind("tcp://*:5566")
for {
newPublisher.Send("test", 0)
}

}

zeromq_sub.go

package main

import (
"fmt"

zmq "github.com/pebbe/zmq4"
)

func main() {

q, _ := zmq.NewSocket(zmq.SUB)
defer q.Close()
q.Connect("tcp://192.168.***.***:5566") //ok!
//q.Connect("tcp://localhost:5566") ok!
//q.Connect("tcp://127.0.0.1:5566") ok!
q.SetSubscribe("")
for {
msg, _ := q.RecvMessage(0)
for _, str := range msg {
fmt.Println(str)
}

}

}

通过go run分别运行两个程序即可。

注意:订阅客户端连接的tcp://ip:port,以上三种情况均可成功连接。

------ 本文结束感谢您的阅读 ------

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK