RSS

Category Archives: RabbitMQ

Install RabbitMQ on Windows

 

  1. Download rabbitmq at:
  2. Install
  3. Config Manangement
    • Open cmd
    • go to this path: C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.3.4\sbin
    • input rabbitmq-plugins.bat enable rabbitmq_management and press enter key
    • rabbitmq-service.bat stop
    • rabbitmq-service.bat install
    • rabbitmq-service.bat start
  4. Start use: http://localhost:15672
    • User: guest
    • Password: guest
  5. Crate User:
    • Add a new/fresh user, say user ‘test’ and password ‘test’
      rabbitmqctl add_user test test
    • Give administrative access to the new access
      rabbitmqctl set_user_tags test administrator
    • Set permission to newly created user
      rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
  6. How to allow Guest login via IP
    • C:\Users\[User Name]\AppData\Roaming\RabbitMQ\rabbitmq.config
    • And add: [{rabbit, [{loopback_users, []}]}]. 
 
Leave a comment

Posted by on February 14, 2017 in RabbitMQ

 

Get started with RabbitMQ on Android (Android Studio)

By: LOVISA JOHANSSON (cloudamqp)

This guide explains how to create a simple chat application in Android using Android Studio and RabbitMQ. Everyone that has the application will be able to send and receive messages from all other users that are using the same application.

If you are using Eclipse, check out this blog post instead.

In the code given, messages will first be added to an internal queue and the publisher will send messages from the internal queue to RabbitMQ when there is a connection established. The message will be added back to the queue if the connection is broken.

RabbitMQ Android

This guide assumes that you have downloaded, installed and set up everything correct for Android Studio.

Start by creating a new Android project, open Android Studio and go to File -> New -> New Project..

1. Configure your new project

  1. Enter project information as specified below.create new android project
  2. Select the form factor your app will run onandroid studio
  3. Select if you like to add an activity to your app or not. In this example we choose Blank Activity to get autogenerated files for the project.add android activity
  4. Customize the Activitycustomize android activity

2. Add Java AMQP library to project

RabbitMQ has developed an excellent Java AMQP library. The full API documentation for the library can be found here.

We need to include the RabbitMQ Java Client Library and reference the jar files into the project. In Android Studio you can create a libs folder in the same level as the app. Copy and past the jars in to this libs folder. Mark all the jar files and press “Add As Library…” as seen in the image below.

add rabbitmq library

You can confirm that the libs has been added as library by opening build.gradle and check under dependencies, all files should seen be there.

dependencies {
  ...
  compile files('libs/rabbitmq-client.jar')
  ...
}

NOTE: Only if you are using Android Gradle plugin 0.7.0 and do get the error “Duplicate files copied in APK” when you later run your application, you need to add packagingOptions to your build.gradle file as specified in here.

android {
  packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
  }
}

3. Android Manifest, internet permission

We need to tell the Android system that this app is allowed to access internet. Open the AndroidManifest.xml file, located in the root of the project. Add the user permission android.permission.INTERNET just before the closing /manifest tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cloudamqp.rabbitmq"
     android:versionCode="1"
     android:versionName="1.0">
     ......
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

4. Start coding

Layout

Create the view for the application. The .xml layout file can be found under res->layout. What we have here is a root ScrollView containing a

EditText a Button and a TextView The EditText will be used as an input field for the text that will be sent. The text will be published when the button is pressed and all messages received by the subscriber will be printed to the TextView.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  ...
  <EditText
  android:id="@+id/text"
  android:layout_width="fill_parent"
  android:background="#ffffff"
  android:hint="Enter a message" />

  <Button
  android:id="@+id/publish"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/text"
  android:text="Publish message" />

  <TextView
  android:id="@+id/textView"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_below="@+id/publish"
  android:textColor="#000000" />
  ...
</ScrollView>

Publish

Create an internal message queue. In this case is a BlockingDeque used. Blockingqueues implementations are designed to be used primarily for producer-consumer queues.

