add Elixir source for tutorial 2

This commit is contained in:
Jeff Weiss 2015-12-12 22:32:31 -08:00
parent 9f0db0be04
commit aa207592b2
No known key found for this signature in database
GPG Key ID: 863E21C5E735FBB2
2 changed files with 43 additions and 0 deletions

15
elixir/new_task.exs Normal file
View File

@ -0,0 +1,15 @@
{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)
AMQP.Queue.declare(channel, "task_queue", durable: true)
message =
case System.argv do
[] -> "Hello World!"
words -> Enum.join(words, " ")
end
AMQP.Basic.publish(channel, "", "hello", message, persistent: true)
IO.puts " [x] Sent '#{message}'"
AMQP.Connection.close(connection)

28
elixir/worker.exs Normal file
View File

@ -0,0 +1,28 @@
defmodule Worker do
def wait_for_messages(channel) do
receive do
{:basic_deliver, payload, meta} ->
IO.puts " [x] Received #{payload}"
payload
|> to_char_list
|> Enum.count(fn x -> x == ?. end)
|> Kernel.*(1000)
|> :timer.sleep
IO.puts " [x] Done."
AMQP.Basic.ack(channel, meta.delivery_tag)
wait_for_messages(channel)
end
end
end
{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)
AMQP.Queue.declare(channel, "task_queue", durable: true)
AMQP.Basic.qos(channel, prefetch_count: 1)
AMQP.Basic.consume(channel, "hello")
IO.puts " [*] Waiting for messages. To exit press CTRL+C, CTRL+C"
Worker.wait_for_messages(channel)