GithubHelp home page GithubHelp logo

rabbitmq / rabbitmq-tutorials Goto Github PK

View Code? Open in Web Editor NEW
6.5K 267.0 3.6K 4.88 MB

Tutorials for using RabbitMQ in various ways

Home Page: http://www.rabbitmq.com/getstarted.html

License: Apache License 2.0

Shell 3.48% Clojure 2.60% C# 4.94% Erlang 3.26% Go 5.18% Haskell 3.78% Java 19.84% Perl 2.53% PHP 9.60% Python 4.84% Ruby 2.01% Makefile 1.07% JavaScript 2.84% Elixir 2.24% Objective-C 5.31% Swift 4.63% Scala 4.07% Kotlin 5.24% Dart 3.13% Rust 9.42%
rabbitmq tutorials

rabbitmq-tutorials's Introduction

RabbitMQ Tutorials

This project contains code for RabbitMQ tutorials with their ports to various languages.

This repository only contains runnable code. Please consult tutorials on the site to learn more about the concepts, requirements, supported client library version and so on.

And please check out the rest of the RabbitMQ documentation!

Prerequisites

All tutorials require a RabbitMQ node running on localhost with stock (default) settings.

Please refer to RabbitMQ documentation to learn more about various installation options:

Languages

The following ports are available:

License

Released under the Apache License 2.0.

rabbitmq-tutorials's People

Contributors

acogoluegnes avatar camelpunch avatar chimdiadi avatar darrylsk avatar deadtrickster avatar dependabot[bot] avatar gofightnguyen avatar gsantomaggio avatar hogimn avatar jeffweiss avatar jiangyongkang avatar keithelder avatar kjnilsson avatar lanzaa avatar lukebakken avatar majek avatar mandolyte avatar michaelklishin avatar monosoul avatar nielspilgaard avatar pilwon avatar pliner avatar priviterag avatar razer-rbi avatar seyfer avatar siking avatar spring-operator avatar squaremo avatar tatzati avatar videlalvaro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rabbitmq-tutorials's Issues

how to use rabbitmq in multi-thread web request

rpc demo is simple example with a request callback, i wanna to know how to use rabbtmq in multi-thread web rquest . when creating a spring-boot project and sending request to the controller , there are many messages stored in the queue and can not calculate the result correctly. how to handle this situation?

i searched many websites but there are all the same results as this git mentioned . can you give a example ? thanks.

when message from the client send to the server , is there any nessary to give a call back infomation to the client.

topic 6 RPC: no line numbers

there is no line numbers in the code, making below comment hard to refer.

The server code is rather straightforward:

(4) As usual we start by establishing the connection and declaring the queue.
(11) We declare our fibonacci function. It assumes only valid positive integer input. (Don't expect this one to work for big numbers, it's probably the slowest recursive implementation possible).
(19) We declare a callback for basic_consume, the core of the RPC server. It's executed when the request is received. It does the work and sends the response back.
(32) We might want to run more than one server process. In order to spread the load equally over multiple servers we need to set the prefetch_count setting.

queue_bind() error

For receive_log.py, I registered a type error from the queue_bind() method, stating that it got multiple values for the queue argument; is this because there is no declared queue (i.e., the queue is temporary) or because it is generating too many queues too randomly? Or is it because the queue is exclusive and being erased before the consumer receives the queue?

Refactor RPC example(s) to not use queueing consumer implementations

seems refactoring was done only for the server ...

RPCClient.cs(20,35,20,43): warning CS0618: 'RabbitMQ.Client.QueueingBasicConsumer' is obsolete:
RPCClient.cs(34,22,34,43): warning CS0618: 'RabbitMQ.Client.QueueingBasicConsumer' is obsolete: 'Deprecated. Use EventingBasicConsumer or a different consumer interface implementation instead'

Tutorial 2 worker.go does not have dot count

The second tutorial includes a fake delay in worker.go based on the number of dot character in the string sent by new_task.go. The following simple change makes it work as the tutorial intends:

go func() {
    for d := range msgs {
        log.Printf("Received a message: %s", d.Body)
        d.Ack(false)
        // added the following three lines
        sleep_seconds := bytes.Count(d.Body, []byte("."))
        t := time.Duration(sleep_seconds)
        time.Sleep(t * time.Second)
    }
}()