private BlockingDeque<String> queue = new LinkedBlockingDeque>String>();
void publishMessage(String message) {
  try {
    Log.d("","[q] " + message);
    queue.putLast(message);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
}

Create a setup function for the ConnectionFactory The connection factory encapsulates a set of connection configuration parameters, in this case the CLOUDAMQP_URL. The URL can be found in the control panel for your instance.

ConnectionFactory factory = new ConnectionFactory();
private void setupConnectionFactory() {
  String uri = "IP";
  try {
    factory.setAutomaticRecoveryEnabled(false);
    //factory.setUri(uri);
    factory.setHost(uri);

  } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException e1) {
    e1.printStackTrace();
}

Create a publisher that publish messages from the internal queue. Messages are added back to the queue if an exception is catched. The publisher will try to reconnect every 5 seconds if the connection is broken.

A thread (“background” or “worker” threads or use of the AsyncTask class) is needed when we have operations to perform that are not instantaneous, such as network access when connecting to rabbitMQ.

We will use a fanout exchange. A fanout exchange routes messages to all of the queues that are bound to it and the routing key is ignored. If N queues are bound to a fanout exchange, will a new message that is published to that exchange, be copied and delivered to all N queues. Fanout exchanges are ideal for the broadcast routing of messages.

public void publishToAMQP()
{
  publishThread = new Thread(new Runnable() {
    @Override
    public void run() {
      while(true) {
        try {
          Connection connection = factory.newConnection();
          Channel ch = connection.createChannel();
          ch.confirmSelect();

          while (true) {
            String message = queue.takeFirst();
            try{
              ch.basicPublish("amq.fanout", "chat", null, message.getBytes());
              Log.d("", "[s] " + message);
              ch.waitForConfirmsOrDie();
            } catch (Exception e){
              Log.d("","[f] " + message);
              queue.putFirst(message);
              throw e;
           }
         }
       } catch (InterruptedException e) {
         break;
       } catch (Exception e) {
         Log.d("", "Connection broken: " + e.getClass().getName());
         try {
           Thread.sleep(5000); //sleep and then try again
         } catch (InterruptedException e1) {
           break;
         }
       }
     }
   }
  });
  publishThread.start();
}

Subscriber

We have now created the publisher, and it is time to create the subscriber. The subscriber will take a handler as parameter. The handler will print the messages to the screen when the messages arrives. The subscribe thread will try to reconnect every 5 seconds when the connection gets broken.

void subscribe(final Handler handler)
{
  subscribeThread = new Thread(new Runnable() {
    @Override
    public void run() {
      while(true) {
        try {
          Connection connection = factory.newConnection();
          Channel channel = connection.createChannel();
          channel.basicQos(1);
          DeclareOk q = channel.queueDeclare();
          channel.queueBind(q.getQueue(), "amq.fanout", "chat");
          QueueingConsumer consumer = new QueueingConsumer(channel);
          channel.basicConsume(q.getQueue(), true, consumer);

          while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            Log.d("","[r] " + message);
            Message msg = handler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("msg", message);
            msg.setData(bundle);
            handler.sendMessage(msg);
          }
        } catch (InterruptedException e) {
          break;
        } catch (Exception e1) {
          Log.d("", "Connection broken: " + e1.getClass().getName());
          try {
            Thread.sleep(5000); //sleep and then try again
          } catch (InterruptedException e) {
            break;
          }
        }
      }
    }
  });
  subscribeThread.start();
}

Call all functions listed above from function onCreate The handler used by the subscribe functions is also created in onCreate. A handler has to be used because it is only possible to write to the GUI from the main tread.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  setupConnectionFactory();
  publishToAMQP();
  setupPubButton();

  final Handler incomingMessageHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      String message = msg.getData().getString("msg");
      TextView tv = (TextView) findViewById(R.id.textView);
      Date now = new Date();
      SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
      tv.append(ft.format(now) + ' ' + message + '\n');
    }
  };
  subscribe(incomingMessageHandler);
}

void setupPubButton() {
  Button button = (Button) findViewById(R.id.publish);
  button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
      EditText et = (EditText) findViewById(R.id.text);
      publishMessage(et.getText().toString());
      et.setText("");
   }
  });
}

The subscribe and the publish tread can both be interrupted when the application is destroyed by adding following code in onDestroy

Thread subscribeThread;
Thread publishThread;
@Override
protected void onDestroy() {
  super.onDestroy();
  publishThread.interrupt();
  subscribeThread.interrupt();
}

 

Copy from: https://www.cloudamqp.com/blog/2015-07-29-rabbitmq-on-android.html

 

Getting Started With RabbitMQ in .net

