/
consumer.ex
50 lines (45 loc) · 1.43 KB
/
consumer.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
defmodule TaskBunny.Consumer do
# Handles consumer concerns.
#
# This module is private to TaskBunny and should not be accessed directly.
#
@moduledoc false
require Logger
@doc """
Opens a channel and start consuming messages for the queue.
"""
@spec consume(AMQP.Connection.t, String.t, integer) ::
{:ok, AMQP.Channel.t, String.t} | {:error, any}
def consume(connection, queue, concurrency) do
with {:ok, channel} <- AMQP.Channel.open(connection),
:ok <- AMQP.Basic.qos(channel, prefetch_count: concurrency),
{:ok, consumer_tag} <- AMQP.Basic.consume(channel, queue)
do
{:ok, channel, consumer_tag}
else
error ->
Logger.warn """
TaskBunny.Consumer: start consumer for #{queue}.
Detail: #{inspect error}"
"""
{:error, error}
end
end
@doc """
Cancel the consumer to stop receiving messages.
"""
@spec cancel(AMQP.Channel.t, String.t) :: {:ok, String.t}
def cancel(channel, consumer_tag) do
AMQP.Basic.cancel(channel, consumer_tag)
end
@doc """
Acknowledges to the message.
"""
@spec ack(AMQP.Channel.t, map, boolean) :: :ok
def ack(channel, meta, succeeded)
def ack(channel, %{delivery_tag: tag}, true), do: AMQP.Basic.ack(channel, tag)
def ack(channel, %{delivery_tag: tag}, false) do
# You have to set false to requeue option to be dead lettered
AMQP.Basic.nack(channel, tag, requeue: false)
end
end