1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golang と RabbitMQ

Posted at

今回GoでAPIを実装するにあたり、イベントを取得します。
イベントはRabbitMQです。

今回は
"github.com/streadway/amqp"
パッケージを使用することにします。
イベント監視処理は、下記となります。

func main() {
	// RabbitMQ
	app := makeApp()
        app.Run(os.Args)
}

func makeApp() *cli.App {
	app := cli.NewApp()
	app.Name = "おすきな名前を"
	app.Usage = "RubbitMQからのメッセージ取得"
	app.Version = "1.0"
	app.Compiled = time.Now()
	app.Commands = []cli.Command{
		{
			Name:   "rabbitmq",  //(A)
			Usage:  "cacheClear対象のistyle_idの取得",
			Action: catchEventMessages,
		},
	}
	return app
}

func catchEventMessages(c *cli.Context) {
	conn, err := amqp.Dial("amqp://hoges:hoge@dev-hoge.com/") //(B)
	if err != nil {
		fmt.Println(err)
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		fmt.Println(err)
	}
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"rabbitmq_use_consumer_name", // name  (C)
		true,              // durable       (D)
		false,             // delete when usused
		false,             // exclusive
		false,             // noWait
		nil,               // arguments
	)
	if err != nil {
		fmt.Println(err)
	}

	msgs, err := ch.Consume(
		q.Name, // queue
		"",     // consumer
		false,  // auto-ack  (E)
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(msgs)
}

ポイントは(A)は、コマンド起動させる際にmain.go の後に名前をつけて起動させる必要があるため、その名称を書いておく必要があります。

$ go run main.go rabbitmq

(B)は、MQのURLとなります。
(C)は、ConsumersのNameです
(D)(E)は、RabbitMQが何らかの不具合で再起動させた際にメッセージを消失しないようにするための設定です。(E)auto-ackをfalseに設定しておくと、MQ側のメッセージは消えずに残ります。
処理が完了したら、MQ側のメッセージを消す必要がありますのでその際は下記にて完了となります。

d.Ack(false)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?