By: Simon Dixon’s Blog

In the previous two examples I built a simple .net application to demonstrate first two sections the RabbitMQ getting started guide in .net. In this post I’ll be looking at the third. Download the Source

3.) Publish/Subscribe

The original article (in Java) is here:http://www.rabbitmq.com/tutorials/tutorial-three-java.html

I’m going to take a slightly different approach to my previous two examples and split the Producer and Consumer into two different Windows Forms. This will allow us to run as many Consumers as we like  and so demonstrate Pub/Sub effectively.

First up is the Producer.

Create a new Form and add the Input TextBox and Button as in the first two examples. Also and a new Button “Start New Consumer” .

Next create the consumer. We only need to output messages so we only need one RichTextBox

In the previous two examples we had pretty much duplicate constructors for both Consumers and Producers. We will now fix this by creating a base class that these can both inherit from. Create a new class called IConnectToRabbitMQ.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public abstract class IConnectToRabbitMQ : IDisposable
    {
        protected IModel Model { get; set; }
        protected IConnection Connection { get; set; }
        public string Server { get; set; }
        public string ExchangeName{ get; set; }
        public string ExchangeTypeName { get; set; }
        public IConnectToRabbitMQ(string server, string exchange, string exchangeType)
        {
            Server = server;
            Exchange = exchange;
            ExchangeTypeName = exchangeType;
        }
        //Create the connection, Model and Exchange(if one is required)
        public virtual bool ConnectToRabbitMQ()
        {
            try
            {
                var connectionFactory = new ConnectionFactory();
                connectionFactory.HostName = Server;
                Connection = connectionFactory.CreateConnection();
                Model = Connection.CreateModel();
                bool durable = true;
                if (!String.IsNullOrEmpty(Exchange))
                    Model.ExchangeDeclare(Exchange, ExchangeTypeName, durable);
                return true;
            }
            catch (BrokerUnreachableException e)
            {
                return false;
            }
        }
        public void Dispose()
        {
            if (Connection != null)
                Connection.Close();
            if (Model != null)
                Model.Abort();
        }
    }

The class name may look a little odd to most as it begins with an “I”, this is usually the naming convention for an Interface but I’m using what I like to call Simon Says naming convention. I’ll be writing a post about this in the near future. The main gist of it, is I like to have classes tell me what they do. For example, a class which calls a remote service might inherit from a class(or interface) called ICallRemoteServices. So the full class name definition would be FooService : ICallRemoteServices. There would also be a abstract method defined that implements the action e.g CallRemoteService.  Other example are  IAmAnOrder(for a value object), ICalculateShipping, IDeliverEmail etc. This may seem a little weird but I like it 🙂.

So enough of that for now, lets go through the class. First we declare fields to hold the familiar IModeland Connection instances. Next up are fields to store the details of the Server, Exchange andExchangeTypeName.  Exchange is the name of the exchange we want to publish/consume messages from and ExchangeTypeName  holds the type of exchange we want to use(in this example it will be “fanout”).  ExchangeType is set from a constant declared in the RabbitMQ.Client.ExchangeType  class, so for us it will be ExchangeType .Fanout(More on this later.) Next we have the  ConnectToRabbitMQ() method, this is almost exactly the same as the Constructor methods of the Producer/Consumer methods  in my  previous two examples. We have this additional block which declares the Exchange.

1
2
3
bool durable = true;
if (!String.IsNullOrEmpty(ExchangeName))
    Model.ExchangeDeclare(ExchangeName, ExchangeTypeName, durable);

We are declaring a durable exchange of the type ExchangeTypeName with the name ExchangeName.  If this exchange had already been declared by another Producer or Consumer  a new one is not created, the existing one will be used.

Now we’ll write our Producer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Producer : IConnectToRabbitMQ
    {
        public Producer(string server, string exchange, string exchangeType) : base(server, exchange, exchangeType)
        {
        }
        public void SendMessage(byte[] message)
        {
            IBasicProperties basicProperties = Model.CreateBasicProperties();
            basicProperties.SetPersistent(true);
            Model.BasicPublish(ExchangeName, "", basicProperties, message);
        }
    }
}

Here we a have a nice lightweight publisher, the only difference from our previous examples is we are publishing to a named exchange called ExchangeName. We do not know about or use a Queue.

