### JSON Codec Setup Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Shows how to configure the client to automatically use JSON for message encoding and decoding. ```APIDOC ## JSON Codec Setup Example ### Description This example configures the `AMQP::Client` to use JSON as the default content type, enabling automatic serialization and deserialization of message bodies. ### Code ```ruby AMQP::Client.configure do |config| config.enable_builtin_codecs config.default_content_type = "application/json" end amqp = AMQP::Client.new("amqp://localhost").start # Now all publishes use JSON automatically amqp.publish({ key: "value" }, exchange: "ex") ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Installs project dependencies locally using 'bin/setup'. ```bash bin/setup ``` -------------------------------- ### Run Bundle Install Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Execute 'bundle install' after adding the gem to your Gemfile to install all project dependencies. ```bash bundle install ``` -------------------------------- ### Install amqp-client Gem Manually Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Install the amqp-client gem directly using the 'gem install' command. ```bash gem install amqp-client ``` -------------------------------- ### RPC Server and Client Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Demonstrates how to set up an RPC server to handle requests and an RPC client to make calls. ```APIDOC ## RPC Server and Client Example ### Description This example illustrates the implementation of a simple RPC pattern, showing how to define an RPC server that responds to calls and an RPC client that invokes these server methods. ### Code ```ruby # Server amqp.rpc_server("add") do |args| { result: args[:a] + args[:b] } end # Client result = amqp.rpc_call("add", { a: 5, b: 3 }) puts result[:result] # => 8 ``` ``` -------------------------------- ### Basic Publish Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Demonstrates how to establish a connection, declare a queue, publish a message, and close the connection using the high-level API. ```ruby require "amqp-client" amqp = AMQP::Client.new("amqp://localhost").start q = amqp.queue("orders") q.publish({ id: 123, amount: 45.99 }) amqp.stop ``` -------------------------------- ### Check if Client is Started Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/RELEASE_NOTES_v2.0.0.md Use `Client#started?` to check if the AMQP client has been started and is ready to process messages. ```ruby # Client#started? # Check if client is started ``` -------------------------------- ### Start AMQP Client with Supervision Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Opens an AMQP connection and starts automatic supervision and reconnection. This method is idempotent and returns immediately if the client is already started. It raises `Error::ConnectionClosed` if the initial connection fails. ```ruby amqp = AMQP::Client.new("amqp://localhost").start q = amqp.queue("myqueue") ``` -------------------------------- ### RPC Server and Client Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Illustrates setting up an RPC server to handle a specific method ('add') and then using an RPC client to call that method and retrieve the result. ```ruby # Server amqp.rpc_server("add") do |args| { result: args[:a] + args[:b] } end # Client result = amqp.rpc_call("add", { a: 5, b: 3 }) puts result[:result] # => 8 ``` -------------------------------- ### Install Gem Locally Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Builds and installs the gem onto the local machine using 'bundle exec rake install'. ```bash bundle exec rake install ``` -------------------------------- ### RPCClient#start Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Starts listening for RPC responses on the special RabbitMQ direct reply-to queue. This method must be called before making any RPC calls and is idempotent. ```APIDOC ## RPCClient#start Starts listening for RPC responses on the special RabbitMQ direct reply-to queue (`amq.rabbitmq.reply-to`). This must be called before making any RPC calls. The method is idempotent. ### Method Signature ```ruby def start → self ``` ### Returns self (allows chaining) ### Raises: - `Error::ChannelClosed` — if channel is closed ### Example ```ruby rpc = AMQP::Client::RPCClient.new(ch).start # Now ready to make calls result = rpc.call("my_method", { arg1: "value" }) ``` ``` -------------------------------- ### Low-Level API Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Demonstrates basic message publishing and retrieval using the low-level AMQP client API. Requires manual connection and channel management. ```ruby conn = AMQP::Client.new("amqp://localhost").connect Thread.new { conn.read_loop } ch = conn.channel ch.queue_declare("myqueue") ch.basic_publish("message", exchange: "", routing_key: "myqueue") msg = ch.basic_get("myqueue") puts msg.body ch.basic_ack(msg.delivery_tag) ``` -------------------------------- ### Basic Subscribe Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Shows how to subscribe to a queue, automatically decode JSON messages, process them, and handle errors by rejecting and requeuing messages. ```ruby amqp.subscribe("orders") do |msg| order = msg.parse # Auto-decode JSON process_order(order) # Auto-acked on success rescue => e msg.reject(requeue: true) # Retry on error raise end ``` -------------------------------- ### Start Interactive Console Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Opens an interactive Ruby console for experimenting with the gem. ```bash bin/console ``` -------------------------------- ### Direct Exchange Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/exchange.md Demonstrates the creation of a direct exchange. Messages are routed to queues with an exact matching binding key. ```ruby ex = amqp.direct_exchange("orders") # Queue binds with binding_key "orders.created" # Message published with routing_key "orders.created" matches # Message published with routing_key "orders" does not match ``` -------------------------------- ### Start RPC Server Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Starts an RPC server that listens on a specified queue for requests. The provided block handles incoming requests and returns a response. Configure worker threads, durability, and auto-deletion behavior. ```ruby amqp.rpc_server("calculate") do |args| { result: args[:a] + args[:b] } end ``` -------------------------------- ### Basic Publish Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Demonstrates a common pattern for publishing messages using the high-level API. ```APIDOC ## Basic Publish Example ### Description This example shows how to establish a connection, declare a queue, and publish a message using the `AMQP::Client`. ### Code ```ruby require "amqp-client" amqp = AMQP::Client.new("amqp://localhost").start q = amqp.queue("orders") q.publish({ id: 123, amount: 45.99 }) amqp.stop ``` ``` -------------------------------- ### Class-Level Configuration: Basic Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/configuration.md Configures default settings for all AMQP::Client instances, such as enabling built-in codecs and setting default content types. Instances created after configuration will inherit these settings. ```ruby AMQP::Client.configure do |config| # Configure codec support config.enable_builtin_codecs # Set defaults config.default_content_type = "application/json" config.strict_coding = false end # All instances inherit these settings client = AMQP::Client.new("amqp://localhost").start client.publish({ id: 1 }) # Automatically JSON-encoded ``` -------------------------------- ### Example Connection URIs Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/configuration.md Demonstrates various formats for AMQP connection URIs, including local and remote connections with credentials, and specifying a client instance name. ```ruby # Local guest connection "amqp://localhost" "amqp://guest:guest@localhost//" # Remote broker with credentials "amqps://user:pass@broker.example.com/vhost" # Named instance for logging "amqp://localhost?name=worker-1" ``` -------------------------------- ### Initialize AMQP Client Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Creates a new client instance without establishing a connection. Use `connect` or `start` to establish connectivity. Supports various options for connection configuration. ```ruby require "amqp-client" # Simple connection client = AMQP::Client.new("amqp://localhost") # With TLS and custom options client = AMQP::Client.new( "amqps://user:pass@broker.example.com/vhost", verify_peer: false, heartbeat: 30, logger: Logger.new($stdout) ) ``` -------------------------------- ### Single RPC Call Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Demonstrates making a single RPC call using the high-level `amqp.rpc_call` method, suitable for infrequent calls. ```ruby result = amqp.rpc_call("add", { a: 2, b: 3 }) ``` -------------------------------- ### Create and Use Connection Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md Demonstrates creating a new connection, opening a channel, declaring a queue, and starting the read loop. The read loop must be run in a thread for the connection to process incoming data. ```ruby conn = AMQP::Client::Connection.new("amqp://localhost") ch = conn.channel ch.queue_declare("my.queue") conn.read_loop # Must run in a thread ``` -------------------------------- ### Basic Subscribe Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Illustrates the common pattern for subscribing to messages and handling them, including error handling and acknowledgments. ```APIDOC ## Basic Subscribe Example ### Description This example demonstrates how to subscribe to a queue, process incoming messages, and handle potential errors by rejecting and requeuing them. ### Code ```ruby amqp.subscribe("orders") do |msg| order = msg.parse # Auto-decode JSON process_order(order) # Auto-acked on success rescue => e msg.reject(requeue: true) # Retry on error raise end ``` ``` -------------------------------- ### Multi-Channel Access and Management Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md This example illustrates how to open and manage multiple independent channels on a single AMQP connection. It shows both auto-assigned and explicitly assigned channel IDs. ```ruby conn = Connection.new("amqp://localhost") Thread.new { conn.read_loop } ch1 = conn.channel # Auto-assigned channel 1 ch2 = conn.channel # Auto-assigned channel 2 ch5 = conn.channel(5) # Explicit channel ID # Use channels independently ch1.queue_declare("queue1") ch2.queue_declare("queue2") # Close channels ch1.close ch2.close # Close connection conn.close ``` -------------------------------- ### AMQP::Client#start Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Opens an AMQP connection and initiates automatic supervision and reconnection. This method is idempotent, meaning calling it multiple times has the same effect as calling it once. It returns immediately if the client is already started. ```APIDOC ## AMQP::Client#start ### Description Opens an AMQP connection and starts automatic supervision and reconnection. Idempotent; returns immediately if already started. ### Method `start → self` ### Returns: self ### Raises: * `Error::ConnectionClosed` — if initial connection fails ### Request Example ```ruby amqp = AMQP::Client.new("amqp://localhost").start q = amqp.queue("myqueue") ``` ``` -------------------------------- ### Install amqp-client Gem using Bundler Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Add the amqp-client gem to your application's Gemfile to manage its dependencies. ```ruby gem 'amqp-client' ``` -------------------------------- ### Start RPCClient Listener Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Starts listening for RPC responses on the RabbitMQ direct reply-to queue. This method must be called before making any RPC calls and is idempotent. ```ruby rpc = AMQP::Client::RPCClient.new(ch).start # Now ready to make calls result = rpc.call("my_method", { arg1: "value" }) ``` -------------------------------- ### Start Consuming Messages with Basic Consume Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/channel.md Starts consuming messages from a specified queue. It supports multi-threading for message processing and can execute a callback when the consumer is canceled by the broker. Use this for continuous message processing. ```ruby def basic_consume(queue, tag: "", no_ack: true, exclusive: false, no_wait: false, arguments: {}, worker_threads: 1, on_cancel: nil, &blk) end ``` ```ruby ch.basic_consume("myqueue", worker_threads: 2) do |msg| puts msg.body ch.basic_ack(msg.delivery_tag) end ``` -------------------------------- ### Example: Declare Topic Exchange Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Demonstrates how to declare a topic exchange named 'events'. ```ruby topic_ex = amqp.topic_exchange("events") ``` -------------------------------- ### AMQP::Client Initialization Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Creates a new AMQP::Client instance. This constructor does not establish a connection; use `connect` or `start` for that. It accepts a connection URI and various options to configure the client's behavior, such as TLS verification, heartbeat settings, and logger. ```APIDOC ## AMQP::Client.new ### Description Creates a new client instance without establishing a connection. Use `connect` or `start` to establish connectivity. ### Method `AMQP::Client.new(uri = "", **options)` ### Parameters #### Path Parameters * **uri** (String) - Optional - Connection URL: `amqp://username:password@hostname/vhost` or `amqps://` for TLS #### Query Parameters * **connection_name** (String) - Optional - Name to identify the client from the broker * **verify_peer** (Boolean) - Optional - Verify broker's TLS certificate; set false for self-signed certs * **heartbeat** (Integer) - Optional - Heartbeat timeout in seconds; 0 means TCP keepalive * **frame_max** (Integer) - Optional - Maximum frame size; negotiated downward with broker * **channel_max** (Integer) - Optional - Maximum channels allowed; max is 65,536 * **logger** (Logger, nil) - Optional - Logger for lifecycle events (connected/disconnected/reconnect errors) * **connect_timeout** (Float) - Optional - TCP connection timeout in seconds * **keepalive** (String) - Optional - TCP keepalive setting: idle:interval:probes * **reconnect_interval** (Integer) - Optional - Seconds to wait before reconnection attempt ### Returns AMQP::Client instance ### Request Example ```ruby require "amqp-client" # Simple connection client = AMQP::Client.new("amqp://localhost") # With TLS and custom options client = AMQP::Client.new( "amqps://user:pass@broker.example.com/vhost", verify_peer: false, heartbeat: 30, logger: Logger.new($stdout) ) ``` ``` -------------------------------- ### Fanout Exchange Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/exchange.md Shows how to create a fanout exchange for broadcasting messages. All messages sent to this exchange are delivered to all bound queues, regardless of the routing key. ```ruby ex = amqp.fanout_exchange("broadcast") # All messages go to all bound queues ex.publish("alert") # routing_key is ignored ``` -------------------------------- ### Connect to Local RabbitMQ Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Establishes a connection to a local RabbitMQ instance using the AMQP client. This is a common starting point for development and testing. ```ruby AMQP::Client.new("amqp://localhost") ``` -------------------------------- ### rpc_server Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Starts an RPC server that listens on a specified queue for requests. The provided block handles incoming requests and returns responses. ```APIDOC ## rpc_server ### Description Starts an RPC server listening on a queue. Block receives request body and must return response body. ### Method POST (conceptual) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters - **worker_threads** (Integer) - Optional - Threads handling requests - **durable** (Boolean) - Optional - Queue persists across restarts - **auto_delete** (Boolean) - Optional - Queue deleted when last consumer stops #### Request Body - **method** (String, Symbol) - Required - RPC method name (queue name) - **arguments** (Hash) - Optional - Custom queue arguments ### Request Example ```ruby amqp.rpc_server("calculate", worker_threads: 2, durable: false) do |args| { result: args[:a] + args[:b] } end ``` ### Response #### Success Response (200) - **Consumer** - An object representing the RPC consumer. #### Response Example ```json { "consumer_tag": "some_tag" } ``` ``` -------------------------------- ### Low-Level AMQP Client API Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Demonstrates basic AMQP operations including connection, channel opening, queue declaration, message publishing, and message retrieval using the low-level API. This API closely matches the AMQP protocol but does not handle automatic reconnects. ```ruby require "amqp-client" # Opens and establishes a connection conn = AMQP::Client.new("amqp://guest:guest@localhost").connect # Open a channel ch = conn.channel # Create a temporary queue q = ch.queue_declare # Publish a message to said queue ch.basic_publish_confirm "Hello World!", exchange: "", routing_key: q.queue_name, persistent: true # Poll the queue for a message msg = ch.basic_get(q.queue_name) # Print the message's body to STDOUT puts msg.body ``` -------------------------------- ### JSON Codec Setup and Usage Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Configures the client to use JSON for message encoding and decoding by default, then demonstrates publishing a message that will be automatically serialized to JSON. ```ruby AMQP::Client.configure do |config| config.enable_builtin_codecs config.default_content_type = "application/json" end amqp = AMQP::Client.new("amqp://localhost").start # Now all publishes use JSON automatically amqp.publish({ key: "value" }, exchange: "ex") ``` -------------------------------- ### Topic Exchange Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/exchange.md Illustrates a topic exchange, which uses wildcard patterns (`*` for one word, `#` for zero or more) for routing. Useful for flexible event-driven systems. ```ruby ex = amqp.topic_exchange("events") # Binding: "order.*" matches: "order.created", "order.updated" # Binding: "order.#" matches: "order.created", "order.items.updated" # Binding: "#" matches: everything ``` -------------------------------- ### Example: Publish Compressed Message Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Publishes a large data string to the 'data' exchange, specifying 'gzip' as the content encoding for compression. ```ruby # Publish with compression amqp.publish("large data", exchange: "data", content_encoding: "gzip" ) ``` -------------------------------- ### Declare Queue with Basic Options Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/configuration.md Declares a queue with standard options like durability, auto-deletion, exclusivity, and passivity. Use this for basic queue setup. ```ruby q = amqp.queue("orders", durable: true, # Survives broker restart auto_delete: false, # Not deleted when consumers stop exclusive: false, # Multiple consumers allowed passive: false, # Create if doesn't exist arguments: {} ) ``` -------------------------------- ### Example: Wait for Multiple Confirms Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Demonstrates publishing two messages using `publish_and_forget` and then waiting for their confirmations using `wait_for_confirms`. The `all_confirmed` variable will indicate if both messages were successfully processed by the broker. ```ruby amqp.publish_and_forget(body1, exchange: "ex", routing_key: "key1") amqp.publish_and_forget(body2, exchange: "ex", routing_key: "key2") all_confirmed = amqp.wait_for_confirms # blocks until both are confirmed/nacked ``` -------------------------------- ### Example: Publish Fire-and-Forget Message Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Publishes a simple string message to the 'logs' exchange with the 'info' routing key without waiting for confirmation. ```ruby amqp.publish_and_forget("event", exchange: "logs", routing_key: "info") ``` -------------------------------- ### Cancel a Consumer Subscription Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/consumer.md Demonstrates how to start a consumer, process messages for a period, and then cancel the subscription. The cancel method is idempotent and can be called multiple times safely. ```ruby consumer = amqp.subscribe("myqueue") do |msg| puts msg.body end sleep 10 consumer.cancel puts "Consumer stopped" consumer.cancel ``` -------------------------------- ### Headers Exchange Example Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/exchange.md Demonstrates a headers exchange, which routes messages based on header content rather than routing keys. Use when message routing depends on custom metadata. ```ruby ex = amqp.headers_exchange("typed") ex.publish("data", headers: { type: "order", priority: "high" }) # Queues bind with header matching arguments ``` -------------------------------- ### AMQP::Client#started? Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Checks the connection status of the AMQP client. Returns true if the client is currently connected or in the process of attempting to connect or reconnect. ```APIDOC ## AMQP::Client#started? ### Description Checks if the client is connected or attempting to connect. ### Method `started? → Boolean` ### Returns: true if connection is active or reconnecting; false otherwise ``` -------------------------------- ### Configuring TCP Keepalive Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md This example shows how to configure TCP keepalive settings for a connection to help detect dead connections. The format specifies idle time, probe interval, and retry count. ```ruby conn = Connection.new("amqp://localhost", keepalive: "60:10:3" # Idle 60s, probe every 10s, 3 times ) ``` -------------------------------- ### Check Consumer Status Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/consumer.md Shows how to check if a consumer is active or has been closed. If the consumer is not closed, it proceeds to cancel it. The example verifies that the consumer is indeed closed after cancellation. ```ruby consumer = amqp.subscribe("queue") { |msg| process(msg) } unless consumer.closed? puts "Consumer is active" consumer.cancel end if consumer.closed? puts "Consumer is now closed" ``` -------------------------------- ### Handle Publish Errors Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/errors.md Provides an example of how to handle potential errors during message publishing, including cases where the broker rejects the message, content type is unsupported, or the channel is closed. ```ruby require "amqp-client" amqp = AMQP::Client.new("amqp://localhost").start begin amqp.publish( { id: 1, data: "test" }, exchange: "orders", routing_key: "order.created", content_type: "application/json" ) rescue AMQP::Client::Error::PublishNotConfirmed puts "Broker rejected message" rescue AMQP::Client::Error::UnsupportedContentType => e puts "Content type not supported: #{e.message}" rescue AMQP::Client::Error::ChannelClosed => e puts "Channel closed: #{e.message}" end ``` -------------------------------- ### Example: Subscribe and Process Messages Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Subscribes to the 'orders' queue. For each received message, it attempts to parse the body as JSON and prints it. If parsing or processing fails, the message is rejected and requeued. The consumer can be explicitly cancelled later. ```ruby consumer = amqp.subscribe("orders") do |msg| order = msg.parse # Parse based on content_type puts "Processing order: #{order}" msg.ack # Auto-ack on success rescue => e puts "Error: #{e.message}" msg.reject(requeue: true) # Requeue on failure end # Later, cancel the consumer consumer.cancel ``` -------------------------------- ### Automatic Consumer Re-establishment on Reconnection Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/consumer.md This example highlights how consumers are automatically re-established by the client after a connection drop and subsequent reconnection. The consumer remains active with the same queue and settings, though the consumer tag might change. ```ruby amqp = AMQP::Client.new("amqp://localhost").start consumer = amqp.subscribe("queue") { |msg| process(msg) } # If connection drops and reconnects, the consumer # is automatically re-created and continues processing ``` -------------------------------- ### Example: Publish JSON Message Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Publishes a JSON payload to the 'events' exchange with the 'order.created' routing key. The message body is automatically encoded based on the content type. ```ruby # Publish JSON with automatic encoding amqp.publish({ order_id: 123, amount: 45.99 }, exchange: "events", routing_key: "order.created", content_type: "application/json" ) ``` -------------------------------- ### RPC Error Handling with Timeout and AMQP Errors Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Provides an example of robust error handling for RPC calls, catching `Timeout::Error` for non-responsive servers and general `AMQP::Client::Error` for other issues. ```ruby rpc = amqp.rpc_client begin response = rpc.call("method", "arg", timeout: 10) # Process response rescue Timeout::Error puts "RPC server did not respond within 10 seconds" rescue AMQP::Client::Error => e puts "RPC call failed: #{e.message}" finally rpc.close end ``` -------------------------------- ### Run Read Loop in a Separate Thread Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md Manually starts the read loop in a separate thread, which is necessary for the connection to process incoming AMQP frames. This is an alternative to using the `read_loop_thread: true` option during initialization. ```ruby conn = AMQP::Client::Connection.new("amqp://localhost", read_loop_thread: false) Thread.new { conn.read_loop } ch = conn.channel ch.queue_declare("my.queue") ``` -------------------------------- ### Create and Use RPC Client Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Demonstrates how to create a reusable RPC client instance and make calls to remote methods. Ensure the AMQP connection is established before initializing the client. ```ruby class MyRPCClient def initialize(amqp) @rpc = amqp.rpc_client end def call_method(name, args, timeout: 10) @rpc.call(name, args, timeout: timeout) end def shutdown @rpc.close end end ``` -------------------------------- ### get Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/queue.md Polls the queue once for a message. Returns the message if available, otherwise returns nil. ```APIDOC ## get ### Description Polls the queue once for a message. Returns the message if available, otherwise returns nil. ### Method `def get(no_ack: false) → Message | nil` ### Parameters #### General - **no_ack** (Boolean) - Optional - Default: false - Auto-ack on retrieval ### Returns [Message](#message) or nil if empty ### Example ```ruby msg = q.get(no_ack: true) puts msg.body if msg ``` ``` -------------------------------- ### Prepare for Release (Patch Version) Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Automates the release preparation process by running tests, bumping the patch version, updating the changelog, and creating a git commit and tag. ```bash rake release:prepare ``` -------------------------------- ### Connection Initialization Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md Establishes a connection to an AMQP broker with various configuration options. ```APIDOC ## Connection.new ### Description Establishes a connection to an AMQP broker. ### Method Constructor ### Parameters #### Path Parameters - **uri** (String) - Optional - Connection URL: amqp://user:pass@host/vhost or amqps:// for TLS - **read_loop_thread** (Boolean) - Optional - If true, read_loop runs in background thread - **codec_registry** (MessageCodecRegistry) - Optional - Codec registry for message encoding/decoding - **strict_coding** (Boolean) - Optional - If true, raise on unknown codecs - **name** (String, nil) - Optional - Instance name for thread and log identification - **connection_name** (String) - Optional - Name for broker identification - **verify_peer** (Boolean) - Optional - Verify TLS certificate - **connect_timeout** (Float) - Optional - TCP connection timeout - **heartbeat** (Integer) - Optional - Heartbeat interval in seconds - **frame_max** (Integer) - Optional - Maximum frame size - **channel_max** (Integer) - Optional - Maximum channels - **keepalive** (String) - Optional - TCP keepalive: idle:interval:probes ### Response #### Success Response - **Connection instance** #### Error Handling - `Error::ConnectionClosed` — if connection fails ``` -------------------------------- ### Initialize AMQP Connection Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md Establishes a connection to an AMQP broker. Use this to create a new connection instance, specifying connection parameters like the URI and threading behavior. ```ruby Connection.new(uri = "", read_loop_thread: true, codec_registry: nil, strict_coding: false, name: nil, **options) ``` -------------------------------- ### Unified Configuration API Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/MIGRATION_GUIDE_v2.md Use the `AMQP::Client.configure` block for a unified way to set up client options, including built-in codecs, default content types, and custom parsers. ```ruby AMQP::Client.configure do |config| config.enable_builtin_codecs config.default_content_type = "application/json" config.default_content_encoding = "gzip" config.strict_coding = true # Can also register custom parsers/coders config.register_parser(content_type: "application/msgpack", parser: MsgPackParser) end ``` -------------------------------- ### configure Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Sets class-level defaults for all new client instances. This allows for global configuration of client behavior. ```APIDOC ## configure ### Description Sets class-level defaults for all new client instances. ### Method Signature `self.configure { |config| ... } -> Configuration` ### Block Parameter - **config** ([Configuration](#configuration)) - An object to configure client defaults. ### Returns [Configuration](#configuration) - The configuration object. ### Example ```ruby AMQP::Client.configure do |config| config.default_content_type = "application/json" config.strict_coding = true config.enable_builtin_codecs end ``` ``` -------------------------------- ### Unified Configuration Block Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/RELEASE_NOTES_v2.0.0.md Configure all client settings in one place using the `AMQP::Client.configure` block. This replaces older configuration methods. ```ruby AMQP::Client.configure do |config| config.enable_builtin_codecs # JSON, gzip, deflate config.default_content_type = "application/json" config.default_content_encoding = "gzip" config.strict_coding = true # Register custom codecs config.register_parser(content_type: "application/msgpack", parser: MsgPackParser) end ``` -------------------------------- ### Prepare for Release (Minor Version Bump) Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Use this command to increment the minor version of the gem (e.g., 1.2.0 to 1.3.0) and prepare for release. ```bash rake release:prepare[minor] ``` -------------------------------- ### Handling Broker-Blocked Connections Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md This snippet demonstrates how to set up callbacks to handle scenarios where the broker blocks publishes due to resource constraints. It includes actions for both blocked and unblocked states. ```ruby conn = Connection.new("amqp://localhost") Thread.new { conn.read_loop } conn.on_blocked do |reason| puts "Broker blocked: #{reason}" # Stop publishing or reduce rate end conn.on_unblocked do puts "Broker unblocked, can publish again" # Resume publishing end ``` -------------------------------- ### basic_consume Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/channel.md Starts consuming messages from a queue. It supports various options for controlling message acknowledgment, exclusivity, and thread management. A block can be provided to process received messages. ```APIDOC ## basic_consume ### Description Starts consuming messages from a queue. It supports various options for controlling message acknowledgment, exclusivity, and thread management. A block can be provided to process received messages. ### Method Ruby Method ### Signature def basic_consume(queue, tag: "", no_ack: true, exclusive: false, no_wait: false, arguments: {}, worker_threads: 1, on_cancel: nil, &blk) ### Parameters #### Arguments - **queue** (String) - Required - Queue name - **tag** (String) - Optional - Consumer tag; empty = broker auto-generates - **no_ack** (Boolean) - Optional - Auto-ack on delivery - **exclusive** (Boolean) - Optional - Only consumer allowed - **no_wait** (Boolean) - Optional - Don't wait for confirmation - **arguments** (Hash) - Optional - Custom arguments - **worker_threads** (Integer) - Optional - Threads processing messages; 0 = blocking - **on_cancel** (Proc) - Optional - Called if broker cancels consumer ### Block Yields [Message](#message) ### Returns ConsumeOk { channel_id, consumer_tag, worker_threads, msg_q, on_cancel }; nil if worker_threads == 0 ### Example ```ruby ch.basic_consume("myqueue", worker_threads: 2) do |msg| puts msg.body ch.basic_ack(msg.delivery_tag) end ``` ``` -------------------------------- ### Get Delivery Information Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/message.md The 'delivery_info' method returns a DeliveryInfo struct containing structured metadata about the message delivery, such as consumer tag, delivery tag, and routing details. ```ruby consumer = amqp.subscribe("q") do |msg| info = msg.delivery_info puts "Consumer: #{info.consumer_tag}" puts "Delivery: #{info.delivery_tag}" puts "Redelivered: #{info.redelivered}" puts "From: #{info.exchange}" puts "Route: #{info.routing_key}" end ``` -------------------------------- ### Concurrent Consumers on Different Queues Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/consumer.md Demonstrates setting up multiple consumers simultaneously, each subscribed to a different queue. These consumers operate concurrently, and individual consumers can be cancelled as needed. ```ruby consumer1 = amqp.subscribe("queue1") { |msg| process1(msg) } consumer2 = amqp.subscribe("queue2") { |msg| process2(msg) } consumer3 = amqp.subscribe("queue3") { |msg| process3(msg) } # All three run concurrently with default settings # Stop them individually when needed consumer1.cancel ``` -------------------------------- ### Initialize RPCClient Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Creates a new RPC client using an existing AMQP channel. The channel is typically obtained from an AMQP::Client connection. ```ruby RPCClient.new(channel) ``` ```ruby # Get channel from connection conn = AMQP::Client.new("amqp://localhost").connect Thread.new { conn.read_loop } ch = conn.channel rpc = AMQP::Client::RPCClient.new(ch).start # Or from high-level client amqp = AMQP::Client.new("amqp://localhost").start rpc = amqp.rpc_client ``` -------------------------------- ### Configuration Reference Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md API for configuring the AMQP::Client, including connection options, codec registration, and default settings. ```APIDOC ## Configuration Reference ### Description Provides methods for configuring the AMQP::Client's behavior, such as connection parameters, content handling, and error reporting. ### Class Methods - **`AMQP::Client.configure`**: Allows setting class-level configuration options via a block. ### Configuration Options - **Connection options**: `uri`, `heartbeat`, `verify_peer`, etc. - **Codec registration**: `register_parser` for custom content types, `register_coder` for custom encoding/decoding. - **Built-in codecs**: `enable_builtin_codecs` to activate JSON, gzip, and deflate codecs. - **Default properties**: Set default `content_type` and other message properties per instance or class. ``` -------------------------------- ### Establish Raw AMQP Connection Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Establishes a raw connection to the broker and returns immediately. The connection is ready for low-level channel operations. Does not automatically reconnect. If `read_loop_thread` is false, the caller must manage the read loop in a separate thread. ```ruby conn = AMQP::Client.new("amqp://localhost").connect ch = conn.channel ch.queue_declare("my.queue") ``` -------------------------------- ### Multiple RPC Calls with RPCClient Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Illustrates using RPCClient for a series of RPC calls, highlighting its efficiency for multiple requests compared to single calls. ```ruby rpc = amqp.rpc_client results = (1..100).map do |i| rpc.call("process", { id: i }) end rpc.close ``` -------------------------------- ### Get a message from the queue Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/queue.md Polls the queue once for a single message. Useful for simple request-response patterns or when you need to retrieve messages on demand. Set `no_ack: true` to auto-acknowledge the message upon retrieval. ```ruby msg = q.get(no_ack: true) puts msg.body if msg ``` -------------------------------- ### Prepare for Release (Major Version Bump) Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Use this command to increment the major version of the gem (e.g., 1.2.0 to 2.0.0) and prepare for release. ```bash rake release:prepare[major] ``` -------------------------------- ### Create a Reusable RPC Client Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Instantiate an `RPCClient` for efficient, multiple RPC calls. Remember to close the client when it's no longer needed to release resources. ```ruby rpc = amqp.rpc_client result1 = rpc.call("add", { a: 2, b: 3 }) result2 = rpc.call("mul", { a: 4, b: 5 }) rpc.close ``` -------------------------------- ### Manual Read Loop Thread Management Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/connection.md When `read_loop_thread` is set to false, you must manually manage the thread for the connection's read loop. This example shows how to create and manage this background thread. ```ruby conn = Connection.new("amqp://localhost", read_loop_thread: false) # Must run read_loop in background thread reader = Thread.new { conn.read_loop } # Now use the connection ch = conn.channel ch.queue_declare("myqueue") # Later, close everything conn.close reader.join # Wait for read loop to finish ``` -------------------------------- ### Error Handling with AMQP Client Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Illustrates how to handle common AMQP client errors such as connection failures, queue not found, and unsupported message content types. Uses begin-rescue blocks for robust error management. ```ruby begin amqp = AMQP::Client.new("amqp://localhost").start rescue AMQP::Client::Error::ConnectionClosed => e puts "Connection failed: #{e.message}" end begin q = amqp.queue("important", passive: true) rescue AMQP::Client::Error::NotFound puts "Queue doesn't exist" end amqp.subscribe("q") do |msg| msg.parse rescue AMQP::Client::Error::UnsupportedContentType => e msg.reject(requeue: false) rescue StandardError => e msg.reject(requeue: true) raise end ``` -------------------------------- ### Connect to CloudAMQP Instance Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/README.md Connects to a CloudAMQP instance using AMQP over TLS/SSL. Requires providing username, password, hostname, and virtual host. ```ruby AMQP::Client.new("amqps://user:pass@flamingo.rmq.cloudamqp.com/vhost") ``` -------------------------------- ### Decode Message Body Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/message.md Use the 'decode' method to get the raw decoded string of the message body, without parsing. This is useful for custom parsing logic, especially for encoded data like gzip. ```ruby consumer = amqp.subscribe("q") do |msg| # Manually handle gzip-encoded data if msg.properties.content_encoding == "gzip" raw = msg.decode # Further processing... end end ``` -------------------------------- ### Handle Queue Operations Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/errors.md Shows how to handle errors when performing queue operations, such as checking for an existing queue's passive status or accessing a queue without proper permissions. It includes examples for NotFound and AccessRefused errors. ```ruby begin q = amqp.queue("important_queue", passive: true) rescue AMQP::Client::Error::NotFound puts "Queue doesn't exist, creating it..." q = amqp.queue("important_queue", durable: true) rescue AMQP::Client::Error::AccessRefused puts "No permission to access queue" end ``` -------------------------------- ### RPC Calls with Codec Support Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Shows how to use RPCClient when the high-level AMQP client has built-in codecs enabled, which automatically serializes arguments to JSON. ```ruby AMQP::Client.configure { |c| c.enable_builtin_codecs } amqp = AMQP::Client.new("amqp://localhost").start rpc = amqp.rpc_client # Arguments are auto-serialized to JSON response = rpc.call("add", { a: 5, b: 3 }) # Response body is returned as-is (string) ``` -------------------------------- ### Configure Built-in Codecs and Defaults Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Set class-level defaults for content type and encoding, and enable built-in codecs for automatic handling of JSON, gzip, and deflate. ```ruby AMQP::Client.configure do |config| config.enable_builtin_codecs # Enable automatic JSON, gzip, and deflate handling config.default_content_type = "application/json" config.default_content_encoding = "gzip" config.strict_coding = true # Raise errors on unknown codecs end ``` -------------------------------- ### High-Level API Usage Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Demonstrates connecting to a broker, declaring queues and exchanges, subscribing to messages with automatic acknowledgment, and publishing messages with automatic serialization and encoding. ```ruby require "amqp-client" # Configure built-in codecs for automatic JSON, gzip, and deflate handling AMQP::Client.configure do |config| config.enable_builtin_codecs end # Start the client, it will connect and once connected it will reconnect if that connection is lost # Operation pending when the connection is lost will raise an exception (not timeout) amqp = AMQP::Client.new("amqp://localhost").start # Declares a durable queue myqueue = amqp.queue("myqueue") # Declares a topic exchange ex = amqp.topic_exchange("myexchange") # Bind the queue to any exchange, with any binding key myqueue.bind(ex, binding_key: "my.events.*") # The message will be reprocessed if the client loses connection to the broker # between message arrival and when the message was supposed to be ack'ed. myqueue.subscribe(prefetch: 20) do |msg| puts msg.parse # Parses msg.body based on content_type and content_encoding rescue => e puts e.full_message end # The message is automatically ack'd by Queue#subscribe if the block returns successfully # If the block raises the message is rejected and requeued. # You still can control the acking and rejecting in the block if you want to, e.g: myqueue.subscribe do |msg| msg.ack rescue => e msg.reject end # Publish directly to the queue, message will be serialized to json automatically myqueue.publish({ foo: "bar" }, content_type: "application/json") # Publish to any exchange ex.publish("my message", routing_key: "topic.foo", headers: { foo: "bar" }) # Message will be gzip encoded automatically amqp.publish("an event", exchange: "amq.topic", routing_key: "my.event", content_encoding: "gzip") ``` -------------------------------- ### RPCClient Initialization Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/rpc-client.md Creates a new RPC client using an existing AMQP channel. This client is designed for making multiple RPC calls efficiently. ```APIDOC ## RPCClient Initialization Creates a new RPC client using an existing channel. ### Constructor ```ruby RPCClient.new(channel) ``` ### Parameters #### Path Parameters - **channel** (Connection::Channel) - Required - Channel to use for RPC calls (usually `conn.channel` or `client.with_connection { |c| c.channel }`) ### Returns RPCClient instance ### Example ```ruby # Get channel from connection conn = AMQP.Client.new("amqp://localhost").connect Thread.new { conn.read_loop } ch = conn.channel rpc = AMQP::Client::RPCClient.new(ch).start # Or from high-level client amqp = AMQP::Client.new("amqp://localhost").start rpc = amqp.rpc_client ``` ``` -------------------------------- ### AMQP::Client#connect Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/client.md Establishes a raw connection to the AMQP broker. This method returns immediately, and the connection is ready for low-level channel operations. It does not automatically handle reconnections. ```APIDOC ## AMQP::Client#connect ### Description Establishes a raw connection to the broker. Returns immediately; the connection is ready for low-level channel operations. Does not automatically reconnect. ### Method `connect(read_loop_thread: true) → Connection` ### Parameters #### Path Parameters * **read_loop_thread** (Boolean) - Optional - If false, the caller must call `connection.read_loop` in a thread ### Returns [Connection](#connection) ### Request Example ```ruby conn = AMQP::Client.new("amqp://localhost").connect ch = conn.channel ch.queue_declare("my.queue") ``` ``` -------------------------------- ### Handle Connection Errors Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/errors.md Demonstrates how to gracefully handle connection-related errors when establishing a connection to the AMQP broker. This includes catching specific connection closed errors and general AMQP errors. ```ruby begin amqp = AMQP::Client.new("amqp://localhost").start rescue AMQP::Client::Error::ConnectionClosed => e puts "Could not connect: #{e.message}" puts "Code: #{e.message.match(/\((\d+)\)/)[1]}" rescue AMQP::Client::Error => e puts "AMQP error: #{e.message}" end ``` -------------------------------- ### Configure Lifecycle Logging and Thread Names Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Identify a client instance in connection URLs using '?name=' to include the identifier in lifecycle log lines and spawned thread names. ```ruby require "logger" client = AMQP::Client.new("amqp://broker?name=worker-1", logger: Logger.new($stdout)) client.start # => INFO -- : AMQP::Client[worker-1]: connected # Thread.list now includes: # "amqp.supervisor[worker-1]" # "amqp.read_loop[worker-1] broker:5672" ``` -------------------------------- ### Create Git Tag Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Creates a git tag for the release, incorporating entries from the changelog. ```bash rake release:tag ``` -------------------------------- ### RPC Server Implementation Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/RELEASE_NOTES_v2.0.0.md Implement an RPC server to handle request-response patterns. The block provided to `rpc_server` receives requests and returns responses. ```ruby # Server amqp.rpc_server("rpc_queue") do |request| { result: request[:value] * 2 } end ``` -------------------------------- ### Run Tests Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/README.md Executes the project's test suite using 'rake test'. ```bash rake test ``` -------------------------------- ### Per-Instance Configuration Override Source: https://github.com/cloudamqp/amqp-client.rb/blob/main/_autodocs/api-reference/configuration.md Override default configuration settings for individual AMQP client instances. This allows different clients to use distinct content types or other settings. ```ruby AMQP::Client.configure do |config| config.default_content_type = "application/json" end # Instance 1 uses JSON (inherited from class config) client1 = AMQP::Client.new("amqp://localhost").start client1.publish({ a: 1 }) # JSON # Instance 2 overrides client2 = AMQP::Client.new("amqp://localhost").start client2.default_content_type = "text/plain" client2.publish({ a: 1 }.to_s) # Plain text # Instance 3 uses class default again client3 = AMQP::Client.new("amqp://localhost").start client3.publish({ a: 1 }) # JSON ```