noAck not exist dotnet example 1

In first example
the call of BasicConsume is

channel.BasicConsume(queue:` "hello", noAck: true, consumer: consumer);

Visual Studio Code say NOPE to noAck and in signature of BasicConsume you have autoAck

Disposable 1000000 message in a Queues

package main

import(
"fmt"
"log"
"github.com/streadway/amqp"
)

func failOnError(err error,msg string){
if err!=nil{
log.Fatal("%s:%s",msg,err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}

func main(){
conn,err := amqp.Dial("amqp://guest:[email protected]:5672/")
failOnError(err,"Failed to connect to RabbitMQ")
defer conn.Close()

ch,err:=conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()

q,err :=ch.QueueDeclare("HelloWord",false,false,false,false,nil)
failOnError(err, "Failed to declare a queue")

body:="hello"
for  i := 1;i<1000000;i++ {
	err = ch.Publish(
	"",
	q.Name,
	false,
	false,
	amqp.Publishing{
	ContentType:"text/plain",
	Body:[]byte(body),
	})

}
log.Printf(" [x] Sent %s", body)
failOnError(err, "Failed to publish a message")

}

when i was run this code , there is a problem when i push 1000000 message in a Queues

/usr/local/go/bin/go run /Users/neo_qiang/Documents/goWorkSpase/src/rabbitmqText/send.go
panic: sync: inconsistent mutex state
panic: sync: inconsistent mutex state
panic: sync: inconsistent mutex state

goroutine 1 [running]:
panic(0x20ee80, 0xc8202a5840)
/usr/local/go/src/runtime/panic.go:464 +0x3e6
sync.(*Mutex).Lock(0xc82000c12c)
/usr/local/go/src/sync/mutex.go:75 +0x16d
github.com/streadway/amqp.(*Connection).send(0xc82000c120, 0x1840218, 0xc8202a0ac0, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/connection.go:347 +0xb8
github.com/streadway/amqp.(*Connection).call(0xc82000c120, 0x18c29c0, 0xc8202a0aa0, 0xc820050fc8, 0x1, 0x1, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/connection.go:636 +0xf9
github.com/streadway/amqp.(*Connection).Close(0xc82000c120, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/connection.go:320 +0x220
panic(0x20ee80, 0xc8202a5830)
/usr/local/go/src/runtime/panic.go:426 +0x4e9
sync.(*Mutex).Lock(0xc82000c12c)
/usr/local/go/src/sync/mutex.go:75 +0x16d
github.com/streadway/amqp.(*Connection).send(0xc82000c120, 0x1840218, 0xc8202a0a80, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/connection.go:347 +0xb8
github.com/streadway/amqp.(*Channel).sendOpen(0xc8200ac100, 0x18c28f0, 0xc8202a0a60, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/channel.go:243 +0x79b
github.com/streadway/amqp.(*Channel).call(0xc8200ac100, 0x18c28f0, 0xc8202a0a60, 0xc820051770, 0x1, 0x1, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/channel.go:145 +0x79
github.com/streadway/amqp.(*Channel).Close(0xc8200ac100, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/channel.go:396 +0x199
panic(0x20ee80, 0xc8202a5820)
/usr/local/go/src/runtime/panic.go:426 +0x4e9
sync.(*Mutex).Lock(0xc82000c12c)
/usr/local/go/src/sync/mutex.go:75 +0x16d
github.com/streadway/amqp.(*Connection).send(0xc82000c120, 0x1840638, 0xc8202a0a40, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/connection.go:347 +0xb8
github.com/streadway/amqp.(*Channel).sendOpen(0xc8200ac100, 0x1840578, 0xc8202b17a0, 0x0, 0x0)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/channel.go:235 +0x57a
github.com/streadway/amqp.(*Channel).Publish(0xc8200ac100, 0x0, 0x0, 0xc8200b8030, 0x9, 0x0, 0x0, 0x2d2550, 0xa, 0x0, ...)
/Users/neo_qiang/Documents/goWorkSpase/src/github.com/streadway/amqp/channel.go:1288 +0x42b
main.main()
/Users/neo_qiang/Documents/goWorkSpase/src/rabbitmqText/send.go:40 +0x30f
exit status 2

Process finished with exit code 1

Correct examples using string.getBytes() without a charset

Hi,
there is a problem in your Java examples, that obtain an encoded content of a string as a byte-array via java.lang.String.getBytes():byte[] method. This may lead to a poison message, which makes your whole queue not readable and results in an error (bad_utf8_character_code) looking like this example:

=ERROR REPORT==== 7-May-2015::15:59:37 ===
** Handler sockjs_cowboy_handler terminating in websocket_info/3
   for the reason exit:{ucs,{bad_utf8_character_code}}
** Message was go
** Options were {service,"/stomp",#Fun<rabbit_ws_sockjs.1.120271989>,{},
                         "http://cdn.sockjs.org/sockjs-0.2.js",false,true,
                         5000,25000,131072,#Fun<rabbit_ws_sockjs.0.116551930>,
                         undefined}

.... and so on.

The call of string.getBytes() method uses by default "Charset.defaultCharset()" or "ISO-8859-1" which could produce an incompatible byte-sequence and make it impossible to retrive a queued message.

We would advice to change all calls of string.getBytes() to string.getBytes("UTF-8") in existing examples to force usage of a compatible string encoding.

How to reproduce: publish a message with the following content "Läuft alles?" into a queue using your examples and then try to retrieve this message.

Debian, RabbitMQ 3.5.1, SockJS + Stomp
Greetz, Andre.

Is it possible that multiple consumers of a Rabbitmq queue get the same message?

I am in charge maintaining a production software written in Golang which uses RabbitMq as its message queue.
Consider the following situation:

  1. A number of goroutines are publishing to a queue name logs.

  2. Another set goroutines read from the queue and write the messages to a MongoDB collection.

  3. Each publisher or consumer has its Own connection, and its own channel respectively, they are working in an infinite loop and never die. (The connections and channels are established when the program starts.)

  4. autoAck, exclusive and noWait are all set to false and prefetch is set to 20 with global set to false for all
    channels. All queues are durable with autoDelete, exclusive
    and noWait all set to false.

The basic assumption was that each message in the queue will be delivered to one and only one consumer, so each message would be inserted in the database exactly once.
The problem is that there are duplicate messages in the MongoDB collection.
I would like to know if it is possible that more than one consumer gets the same message causing them to insert duplicates?

C# RPC tutorial does not handle multiple calls from client.

My solution:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Admin.Main.Models;
using Admin.Server.Settings;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Admin.Main.Services;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Mvc;
using System.Threading;

namespace Admin.Main.Services
{
    public class QueueService : IQueueService
    {
        private readonly ILogger<QueueService> _logger;
        private ConnectionFactory _factory;
        private IConnection _connection;
        private ConcurrentDictionary<int, RpcCall> _activeRpcCalls;
        private int _rpcTimeout = 10000;

        public QueueService(ILogger<QueueService> logger, IOptions<QueueSettings> queueSettings)
        {
            _logger = logger;
            _activeRpcCalls = new ConcurrentDictionary<int, RpcCall>();

            _factory = new ConnectionFactory()
            {
                HostName = queueSettings.Value.HostName,
                AutomaticRecoveryEnabled = true,
                TopologyRecoveryEnabled = true
            };
        }

        public Task<string> ExecuteRPCAsync(string exchange, string routingKey, string requestMessage)
        {
            return Task.Run(() => ExecuteRPC(exchange, routingKey, requestMessage));
        }

        public string ExecuteRPC(string exchange, string routingKey, string requestMessage)
        {
            _logger.LogTrace("Trying to execute an RPC call. Exchange={0} | RoutingKey={1} | RequestMessage={2}", exchange, routingKey, requestMessage);
            
            var connection = CreateOrGetConnection();

            using (var channel = connection.CreateModel())
            {
                // The RabbitMQ direct reply-to pattern is used to execute the RPC (remote procedure call).
                // Therefore the RabbitMQ server provides the following pseudo-queue for the replies: 
                var replyQueueName = "amq.rabbitmq.reply-to";
                var correlationId = Guid.NewGuid().ToString();

                // Because the channelNumber is unique for one connection it's possible to store all the information of one rpc call in a global dictionary.
                var rpcCall = new RpcCall(exchange, routingKey, requestMessage, channel, correlationId, replyQueueName);
                var added = _activeRpcCalls.TryAdd(channel.ChannelNumber, rpcCall);
                if(!added) throw new Exception(String.Format("Could not add to active rpc calls dictionary. Exchange={0} | RoutingKey={1} | ChannelNumber={2}", exchange, routingKey, channel.ChannelNumber));

                ConsumeReplyQueue(rpcCall);
                PublishRequest(rpcCall);

                var received = rpcCall.ResponseReceivedEvent.WaitOne(_rpcTimeout); // Block until the event is fired or timeout exceeds
                if(!received) throw new TimeoutException(String.Format("Did not receive a RPC response within {0}ms. Channel={1} | RequestExchange={2} | RoutingKey={3} | Request={4}", _rpcTimeout, channel.ChannelNumber, exchange, routingKey, requestMessage));

                RpcCall removedItem;
                var removed = _activeRpcCalls.TryRemove(channel.ChannelNumber, out removedItem);
                if(!removed) _logger.LogWarning("Could not remove item from active rpc calls dictionary. Exchange={0} | RoutingKey={1} | ChannelNumber={2}", exchange, routingKey, channel.ChannelNumber);

                return rpcCall.Response; 
            }
        }

        private IConnection CreateOrGetConnection()
        {
            if(_connection == null)
            {
                _connection = _factory.CreateConnection();
                _logger.LogDebug("Created new queue connection to '{0}:{1}'.", _connection.Endpoint.HostName, _connection.Endpoint.Port);
                return _connection;
            }
            else return _connection;
        }

        private void ConsumeReplyQueue(RpcCall rpcCall)
        {
            var consumer = new EventingBasicConsumer(rpcCall.Channel);

            consumer.Received += (model, ea) => EventingBasicConsumer_Received(model, ea);

            rpcCall.Channel.BasicConsume(queue: rpcCall.ReplyQueueName,
                                        consumer: consumer,
                                        autoAck: true);
            _logger.LogDebug("Subscribed on replyTo pseudo-queue to wait for RPC response. Channel={0} | RequestExchange={1} | RequestMessage={2}", rpcCall.Channel.ChannelNumber, rpcCall.Exchange, rpcCall.Request);
        }

        private void PublishRequest(RpcCall rpcCall)
        {
            rpcCall.Channel.ExchangeDeclare(rpcCall.Exchange, "topic", durable: true);

            var props = rpcCall.Channel.CreateBasicProperties();
            props.ReplyTo = rpcCall.ReplyQueueName;
            props.CorrelationId = rpcCall.CorrelationId;

            var messageBytes = Encoding.UTF8.GetBytes(rpcCall.Request);

            rpcCall.Channel.BasicPublish(exchange: rpcCall.Exchange,
                                        routingKey: rpcCall.RoutingKey,
                                        basicProperties: props,
                                        body: messageBytes);
            _logger.LogDebug("Published RPC request to exchange '{0}' with routingKey '{1}'. Channel={2} | CorrelationId={3} | RequestMessage={4}", rpcCall.Exchange, rpcCall.RoutingKey, rpcCall.Channel.ChannelNumber, rpcCall.CorrelationId, rpcCall.Request);
        }

        private void EventingBasicConsumer_Received(object model, BasicDeliverEventArgs ea)
        {
            int channelNumber = -1;
            try
            {
                var consumer = (EventingBasicConsumer)model;
                channelNumber = consumer.Model.ChannelNumber;
                RpcCall rpcCall;
                var exists = _activeRpcCalls.TryGetValue(channelNumber, out rpcCall);
 
                if (ea.BasicProperties.CorrelationId == rpcCall.CorrelationId)
                {
                    var message = Encoding.UTF8.GetString(ea.Body);
                    rpcCall.Response = message;
                    
                    _logger.LogInformation("Received RPC response. Channel={0} | RequestExchange={1} | Request={2} | Response={3}", rpcCall.Channel.ChannelNumber, rpcCall.Exchange, rpcCall.Request, message);
                    rpcCall.ResponseReceivedEvent.Set(); // Fire event
                }
                else throw new Exception("Wrong correlation id.");
            }
            catch (Exception e)
            {
                _logger.LogError("Received a response on channel '{0}', but could not interpret it. Error: {1}", channelNumber, e.Message);
            }
        }
    }
}
using System.Threading;
using RabbitMQ.Client;

namespace Admin.Main.Models
{
    public class RpcCall
    {
        public string Exchange { get; }
        public string RoutingKey { get; }
        public IModel Channel { get; }
        public string CorrelationId { get; }
        public string ReplyQueueName { get; }
        public string Request { get; }
        public string Response { get; set; }
        public ManualResetEvent ResponseReceivedEvent { get; }

        public RpcCall(string exchange, string routingKey, string request, IModel channel, string correlationId, string replyQueueName)
        {
            Exchange = exchange;
            RoutingKey = routingKey;
            Channel = channel;
            CorrelationId = correlationId;
            ReplyQueueName = replyQueueName;
            Request = request;
            ResponseReceivedEvent = new ManualResetEvent(false);
        }
    }
}

Isn't rpc_queue required in client ?

rpc_queue is declared only in server and not in client

$channel->queue_declare('rpc_queue', false, false, false, false);

Isn't that required in client? Does default exchange route it to rpc_queue on this basis of this as routing_key ?

How do I install this gem in windows 7?

I have tried to install this gem but fail to install on windows 7.
Can you please tell me how to install on windows 7?

I have tried:
gem install amqp
gem install amqp --pre
gem install amqp --pre --version "~> 0.8.0.rc12"
gem install amqp --platform=win32

php library how to get message_count? $channel->queue_declare('hello', true); return 0 always

<?php

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();


$channel->queue_declare('hello', true, true, false, false);

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$callback = function($msg) use($channel){
	sleep(3);
	$queue_info = $channel->queue_declare('hello', true);
	var_dump($queue_info);
  echo " [x] Received ", $msg->body, "\n";
};

$channel->basic_consume('hello', '', false, true, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}

$channel->close();
$connection->close();

?>

i try $queue_info = $channel->queue_declare('hello', true); get queue,message_count,consumer_count.
and i find message_count always equal 0 ,other fields is right, may be is bug

execute error

python receive_logs_topic.py "_.rabbit"
Traceback (most recent call last):
File "receive_logs_topic.py", line 6, in
host='localhost'))
File "/Library/Python/2.7/site-packages/pika/adapters/blocking_connection.py", line 32, in init
BaseConnection.init(self, parameters, None, reconnection_strategy)
File "/Library/Python/2.7/site-packages/pika/adapters/base_connection.py", line 50, in init
reconnection_strategy)
File "/Library/Python/2.7/site-packages/pika/connection.py", line 170, in init
self._connect()
File "/Library/Python/2.7/site-packages/pika/connection.py", line 228, in _connect
self.parameters.port or spec.PORT)
File "/Library/Python/2.7/site-packages/pika/adapters/blocking_connection.py", line 36, in _adapter_connect
BaseConnection._adapter_connect(self, host, port)
File "/Library/Python/2.7/site-packages/pika/adapters/base_connection.py", line 58, in _adapter_connect
self.socket.connect((host, port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(_args)
socket.error: [Errno 61] Connection refused

python emit_log_topic.py
Traceback (most recent call last):
File "emit_log_topic.py", line 6, in
host='localhost'))
File "/Library/Python/2.7/site-packages/pika/adapters/blocking_connection.py", line 32, in init
BaseConnection.init(self, parameters, None, reconnection_strategy)
File "/Library/Python/2.7/site-packages/pika/adapters/base_connection.py", line 50, in init
reconnection_strategy)
File "/Library/Python/2.7/site-packages/pika/connection.py", line 170, in init
self._connect()
File "/Library/Python/2.7/site-packages/pika/connection.py", line 228, in _connect
self.parameters.port or spec.PORT)
File "/Library/Python/2.7/site-packages/pika/adapters/blocking_connection.py", line 36, in _adapter_connect
BaseConnection._adapter_connect(self, host, port)
File "/Library/Python/2.7/site-packages/pika/adapters/base_connection.py", line 58, in _adapter_connect
self.socket.connect((host, port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 61] Connection refused

Eradicate QueueingBasicConsumer

It is no longer necessary as of 3.5.0 with concurrent dispatch of consumer operations, cannot be automatically recovered and has all kinds of oddities in general. It has to go.

ECONNRESET when running javascript-nodejs tutorial

# node send.js
 [x] Sent 'Hello World!'

/home/vagrant/rabbitmq-tutorials/javascript-nodejs/amqp-hacks.js:13
                throw e;
                      ^
Error: read ECONNRESET
    at errnoException (net.js:904:11)
    at TCP.onread (net.js:558:19)
root@precise64:~/rabbitmq-tutorials/javascript-nodejs#

node send.js - Error: read ECONNRESET

zhe@zhe-X550CL:~/projects/fora$ node send.js
[x] Sent 'Hello World!'

Error: read ECONNRESET
at errnoException (net.js:904:11)
at TCP.onread (net.js:558:19)


Log:

=WARNING REPORT==== 29-Apr-2015::15:15:16 ===
closing AMQP connection <0.458.0> (127.0.0.1:57454 -> 127.0.0.1:5672):
connection_closed_abruptly


AMQP-SERVER

zhe@zhe-X550CL:/var/log/rabbitmq$ sudo service rabbitmq-server status
Status of node 'rabbit@zhe-X550CL' ...
[{pid,24509},
{running_applications,
[{rabbitmq_management,"RabbitMQ Management Console","3.5.1"},
{rabbitmq_web_dispatch,"RabbitMQ Web Dispatcher","3.5.1"},
{webmachine,"webmachine","1.10.3-rmq3.5.1-gite9359c7"},
{mochiweb,"MochiMedia Web Server","2.7.0-rmq3.5.1-git680dba8"},
{rabbitmq_management_agent,"RabbitMQ Management Agent","3.5.1"},
{rabbit,"RabbitMQ","3.5.1"},
{os_mon,"CPO CXC 138 46","2.2.14"},
{inets,"INETS CXC 138 49","5.9.7"},
{mnesia,"MNESIA CXC 138 12","4.11"},
{amqp_client,"RabbitMQ AMQP Client","3.5.1"},
{xmerl,"XML parser","1.3.5"},
{sasl,"SASL CXC 138 11","2.3.4"},
{stdlib,"ERTS CXC 138 10","1.19.4"},
{kernel,"ERTS CXC 138 10","2.16.4"}]},
{os,{unix,linux}},
{erlang_version,
"Erlang R16B03 (erts-5.10.4) [source] [64-bit] [smp:2:2] [async-threads:30] [kernel-poll:true]\n"},
{memory,
[{total,42613792},
{connection_readers,9136},
{connection_writers,5408},
{connection_channels,12016},
{connection_other,33592},
{queue_procs,19616},
{queue_slave_procs,0},
{plugins,513568},
{other_proc,13584352},
{mnesia,61352},
{mgmt_db,207960},
{msg_index,47216},
{other_ets,1060344},
{binary,2643632},
{code,19490409},
{atom,703377},
{other_system,4221814}]},
{alarms,[]},
{listeners,[{clustering,25672,"::"},{amqp,5672,"::"}]},
{vm_memory_high_watermark,0.4},
{vm_memory_limit,3301520179},
{disk_free_limit,50000000},
{disk_free,334267748352},
{file_descriptors,
[{total_limit,924},{total_used,4},{sockets_limit,829},{sockets_used,2}]},
{processes,[{limit,1048576},{used,192}]},
{run_queue,0},
{uptime,1546}]

type error: cannot read property createchannel of undefined (rabbitmq)

hi,i just started learning rabbitmq
i have run the send.js node file and i keep getting the error can not read property create channel
I have only changed one line of the code to
amqp.connect('amqp://hostname:3000', function(err, conn)
what is it that iam probably doing wrong?

update clojure ns names for examples in readme

the use of underscores for clojure namespaces in the readme code examples is incorrect for namespaces containing a dash:

currently (broken):

lein run -m rabbitmq.tutorials.receive_logs_direct

correct:

lein run -m rabbitmq.tutorials.receive-logs-direct

Java samples are outdated

I created a simple Gradle project with following dependency:
compile 'com.rabbitmq:rabbitmq-client:1.3.0'

I copied sample RabbitMQ Java classes over and it shows it to me a lot of errors in them, for example it does not recognize "setHost" method here:
factory.setHost("localhost");

SELinux policy prevents send.php from working via httpd

Fatal error: Uncaught exception 'PhpAmqpLib\Exception\AMQPRuntimeException' with message 'Error Connecting to server(13): Permission denied ' in /var/www/vhosts/myRabbitProject/vendor/videlalvaro/php-amqplib/PhpAmqpLib/Wire/IO/StreamIO.php:27

This is because amqp_port_t type is assigned to port 5672 in the CentOS6 default SELinux policy.

So from your examples, I can run send.php and receive.php from the command line without trouble. The receive.php will be run from the command line, so that's will work fine. However, generally I'm going to want to run send.php when someone hits a particular part of the API (i.e. via http), which generates the error above.

I can add in an SELinux module that allows httpd to connect to port 5672 but I'd like to know whether this would be considered "best-practise"? And if not then what is?

Client unexpectedly closed TCP connection

Java Error Log :

Exception in thread "main" java.util.concurrent.TimeoutException
at com.rabbitmq.utility.BlockingCell.get(BlockingCell.java:76)
at com.rabbitmq.utility.BlockingCell.uninterruptibleGet(BlockingCell.java:110)
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36)
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:366)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:292)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:824)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:778)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:868)
at com.cts.peg.iot.MQTT_HelloWorld.Send.main(Send.java:21)

RabbitMQ Server Logs :

=INFO REPORT==== 22-Sep-2016::16:15:24 ===
Starting RabbitMQ 3.6.5 on Erlang R16B03-1
Copyright (C) 2007-2016 Pivotal Software, Inc.
Licensed under the MPL. See http://www.rabbitmq.com/

=INFO REPORT==== 22-Sep-2016::16:15:24 ===
node : rabbit@iotmaster
home dir : /var/lib/rabbitmq
config file(s) : /etc/rabbitmq/rabbitmq.config (not found)
cookie hash : KF/nlWAlT8axIkjGGrzg3A==
log : /var/log/rabbitmq/[email protected]
sasl log : /var/log/rabbitmq/[email protected]
database dir : /var/lib/rabbitmq/mnesia/rabbit@iotmaster

=INFO REPORT==== 22-Sep-2016::16:15:25 ===
Memory limit set to 3154MB of 7885MB total.

=INFO REPORT==== 22-Sep-2016::16:15:25 ===
Disk free limit set to 50MB

=INFO REPORT==== 22-Sep-2016::16:15:25 ===
Limiting to approx 924 file handles (829 sockets)

=INFO REPORT==== 22-Sep-2016::16:15:25 ===
FHC read buffering: OFF
FHC write buffering: ON

=INFO REPORT==== 22-Sep-2016::16:15:25 ===
Database directory at /var/lib/rabbitmq/mnesia/rabbit@iotmaster is empty. Initialising from scratch...

=INFO REPORT==== 22-Sep-2016::16:15:25 ===
Priority queues enabled, real BQ is rabbit_variable_queue

=INFO REPORT==== 22-Sep-2016::16:15:33 ===
Adding vhost '/'

=INFO REPORT==== 22-Sep-2016::16:15:34 ===
Creating user 'guest'

=INFO REPORT==== 22-Sep-2016::16:15:34 ===
Setting user tags for user 'guest' to [administrator]

=INFO REPORT==== 22-Sep-2016::16:15:34 ===
Setting permissions for 'guest' in '/' to '.', '.', '.*'

=INFO REPORT==== 22-Sep-2016::16:15:34 ===
msg_store_transient: using rabbit_msg_store_ets_index to provide index

=INFO REPORT==== 22-Sep-2016::16:15:34 ===
msg_store_persistent: using rabbit_msg_store_ets_index to provide index

=WARNING REPORT==== 22-Sep-2016::16:15:34 ===
msg_store_persistent: rebuilding indices from scratch

=INFO REPORT==== 22-Sep-2016::16:15:50 ===
started TCP Listener on [::]:5672

=INFO REPORT==== 22-Sep-2016::16:15:58 ===
Server startup complete; 0 plugins started.

=INFO REPORT==== 22-Sep-2016::17:13:18 ===
accepting AMQP connection <0.733.0> (10.226.110.111:57270 -> 10.226.110.110:5672)

=WARNING REPORT==== 22-Sep-2016::17:13:24 ===
closing AMQP connection <0.733.0> (10.226.110.111:57270 -> 10.226.110.110:5672):
client unexpectedly closed TCP connection

RabbitMQ SASL-Server Logs :

empty file

`tutorial-one-java` is missing two imports

As said in the title, the first chapter of the Java tutorial is missing two imports to compile.

The imports of the file Recv.java should have:

...
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP;

for the callback code to work.

Writing Unit Tests

Greetings, I am trying to figure out the best way to write unit tests against these examples.

I tried to use the package amqp-mock but its not compatible (for example, yours use close(), and the mock uses done()).

Would you mind to provide some examples or point me to where I could read some examples?

exclusive vs auto-delete

in fanout chapter:

Secondly, once we disconnect the consumer the queue should be deleted. There's an exclusive flag for that:

result = channel.queue_declare(exclusive=True)

the wording sounds confusing. I understand exclusive will lead to behavior similiar with auto-delete, but from the name exclusive only means the queue can be used exclusively. maybe give some brief explanation about the 2 knobs...

C# RPC Client example is not consistent with the documentation or other languages implementations

Here (https://www.rabbitmq.com/tutorials/tutorial-six-dotnet.html), one can read

We're going to set it to a unique value for every request

At least in the python and the Java implementations, a new correlation id is created each time the 'call' is published to rabbitmq. However, in the C# implementation, the correlation id is created once end for all in the client constructor then reused for each call.

This is not consistent with the text, and imho, it's misleading as the duty of distinguishing between clients is already carried on by the client specific 'ReplyTo' queue...

When I get some time, I can submit a minimal PR for this.

Failed to connect to RabbitMQ: dial tcp [::1]:5672: getsockopt

When I try to run send.go my terminal shows this error.

Failed to connect to RabbitMQ: dial tcp [::1]:5672: getsockopt: connection refused
exit status 1

I get this error even after installing github.com/streadway/amqp
what is the reason for this error??

how to use "rabbitTemplate.sendAndReceive"?

hello, i want to know how to use rabbitTemplate.sendAndReceive to receive some message from rabbitmq server ?

below is my code .

` public Message sendAndReply(User user) {
CorrelationData correlationData = new CorrelationData(user.getUuid());
String json = JSONObject.toJSONString(user);
/***
* replyTo:如果是响应的到返回的消息,必选指定这个返回队列的名称 ① 和 ②
*/
BasicProperties basicProperties = new BasicProperties.Builder()
.correlationId(user.getUuid())
.replyTo(RabbitMQConfig.REPLY_QUEUE_NAME)
.build();
MessageProperties messageProperties = messagePropertiesConverter.toMessageProperties(basicProperties, null,"UTF-8");

	Message sendMessage =  MessageBuilder.withBody(json.getBytes()).andProperties(messageProperties).build();
	messageProperties.setReceivedExchange(RabbitMQConfig.REPLY_EXCHANGE_NAME);
	messageProperties.setReceivedRoutingKey(RabbitMQConfig.REPLY_MESSAGE_KEY);
	messageProperties.setRedelivered(false);
	messageProperties.setCorrelationIdString(user.getUuid());
	rabbitTemplate.expectedQueueNames();
	Message replyMessage=null;
	try {
		rabbitTemplate.setReplyAddress(RabbitMQConfig.REPLY_QUEUE_NAME);
		/**发送消息*/
		replyMessage = rabbitTemplate.sendAndReceive(RabbitMQConfig.SEND_EXCHANGE_NAME, RabbitMQConfig.SEND_MESSAGE_KEY,sendMessage,correlationData);
		
		/**
		 * 接收消息  到时候注意接收消息队列的名称 ②
		 */
		replyMessage = rabbitTemplate.receive(RabbitMQConfig.REPLY_QUEUE_NAME);
		if(replyMessage != null) {
			MessageProperties replyMessageProperties = replyMessage.getMessageProperties();
			System.err.println("收到的消息"+replyMessageProperties.getCorrelationIdString());
		}
		logger.info("收到的反馈消息:"+ (replyMessage == null?"没有接收到消息":new String(replyMessage.getBody(),"UTF-8")));
		
		/***判断消息是否被成功的消费了,是根据数据库存储的消费记录来判断的*/	
		RabbitConfirmMessage confirmMessage = rabbitConfirmMessageRepository.findByCorrelationData(correlationData.getId());
		if(confirmMessage != null) {
			logger.info(correlationData.getId()+(confirmMessage.getAck()?"被成功消费了!":"消费失败"));
		}
	} catch (Exception e) {
		replyMessage = new Message(e.getMessage().getBytes(), new MessageProperties());
		e.printStackTrace();
	}
	return replyMessage;
}`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.