Then it’s our consumer, this is slightly more complicated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Consumer : IConnectToRabbitMQ
    {
        protected bool isConsuming;
        protected string QueueName;
        // used to pass messages back to UI for processing
        public delegate void onReceiveMessage(byte[] message);
        public event onReceiveMessage onMessageReceived;
        public Consumer(string server, string exchange, string exchangeType) : base(server, exchange, exchangeType)
        {
        }
        //internal delegate to run the consuming queue on a seperate thread
        private delegate void ConsumeDelegate();
        public void StartConsuming()
        {
                Model.BasicQos(0, 1, false);
                QueueName = Model.QueueDeclare();
                Model.QueueBind(QueueName, ExchangeName, "");
                isConsuming = true;
                ConsumeDelegate c = new ConsumeDelegate(Consume);
                c.BeginInvoke(null, null);
        }
        protected Subscription mSubscription { get; set; }
        private void Consume()
        {
            bool autoAck = false;
            //create a subscription
            mSubscription = new Subscription(Model, QueueName, autoAck);
            while (isConsuming)
            {
                BasicDeliverEventArgs e = mSubscription.Next();
                byte[] body = e.Body;
                onMessageReceived(body);
                mSubscription.Ack(e);
            }
        }
        public void Dispose()
        {
            isConsuming = false;
            base.Dispose();
        }
    }

We need to store the name of our Queue that we will be binding to the exchange so we have a field QueueName for this purpose. The next code of interest is the StartConsuming() method. Most of this is familiar with this additional block:

1
2
QueueName = Model.QueueDeclare();
Model.QueueBind(QueueName, ExchangeName, "");

What we are doing here is asking the model to declare a temporary queue for us and give it a random unique name(stored in QueueName), we then bind this queue to the Exchange called ExchangeName. 

This a key concept to exchanges in RabbitMQ, a publisher/producer only knows about the Exchange, it will publish messages directly to the Exchange and has no concept of a queue. Each consumer knows about the Exchange but they will also have a queue that is bound to the Exchange.  The way I look at it is the one or more Producers own an Exchange(and publish to it) and each Consumer owns a Queue(which is bound to an Exchange.)

The Consume() method is very different to what we have seen before(and the Java Example). Instead of using a  QueueingBasicConsumer we are using a Subscription. Subscription is part of theRabbitMQ.Client.MessagePatterns package in the .net client Library. It give us a nice wrapper to the boilerplate message de-queuing code. More info is here.

1
2
3
4
5
mSubscription = new Subscription(Model, QueueName, autoAck);
  .....
  BasicDeliverEventArgs e = mSubscription.Next();
  .....
  mSubscription.Ack(e);

Now we need to add the code for our Producer Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public string HOST_NAME = "localhost";
 public string EXCHANGE_NAME = "logs";
 private Producer producer;
 //delegate to show messages on the UI thread
 private delegate void showMessageDelegate(string message);
 public PubSub_Producer()
 {
     InitializeComponent();
     //Declare the producer
     producer = new Producer(HOST_NAME, EXCHANGE_NAME, ExchangeType.Fanout);
     //connect to RabbitMQ
     if(!producer.ConnectToRabbitMQ())
     {
         //Show a basic error if we fail
         MessageBox.Show("Could not connect to Broker");
     }
 }
 private int count = 0;
 private void button1_Click(object sender, EventArgs e)
 {
     string message = String.Format("{0} - {1}", count++, textBox1.Text);
     producer.SendMessage(System.Text.Encoding.UTF8.GetBytes(message));
 }
 private void button2_Click(object sender, EventArgs e)
 {
     //Open a new Consumer Form
     PubSub_Consumer consumer = new PubSub_Consumer();
     consumer.Show();
 }

This should be fairly self explanatory. The producer.ConnectToRabbitMQ() call is handled in the base IConnectToRabbitMQ class. We’ve added little error handling code just in case the broker is unavailable(if it is run rabbitmq-server -detached from the command line .) There’s also a method to handle clicks on the “Start New Consumer” Button which spawns a new Consumer Form.

Then we have our Consumer Form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public partial class PubSub_Consumer : Form
    {
        public string HOST_NAME = "localhost";
        public string EXCHANGE_NAME = "logs";
        private Consumer consumer;
        public PubSub_Consumer()
        {
            InitializeComponent();
            //create the consumer
            consumer = new Consumer(HOST_NAME, EXCHANGE_NAME, ExchangeType.Fanout);
            //connect to RabbitMQ
            if (!consumer.ConnectToRabbitMQ())
            {
                //Show a basic error if we fail
                MessageBox.Show("Could not connect to Broker");
            }
            //Register for message event
            consumer.onMessageReceived += handleMessage;
            //Start consuming
            consumer.StartConsuming();
        }
        //delegate to post to UI thread
        private delegate void showMessageDelegate(string message);
        //Callback for message receive
        public void handleMessage(byte[] message)
        {
            showMessageDelegate s = new showMessageDelegate(richTextBox1.AppendText);
            this.Invoke(s, System.Text.Encoding.UTF8.GetString(message) + Environment.NewLine);
        }
    }

This is exactly the same as previous Consumer examples with the additional call to the base class.

Now we can run the project after making sure the correct Form is opened on starup

1
2
3
4
5
6
7
[STAThread]
     static void Main()
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new PubSub_Producer());
     }

Click the “Start New Consumer” Button a couple of time to get a few consumers running, then put  your message in the “Producer Input”  TextBox and hit send. You should see the message appear in all the Consumer output windows. Good stuff 🙂

Summary

What we have done here is create a Fanout Exchange named “logs”,  we’ve created some Consumers(three in my example above) each with their own unique temporary queue bound to the exchange. We have then published a message to the exchange using our Producer, the exchange then routes the message to all bound queues which in turn delivers it to the Consumers. Download the Source

 

Copy from: https://simonwdixon.wordpress.com/2011/05/19/getting-started-with-rabbitmq-in-net-%E2%80%93-part-3/

 
Leave a comment

Posted by on November 18, 2015 in RabbitMQ

 

Installing RabbitMQ on Ubuntu

By: MONKEY HACKS

 

By default, RabbitMQ packages are included in Ubuntu and Debian Linux distributions. The problem is, they are horribly outdated. You are far better off downloading the package online and installing it yourself.
Installing RabbitMQ
sudo -i

sudo echo "deb http://www.rabbitmq.com/debian testing main" >> /etc/apt/sources.list
After the repository is added, we will add the RabbitMQ public key to our trusted key list to avoid any warnings about unsigned packages.
wget https://www.rabbitmq.com/rabbitmq-signing-key-public.asc
sudo apt-key add rabbitmq-signing-key-public.asc
Now we just need to run an update, and install the rabbitmq-server from our newly added package.
sudo apt-get update
sudo apt-get install rabbitmq-server
If everything installed correctly, you should see a message similar to this:
RabbitMQ Management
To manage your RabbitMQ server, you can use the rabbitmq-management plugin. This plugin allows you to manage and monitor your RabbitMQ server in a variety of ways, such as listing and deleting exchanges, queues, bindings and users. You can send and receive messages, and monitor activity on specific queues.
To install the plugin, use the following command:
sudo rabbitmq-plugins enable rabbitmq_management


ou can access the user-management with rabbitmqctl and use the command:

add_user {username} {password}

or more preferably maybe edit an existing user, or set the permissions for the new user with:

set_permissions [-p vhostpath] {user} {conf} {write} {read}

For example use the following commands: (it is important to perform these three steps even when creating a new user, if you want to be able to login to the UI console and for your programs to work without facing any permission issues)

add_user newadmin s0m3p4ssw0rd
set_user_tags newadmin administrator
set_permissions -p / newadmin ".*" ".*" ".*"
Once the plugin is installed, you are able to access it via the following url:
http://[your-server]:15672/
If you are running the server on your local machine, the url will be as simple as http://localhost:15672/. You should see the following screen when you first access the plugin:
The default username and password are guest and guest. Login, and you will be greeted with the RabbitMQ dashboard.
Congratulations! You now have your own RabbitMQ Server. If you have any questions, feel free to leave them in the comments below.
*** Notation: if guest fail login please do as follow:

So I created the rabbitmq.config inside the directory /etc/rabbitmq with this:

[{rabbit, [{loopback_users, []}]}].

Then

sudo invoke-rc.d rabbitmq-server stop

sudo invoke-rc.d rabbitmq-server start

and both the console and the java client can access using guest/guest:

 

 
Leave a comment

Posted by on October 14, 2015 in Application Server, RabbitMQ