### Worker setup with AMQP 1.0 Go client Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-two-go-amqp10.md This code snippet shows the initial setup for a worker using the AMQP 1.0 Go client, including connecting to the broker and declaring the necessary queue. It's a part of the `worker.go` example. ```go package main import ( "bytes" "context" "errors" "log" "time" rmq "github.com/rabbitmq/rabbitmq-amqp-go-client/pkg/rabbitmqamqp" ) const brokerURI = "amqp://guest:guest@localhost:5672/" func main() { ctx := context.Background() env := rmq.NewEnvironment(brokerURI, nil) conn, err := env.NewConnection(ctx) if err != nil { log.Panicf("Failed to connect to RabbitMQ: %v", err) } defer func() { _ = env.CloseConnections(context.Background()) }() _, err = conn.Management().DeclareQueue(ctx, &rmq.QuorumQueueSpecification{Name: "task_queue"}) if err != nil { ``` -------------------------------- ### Setup Project Scaffolding Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-two-dotnet-stream.md Shell commands to initialize .NET console projects and install the RabbitMQ Stream Client dependency. ```shell dotnet new console --name OffsetTrackingSend mv OffsetTrackingSend/Program.cs OffsetTrackingSend/OffsetTrackingSend.cs dotnet new console --name OffsetTrackingReceive mv OffsetTrackingReceive/Program.cs OffsetTrackingReceive/OffsetTrackingReceive.cs cd OffsetTrackingSend dotnet add package RabbitMQ.Stream.Client cd ../OffsetTrackingReceive dotnet add package RabbitMQ.Stream.Client cd .. ``` -------------------------------- ### Install AMQP 1.0 Go Client Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-go-amqp10.md Install the RabbitMQ AMQP 1.0 Go client library using the go get command. This is required before writing any code. ```go go get github.com/rabbitmq/rabbitmq-amqp-go-client ``` -------------------------------- ### Install amqp.node Client Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-javascript.md Installs the amqp.node client library, which is used to interact with RabbitMQ using the AMQP 0-9-1 protocol. This is a prerequisite for running the JavaScript examples. ```bash npm install amqplib ``` -------------------------------- ### Erlang: Basic Example of Publishing and Consuming Messages Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/client-libraries/erlang-client-user-guide.md A complete basic example in Erlang demonstrating the library's usage. It includes starting a connection, opening a channel, declaring a queue, publishing a message, polling for it using 'basic.get', and acknowledging its receipt with 'basic.ack'. This example uses polling and manual acknowledgements. ```erlang -module(amqp_example). -include("amqp_client.hrl"). -compile([export_all]). test() -> %% Start a network connection {ok, Connection} = amqp_connection:start(#amqp_params_network{}), %% Open a channel on the connection {ok, Channel} = amqp_connection:open_channel(Connection), %% Declare a queue #'queue.declare_ok'{queue = Q} = amqp_channel:call(Channel, #'queue.declare'{}), %% Publish a message Payload = <<"foobar">>, Publish = #'basic.publish'{exchange = <<>>, routing_key = Q}, amqp_channel:cast(Channel, Publish, #amqp_msg{payload = Payload}), %% Poll for a message Get = #'basic.get'{queue = Q}, {#'basic.get_ok'{delivery_tag = Tag}, Content} = amqp_channel:call(Channel, Get), %% Do something with the message payload %% (some work here) %% Ack the message amqp_channel:cast(Channel, #'basic.ack'{delivery_tag = Tag}), %% Close the channel amqp_channel:close(Channel), %% Close the connection amqp_connection:close(Connection), ok. ``` -------------------------------- ### Start RabbitMQ Documentation Development Server Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/GEMINI.md Starts a local development server for the RabbitMQ documentation website. Access it at http://localhost:3000/docs. ```bash npm start ``` -------------------------------- ### Setup RabbitMQ Stream Environment Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2022-07-05-rabbitmq-3-11-feature-preview-single-active-consumer-for-streams/index.md Shell commands to remove existing images, start a RabbitMQ broker with stream support enabled via Docker, and clone the sample project repository. ```shell docker rmi pivotalrabbitmq/rabbitmq-stream docker run -it --rm --name rabbitmq -p 5552:5552 -p 5672:5672 -p 15672:15672 \ -e RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS='-rabbitmq_stream advertised_host localhost' \ pivotalrabbitmq/rabbitmq-stream cd /tmp git clone https://github.com/acogoluegnes/rabbitmq-stream-single-active-consumer.git cd rabbitmq-stream-single-active-consumer ``` -------------------------------- ### Basic Example: Publish, Poll, and Acknowledge Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/client-libraries/erlang-client-user-guide.md A complete example demonstrating basic usage: establishing a connection, opening a channel, declaring a queue, publishing a message, polling for it, and acknowledging its receipt. ```APIDOC ## A Basic Example {#example} Below is a complete example of basic usage of the library. For the sake of simplicity it does not use [publisher confirms](/docs/confirms) and uses a [polling consumer](#polling) which performs [manual acknowledgements](/docs/confirms). ```erlang -module(amqp_example). -include("amqp_client.hrl"). -compile([export_all]). test() -> %% Start a network connection {ok, Connection} = amqp_connection:start(#amqp_params_network{}), %% Open a channel on the connection {ok, Channel} = amqp_connection:open_channel(Connection), %% Declare a queue #'queue.declare_ok'{queue = Q} = amqp_channel:call(Channel, #'queue.declare'{}), %% Publish a message Payload = <<"foobar">>, Publish = #'basic.publish'{exchange = <<>>, routing_key = Q}, amqp_channel:cast(Channel, Publish, #amqp_msg{payload = Payload}), %% Poll for a message Get = #'basic.get'{queue = Q}, {#'basic.get_ok'{delivery_tag = Tag}, Content} = amqp_channel:call(Channel, Get), %% Do something with the message payload %% (some work here) %% Ack the message amqp_channel:cast(Channel, #'basic.ack'{delivery_tag = Tag}), %% Close the channel amqp_channel:close(Channel), %% Close the connection amqp_connection:close(Connection), ok. ``` In this example, a queue is created with a server generated name and a message is published directly to the queue. This makes use of the fact that every queue is bound to the default exchange via its own queue name. The message is then dequeued and acknowledged. ``` -------------------------------- ### Run RPC Client (Example) Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-six-go-amqp10.md Another example of running the RPC client with a different input value. This demonstrates sending a request for fib(10) and receiving the result. ```bash go run rpc_client.go 10 # => [x] Requesting fib(10) # => [.] Got 55 ``` -------------------------------- ### Install Docusaurus Dependencies Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/README.md Installs the necessary JavaScript components for Docusaurus. This command should be run once before starting development. ```shell # for NPM users npm install ``` -------------------------------- ### Run Publisher Confirms Example Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-seven-go.md Execute the publisher_confirms.go file to observe the performance of different publisher confirm strategies. ```bash go run publisher_confirms.go ``` -------------------------------- ### Initialize Go Project with AMQP Client Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-go-amqp10.md Set up your Go project by creating a go.mod file and specifying the AMQP client dependency. ```go module rabbitmq-tutorials go 1.21 require github.com/rabbitmq/rabbitmq-amqp-go-client v0.7.0 ``` -------------------------------- ### Install Pika Python Client Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-python.md Installs the Pika library, the recommended Python client for RabbitMQ, using pip. This is a prerequisite for running the Python examples in the tutorial. ```bash python -m pip install pika --upgrade ``` -------------------------------- ### Running RabbitMQ Swift Examples Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-four-swift.md Command line instructions for executing the emitter and receiver programs to demonstrate direct routing. ```bash swift run ReceiveLogsDirect warning error > logs_from_rabbit.log swift run ReceiveLogsDirect info warning error swift run EmitLogDirect error "Run. Run. Or it will explode." ``` -------------------------------- ### Setting up a Consumer to Receive Messages Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-dotnet-amqp10.md Declare the 'hello' queue and set up a consumer with a message handler. The handler logs the received message and accepts it using ctx.Accept(). ```csharp IManagement management = connection.Management(); IQueueSpecification queueSpec = management.Queue("hello").Type(QueueType.QUORUM); await queueSpec.DeclareAsync(); IConsumer consumer = await connection.ConsumerBuilder() .Queue("hello") .MessageHandler((ctx, message) => { Console.WriteLine($"Received a message: {Encoding.UTF8.GetString(message.Body()!)}"); ctx.Accept(); return Task.CompletedTask; }) .BuildAndStartAsync(); ``` -------------------------------- ### Initialize RabbitMQ Swift Project Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-swift.md Commands to create a new directory and initialize a Swift executable package for the RabbitMQ tutorial. ```bash mkdir rabbitmq-swift-tutorial cd rabbitmq-swift-tutorial swift package init --type executable --name Send ``` -------------------------------- ### Setup Erlang and Elixir Environment Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2022-05-31-flame-graphs/index.md Commands to install specific versions of Erlang/OTP and Elixir using kerl and kiex, which are necessary for JIT-enabled profiling. ```bash kerl build 25.0 25.0 kerl install 25.0 ~/kerl/25.0 source ~/kerl/25.0 kiex install 1.12.3 kiex use 1.12.3 ``` -------------------------------- ### MQTT Client Request-Response Example using mqttx Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2023-07-21-mqtt5/index.md Demonstrates a typical request-response pattern using MQTT clients with the mqttx tool. It shows how to subscribe to topics, publish messages with correlation data and response topics, and handle responses, highlighting the use of correlation data for message matching. ```bash mqttx sub --client-id responder --topic t/7 --session-expiry-interval 600 --output-mode clean --qos 1 ``` ```bash mqttx sub --client-id requester --topic my/response/topic --session-expiry-interval 600 --qos 1 … Connecting... ✔ Connected … Subscribing to my/response/topic... ✔ Subscribed to my/response/topic ^C ``` ```bash mqttx pub --client-id requester --topic t/7 --message "my request" \ --correlation-data abc-123 --response-topic my/response/topic \ --session-expiry-interval 600 --no-clean ``` ```json { "topic": "t/7", "payload": "my request", "packet": { ... "properties": { "responseTopic": "my/response/topic", "correlationData": { "type": "Buffer", "data": [ 97, 98, 99, 45, 49, 50, 51 ] } } } } ``` ```bash mqttx pub --client-id responder --topic my/response/topic --message "my response" --correlation-data abc-123 ``` ```bash mqttx sub --client-id requester --topic my/response/topic --no-clean --qos 1 --output-mode clean { "topic": "my/response/topic", "payload": "my response", "packet": { ... "properties": { "correlationData": { "type": "Buffer", "data": [ 97, 98, 99, 45, 49, 50, 51 ] } } } } ``` -------------------------------- ### Configure Consumer Offset Specifications Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-two-rust-stream.md Examples of configuring the RabbitMQ consumer to start from different positions in the stream, such as a specific offset or the next available message. ```rust consumer = environment .consumer() .offset(OffsetSpecification::Offset(42)) .build(stream) .await .unwrap(); ``` ```rust consumer = environment .consumer() .offset(OffsetSpecification::Next) .build(stream) .await .unwrap(); ``` -------------------------------- ### Setup Java Environment for RabbitMQ Streams Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-java-stream.md Verifies the Java installation and Maven setup required for the RabbitMQ Stream Java client. It ensures that 'java --help' and './mvnw --version' commands execute successfully, indicating a properly configured environment for building the project. ```bash java --help ``` ```shell ./mvnw --version ``` -------------------------------- ### RabbitMQ Consumer Setup in Ruby Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-ruby.md Establishes a connection to RabbitMQ, creates a channel, and declares a queue named 'hello'. Ensure the queue exists before consuming messages. ```ruby connection = Bunny.new connection.start channel = connection.create_channel queue = channel.quorum_queue('hello') ``` -------------------------------- ### Retrieve Authentication Attempt Metrics via HTTP API Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2021-03-01-auth-attempts-metrics/index.md Examples of HTTP GET requests to query authentication attempt statistics from the RabbitMQ management plugin. ```plaintext GET /api/auth/attempts/{node} GET /api/auth/attempts/{node}/source ``` -------------------------------- ### Setup Python Environment for RabbitMQ Streams Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-python-stream.md Commands to create a project directory and install the rstream library using pip or pipenv. This is a prerequisite for running the producer and consumer scripts. ```bash mkdir python-rstream cd python-rstream pip install rstream ``` ```bash mkdir python-rstream cd python-rstream pipenv install rstream pipenv shell ``` -------------------------------- ### Run RabbitMQ Topic Examples via CLI Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-five-dotnet.md Commands to execute the .NET producer and consumer applications with various routing key patterns to demonstrate topic-based filtering. ```bash # Receive all logs dotnet run "#" # Receive logs from specific facility dotnet run "kern.*" # Receive logs with specific severity dotnet run "*.critical" # Emit a specific log message dotnet run "kern.critical" "A critical kernel error" ``` -------------------------------- ### Connect to RabbitMQ using ConnectionFactory Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/client-libraries/java-api-guide.md Demonstrates how to initialize a ConnectionFactory, set connection parameters such as credentials and host details, and establish a new connection. ```java ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(userName); factory.setPassword(password); factory.setVirtualHost(virtualHost); factory.setHost(hostName); factory.setPort(portNumber); Connection conn = factory.newConnection(); ``` -------------------------------- ### Run Publisher Confirms Example in .NET Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-seven-dotnet.md Execute the PublisherConfirms.cs sample to observe the performance of different publisher confirm strategies. The output will show the time taken for publishing messages using per-message, batch, and asynchronous confirmation handling. ```shell dotnet run # => 11/6/2024 10:36:22 AM [INFO] publishing 50,000 messages and handling confirms per-message # => 11/6/2024 10:36:28 AM [INFO] published 50,000 messages individually in 5,699 ms # => 11/6/2024 10:36:28 AM [INFO] publishing 50,000 messages and handling confirms in batches # => 11/6/2024 10:36:29 AM [INFO] published 50,000 messages in batch in 1,085 ms # => 11/6/2024 10:36:29 AM [INFO] publishing 50,000 messages and handling confirms asynchronously # => 11/6/2024 10:36:29 AM [WARNING] message sequence number 50000 has been basic.return-ed # => 11/6/2024 10:36:29 AM [WARNING] message sequence number 50000 has been basic.return-ed # => 11/6/2024 10:36:29 AM [WARNING] message sequence number 50000 has been basic.return-ed # => ... # => ... # => ... # => 11/6/2024 10:36:30 AM [WARNING] message sequence number 50000 has been basic.return-ed # => 11/6/2024 10:36:30 AM [INFO] published 50,000 messages and handled confirm asynchronously 878 ms ``` -------------------------------- ### Connect to RabbitMQ and Declare Stream (Node.js) Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-javascript-stream.md Establishes a connection to a RabbitMQ instance and declares a stream with specified retention policies. This setup is common for both producers and consumers, allowing either to be started first. ```javascript const rabbit = require("rabbitmq-stream-js-client") const client = await rabbit.connect({ hostname: "localhost", port: 5552, username: "guest", password: "guest", vhost: "/" }) const streamName = "my-stream" const streamSizeRetention = 5 * 1e9 await client.createStream({ stream: streamName, arguments: { "max-length-bytes": streamSizeRetention } }); ``` -------------------------------- ### Setup RabbitMQ exchange and queue Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2011-08-16-using-the-rabbitmq-service-on-cloud-foundry-with-nodejs/index.md Configures the RabbitMQ exchange and anonymous queue, handling the asynchronous nature of AMQP operations via callbacks to ensure the queue is bound before starting the HTTP server. ```javascript var messages = []; function setup() { var exchange = conn.exchange('cf-demo', {'type': 'fanout', durable: false}, function() { var queue = conn.queue('', {durable: false, exclusive: true}, function() { queue.subscribe(function(msg) { messages.push(htmlEscape(msg.body)); if (messages.length > 10) { messages.shift(); } }); queue.bind(exchange.name, ''); }); queue.on('queueBindOk', function() { httpServer(exchange); }); }); } ``` -------------------------------- ### Install Local Path Provisioner (Bash) Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/kubernetes/operator/quickstart-operator.md Applies the Local Path Provisioner to a Kubernetes cluster, which is useful for local development environments like 'kind' or 'minikube'. This ensures that PVCs can be satisfied, allowing RabbitMQ to start. ```bash kubectl apply -f https://raw.githubusercontent.com/rancher/local-path-provisioner/master/deploy/local-path-storage.yaml kubectl annotate storageclass local-path storageclass.kubernetes.io/is-default-class=true ``` -------------------------------- ### Build and Run RabbitMQ Tutorial Application Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-two-spring-amqp.md Commands to compile the project using Maven and execute the sender and receiver instances using Spring profiles. ```bash ./mvnw clean package # shell 1 java -jar target/rabbitmq-tutorials.jar --spring.profiles.active=work-queues,receiver # shell 2 java -jar target/rabbitmq-tutorials.jar --spring.profiles.active=work-queues,sender ``` -------------------------------- ### Bash Commands for RabbitMQ RPC Example Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-six-go.md These bash commands demonstrate how to run the RabbitMQ RPC server and client. The server starts listening for requests, and the client sends a request with a specific number to calculate its Fibonacci value. ```bash go run rpc_server.go # => [x] Awaiting RPC requests ``` ```bash go run rpc_client.go 30 # => [x] Requesting fib(30) ``` -------------------------------- ### Initialize RabbitMQ Stream System and Stream Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-two-dotnet-stream.md Sets up the StreamSystem configuration and declares a new stream for the offset tracking tutorial. ```csharp var streamSystem = await StreamSystem.Create(new StreamSystemConfig()); var stream = "stream-offset-tracking-dotnet"; await streamSystem.CreateStream(new StreamSpec(stream)); ``` -------------------------------- ### Get OAuth2 Token with .NET Client Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/client-libraries/dotnet-api-guide.md Demonstrates how to obtain an OAuth2 JWT token using the `OAuth2ClientCredentialsProvider` in the .NET client. This token is then used to establish a connection to RabbitMQ. It covers basic setup and production considerations like using HTTPS and configuring HttpClientHandler. ```csharp using RabbitMQ.Client.OAuth2; var tokenEndpointUri = new Uri("http://somedomain.com/token"); var oAuth2Client = new OAuth2ClientBuilder("client_id", "client_secret", tokenEndpointUri).Build(); ICredentialsProvider credentialProvider = new OAuth2ClientCredentialsProvider("prod-uaa-1", oAuth2Client); var connectionFactory = new ConnectionFactory { CredentialsProvider = credentialProvider }; var connection = await connectionFactory.CreateConnectionAsync(); ``` ```csharp HttpClientHandler httpClientHandler = buildHttpClientHandlerWithTLSEnabled(); var tokenEndpointUri = new Uri("https://somedomain.com/token"); var oAuth2ClientBuilder = new OAuth2ClientBuilder("client_id", "client_secret", tokenEndpointUri) oAuth2ClientBuilder.SetHttpClientHandler(httpClientHandler); var oAuth2Client = await oAuth2ClientBuilder.BuildAsync(); ICredentialsProvider credentialsProvider = new OAuth2ClientCredentialsProvider("prod-uaa-1", oAuth2Client); var connectionFactory = new ConnectionFactory { CredentialsProvider = credentialsProvider }; var connection = await connectionFactory.CreateConnectionAsync(); ``` -------------------------------- ### Build RabbitMQ Documentation Website Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/GEMINI.md Use this command to build the RabbitMQ documentation website. For development with more details, use the '--dev' flag. ```bash npm run docusaurus "--" build ``` ```bash npm run docusaurus "--" build "--dev" ``` -------------------------------- ### Java Code for RabbitMQ Streams Consumer Setup Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2021-07-19-rabbitmq-streams-first-application/index.md This Java code snippet demonstrates how to configure a consumer for RabbitMQ Streams. It shows the creation of a `Consumer` instance, specifying the stream to consume from, the starting offset, and a message handler to process incoming messages by incrementing a counter. ```java AtomicInteger messageConsumed = new AtomicInteger(0); // just a counter Consumer consumer = environment.consumerBuilder() .stream("first-application-stream") // stream to consume from .offset(OffsetSpecification.first()) // where to start consuming .messageHandler((context, message) -> messageConsumed.incrementAndGet()) // behavior .build(); ``` -------------------------------- ### Erlang State Transform Monad Transformer Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2011-05-17-can-you-hear-the-drums-erlando/index.md This example demonstrates the State Transform monad transformer in Erlang, applied to the Identity-monad. It abstracts state management, allowing functions to 'get' and 'set' state implicitly. This avoids manual state variable re-numbering in single-assignment languages. ```erlang StateT = state_t:new(identity_m), SM = StateT:modify(_), SMR = StateT:modify_and_return(_), StateT:exec( do([StateT || StateT:put(init(Dimensions)), SM(plant_seeds(SeedCount, _)), DidFlood <- SMR(pour_on_water(WaterVolume, _)), SM(apply_sunlight(Time, _)), DidFlood2 <- SMR(pour_on_water(WaterVolume, _)), Crop <- SMR(harvest(_)), ... ]), undefined). ``` -------------------------------- ### Run RabbitMQ Go Scripts Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-go.md Command line instructions to execute the publisher and consumer Go scripts. ```bash go run send.go go run receive.go ``` -------------------------------- ### Java RabbitMQ Stream Consumer Setup Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-java-stream.md This Java code sets up a RabbitMQ stream consumer. It initializes the environment, declares the stream if it doesn't exist, and configures the consumer to start from the first available message. The consumer continuously listens for and prints messages received from the specified stream. ```Java import com.rabbitmq.stream.ByteCapacity; import com.rabbitmq.stream.Consumer; import com.rabbitmq.stream.Environment; import com.rabbitmq.stream.OffsetSpecification; public class Receive { public static void main(String[] args) throws Exception { Environment environment = Environment.builder().build(); String stream = "hello-java-stream"; environment.streamCreator().stream(stream).maxLengthBytes(ByteCapacity.GB(5)).create(); Consumer consumer = environment.consumerBuilder() .stream(stream) .offset(OffsetSpecification.first()) .messageHandler((unused, message) -> { System.out.println("Received message: " + new String(message.getBodyAsBinary())); }).build(); } } ``` -------------------------------- ### Creating a RabbitMQ Publisher Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/client-libraries/amqp-client-libraries.md Demonstrates how to initialize a publisher instance bound to a specific exchange and routing key. This setup allows messages to be consistently routed to the target destination. ```java Publisher publisher = connection.publisherBuilder() .exchange("foo").key("bar") .build(); // ... // close the publisher when it is no longer necessary publisher.close(); ``` ```csharp IPublisher publisher = await connection.PublisherBuilder().Exchange("foo").Key("bar") .BuildAsync(); // ... // close the publisher when it is no longer necessary await publisher.CloseAsync(); publisher.Dispose(); ``` ```python exchange_address = AddressHelper.exchange_address("foo", "bar") publisher = connection.publisher(addr) # close the publisher when it is no longer necessary publisher.close() ``` ```go publisher, err := amqpConnection.NewPublisher(context.Background(), &rmq.ExchangeAddress{ Exchange: "foo", Key: "bar", }, nil) // close the publisher when it is no longer necessary publisher.close() ``` ```javascript const publisher = await connection.createPublisher({ exchange: { name: "exchange", routingKey: "key" }, }); // close the publisher when it is no longer necessary publisher.close(); ``` -------------------------------- ### Create Consumer and Receive Messages Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-go-amqp10.md Set up a message consumer for the 'hello' queue. The consumer continuously listens for messages, logs them, and acknowledges receipt. Ensure the consumer is closed after use. ```go package main import ( "context" "errors" "log" rmq "github.com/rabbitmq/rabbitmq-amqp-go-client/pkg/rabbitmqamqp" ) const brokerURI = "amqp://guest:guest@localhost:5672/" func main() { ctx := context.Background() env := rmq.NewEnvironment(brokerURI, nil) conn, err := env.NewConnection(ctx) if err != nil { log.Panicf("Failed to connect to RabbitMQ: %v", err) } defer func() { _ = env.CloseConnections(context.Background()) }() _, err = conn.Management().DeclareQueue(ctx, &rmq.QuorumQueueSpecification{Name: "hello"}) if err != nil { log.Panicf("Failed to declare a queue: %v", err) } consumer, err := conn.NewConsumer(ctx, "hello", nil) if err != nil { log.Panicf("Failed to create consumer: %v", err) } defer func() { _ = consumer.Close(context.Background()) }() log.Printf(" [*] Waiting for messages. To exit press CTRL+C") for { delivery, err := consumer.Receive(ctx) if err != nil { if errors.Is(err, context.Canceled) { return } log.Panicf("Failed to receive a message: %v", err) } msg := delivery.Message() var body string if len(msg.Data) > 0 { body = string(msg.Data[0]) } log.Printf("Received a message: %s", body) err = delivery.Accept(ctx) if err != nil { log.Panicf("Failed to accept message: %v", err) } } } ``` -------------------------------- ### Configure TLS for RabbitMQ Java Client Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/client-libraries/java-api-guide.md Demonstrates the basic setup for enabling TLS encryption between the Java client and the RabbitMQ broker. This example is suitable for development but does not include peer certificate verification, making it vulnerable to man-in-the-middle attacks. For production, proper certificate verification must be implemented. ```java ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5671); // Only suitable for development. // This code will not perform peer certificate chain verification and prone // to man-in-the-middle attacks. // See the main TLS guide to learn about peer verification and how to enable it. factory.useSslProtocol(); ``` -------------------------------- ### Initialize RabbitMQ with MQTT 5.0 Support Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/blog/2023-07-21-mqtt5/index.md Commands to start a RabbitMQ 3.13 container, enable the MQTT plugin, and activate all required feature flags for MQTT 5.0 support. ```bash docker run -it --rm --name rabbitmq -p 1883:1883 -p 15672:15672 -p 15692:15692 rabbitmq:3.13.0-management docker exec rabbitmq rabbitmq-plugins enable rabbitmq_mqtt docker exec rabbitmq rabbitmqctl enable_feature_flag all docker exec rabbitmq rabbitmqctl list_feature_flags --formatter=pretty_table ``` -------------------------------- ### Install RabbitMQ Cluster Operator Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/kubernetes/operator/install-operator.md Apply the operator manifest to install the RabbitMQ Cluster Kubernetes Operator. This command installs the latest stable version. ```bash kubectl apply -f "https://github.com/rabbitmq/cluster-operator/releases/latest/download/cluster-operator.yml" # namespace/rabbitmq-system created # customresourcedefinition.apiextensions.k8s.io/rabbitmqclusters.rabbitmq.com created # serviceaccount/rabbitmq-cluster-operator created # role.rbac.authorization.k8s.io/rabbitmq-cluster-leader-election-role created # clusterrole.rbac.authorization.k8s.io/rabbitmq-cluster-operator-role created # rolebinding.rbac.authorization.k8s.io/rabbitmq-cluster-leader-election-rolebinding created # clusterrolebinding.rbac.authorization.k8s.io/rabbitmq-cluster-operator-rolebinding created # deployment.apps/rabbitmq-cluster-operator created ``` -------------------------------- ### Create Publisher and Send Message Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/tutorials/tutorial-one-go-amqp10.md Create a message publisher, send a message to the 'hello' queue, and verify the broker's acceptance. Ensure the publisher is closed after use. ```go publisher, err := conn.NewPublisher(ctx, &rmq.QueueAddress{Queue: "hello"}, nil) if err != nil { log.Panicf("Failed to create publisher: %v", err) } defer func() { _ = publisher.Close(context.Background()) }() body := "Hello World!" res, err := publisher.Publish(ctx, rmq.NewMessage([]byte(body))) if err != nil { log.Panicf("Failed to publish a message: %v", err) } sswitch res.Outcome.(type) { case *rmq.StateAccepted: default: log.Panicf("Unexpected publish outcome: %v", res.Outcome) } log.Printf(" [x] Sent %s\n", body) ``` -------------------------------- ### Install cert-manager for RabbitMQ Operator Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/kubernetes/operator/install-topology-operator.md Installs cert-manager, a prerequisite for one of the RabbitMQ Messaging Topology Operator installation methods. This command applies the cert-manager deployment from a specific release URL. ```bash kubectl apply -f https://github.com/jetstack/cert-manager/releases/download/v1.3.1/cert-manager.yaml ``` -------------------------------- ### Install RabbitMQ Cluster Operator using kubectl rabbitmq plugin Source: https://github.com/rabbitmq/rabbitmq-website/blob/main/kubernetes/operator/quickstart-operator.md Installs the RabbitMQ Cluster Operator using the `kubectl rabbitmq` plugin. This is a simplified command provided by the plugin to automate the operator installation process. ```bash kubectl rabbitmq install-cluster-operator ```