Advertisement
Guest User

Untitled

a guest
Apr 5th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. defmodule MT.Client do
  2. require Logger
  3.  
  4. @host Application.get_env(:mt, :host)
  5. @username Application.get_env(:mt, :username)
  6. @password Application.get_env(:mt, :password)
  7. @channel Application.get_env(:mt, :channel)
  8.  
  9. def start_link do
  10. MT.Client.connect
  11. end
  12.  
  13. def connect do
  14. {:ok, connection} = AMQP.Connection.open(host: @host, username: @username, password: @password)
  15. {:ok, channel} = AMQP.Channel.open(connection)
  16.  
  17. AMQP.Queue.declare(channel, @channel, durable: true)
  18. AMQP.Basic.qos(channel, prefetch_count: 1)
  19.  
  20. AMQP.Basic.consume(channel, @channel)
  21.  
  22. Logger.info "[*] Waiting for messages"
  23.  
  24. MT.Client.loop(channel)
  25. end
  26.  
  27. def loop(channel) do
  28. receive do
  29. {:basic_deliver, payload, meta} ->
  30. Logger.info "[x] Received #{payload}"
  31. payload
  32. |> to_char_list
  33. |> Enum.count(fn x -> x == ?. end)
  34. |> Kernel.*(1000)
  35. |> :timer.sleep
  36. Logger.info "[x] Done."
  37. AMQP.Basic.ack(channel, meta.delivery_tag)
  38.  
  39. MT.Client.loop(channel)
  40. end
  41. end
  42. end
  43.  
  44. defmodule MT.Client.Supervisor do
  45. use Supervisor
  46. require Logger
  47.  
  48. @name MTClientSupervisor
  49.  
  50. def start_link do
  51. Supervisor.start_link(__MODULE__, :ok, name: @name)
  52. end
  53.  
  54. def init(:ok) do
  55. children = [
  56. worker(MT.Client, [], restart: :transient, id: "MTClient01"),
  57. worker(MT.Client, [], restart: :transient, id: "MTClient02"),
  58. worker(MT.Client, [], restart: :transient, id: "MTClient03")
  59. ]
  60. supervise(children, strategy: :one_for_one)
  61. end
  62. end
  63.  
  64. iex -S mix
  65. MT.Client.Supervisor.start_link`
  66.  
  67. 08:46:50.746 [info] [*] Waiting for messages
  68. 08:46:50.746 [info] [x] Received {"job":"TestMessage","data":{"message":"message........"}}
  69. 08:46:58.747 [info] [x] Done.
  70. 08:46:58.748 [info] [x] Received {"job":"TestMessage","data":{"message":"last........"}}
  71. 08:47:06.749 [info] [x] Done.
  72.  
  73. MT.Client.start_link
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement