SpringBoot RabbitMq Headers Exchange

In the past post, we had introduced about RabbitMQ Topic Exchange. Today, JavaSampleApproach will show you how to work with SpringBoot RabbitMQ Headers Exchange.

Related posts:
SpringBoot RabbitMQ Topic Exchange
RabbitMQ – How to create Spring RabbitMQ Producer/Consumer applications with SpringBoot
RabbitMq – How to create Spring RabbitMq Publish/Subcribe pattern with SpringBoot
RabbitMQ – How to send/receive Java object messages with Spring RabbitMq | SpringBoot
SpringBoot RabbitMq Exchange to Exchange Topology

I. Technologies

– Java 8
– Maven 3.6.1
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.7.RELEASE
– RabbitMQ

II. RabbitMq Headers Exchange

Headers exchange routes message based on header values instead of routing keys.
A special argument named x-match has 2 values {all, any} where all is the default value of a headers binding.
x-match = all means that all the values must match.
x-match = any means just one matching header value is sufficient.

springboot rabbitmq exchage headers - architecture design

Scenarios with above design:
– When sending a message with headers: {layer=system, level=error}, the message will be delivered to 2 queues {Q1, Q2}.
– When sending a message with headers: {layer=application, level=error}, the message will be delivered to one queue Q2.
– When sending a message with headers: {layer=system, level=info}, the message will be discarded.

III. Practices

In the tutorial, we create 2 SpringBoot project as below:

springboot rabbitmq exchage headers - project structures

Step to do:
– Create SpringBoot projects
– Implement RabbitMq producer
– Implement RabbitMq consumer
– Run and check results

1. Create SpringBoot projects

Using SpringToolSuite, create 2 SpringBoot projects, then add need dependency spring-boot-starter-amqp:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2. Implement RabbitMq producer

2.1 Configure RabbitMq connection

Open application.properties file, add configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.exchange=jsa.exchange.logs.headers

2.2 Implement Producer


package com.javasampleapproach.rabbitmq.producer;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class Producer {
	
	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Value("${jsa.rabbitmq.exchange}")
	private String exchange;
	
	public void produce(Message message){
		
		/**
		 * void send(String exchange, String routingKey, Message message) throws AmqpException;
		 * routingKey is NOT need so we set it to an empty String.
		 * 
		 */
		amqpTemplate.send(exchange, "", message);
		System.out.println("Send msg = " + new String(message.getBody()));
	}
}

2.3 Implement Producer client


package com.javasampleapproach.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.javasampleapproach.rabbitmq.producer.Producer;


@SpringBootApplication
public class SpringRabbitMqProducerApplication  implements CommandLineRunner{

	public static void main(String[] args) {
		SpringApplication.run(SpringRabbitMqProducerApplication.class, args);
	}
	
	@Autowired
	Producer producer;

	@Override
	public void run(String... args) throws Exception {
		
		/**
		 *  message 1
		 *  
		 *  This message will be delivered to 2 queues
		 *  {
		 *  	jsa.queue.logs.all-sys-error
		 *  	jsa.queue.logs.any-app-error
		 *  }
		 */
		String systemErrorLog = "2017-10-10 10:57:51.10 ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]";
		Message sysErrMsg = MessageBuilder.withBody(systemErrorLog.getBytes())
											.setHeader("layer", "system")
											.setHeader("level", "error")
											.build();
		producer.produce(sysErrMsg);
		
		/**
		 *  message 2
		 *  
		 *  This message will be delivered to one queue: jsa.queue.logs.any-app-error
		 */
		String appErrorLog = "2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception";
		Message appErrMsg = MessageBuilder.withBody(appErrorLog.getBytes())
											.setHeader("layer", "application")
											.setHeader("level", "error")
											.build();
		producer.produce(appErrMsg);
		
		/**
		 *  message 3
		 *  
		 *  => This message will be discarded because it does NOT match with critical conditions of 2 queues 
		 *  {
		 *  	jsa.queue.logs.all-sys-error
		 *  	jsa.queue.logs.any-app-error
		 *  }
		 */
		String sysInfoLog = "2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52";
		Message sysInfoMsg = MessageBuilder.withBody(sysInfoLog.getBytes())
											.setHeader("layer", "system")
											.setHeader("level", "info")
											.build();
		producer.produce(sysInfoMsg);
	}
}

3. Implement RabbitMq consumer

3.1 Configure RabbitMq connection

Open application.properties file, add configuration:


spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
jsa.rabbitmq.queue=jsa.queue.logs.all-sys-error
#jsa.rabbitmq.queue=jsa.queue.logs.any-app-error

3.2 Implement Consumer


package com.javasampleapproach.rabbitmq.consumer;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Component
public class Consumer {
	
	@RabbitListener(queues="${jsa.rabbitmq.queue}")
    public void recievedMessage(byte[] log) {
        System.out.println("Recieved Message: " + new String(log));
    }
}

4. Run and check results

4.1 Setup RabbitMq exchange, queues

Enable rabbitmq_management by cmd: rabbitmq-plugins enable rabbitmq_management --online
Then go to: http://localhost:15672 -> login with user/password: guest/guest.

Add exchange:
Go to http://localhost:15672/#/exchanges, add exchange: jsa.exchange.logs.headers

springboot rabbitmq exchage headers - create exchange

Add queue:
Go to http://localhost:15672/#/queues, add 2 queues: jsa.queue.logs.all-sys-error, jsa.queue.logs.any-app-error.

springboot rabbitmq exchage headers - create queues

– Binding the queues with above exchange:

springboot rabbitmq exchage headers - binding queues with exchange

4.2 Run & check results

– Run SpringBootRabbitMqProducer with commandline mvn spring-boot:run,

-> Console’s logs:


Send msg = 2017-10-10 10:57:51.10 ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
Send msg = 2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception
Send msg = 2014-03-05 10:58:51.1  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52

-> See queues’ status:

springboot rabbitmq exchage headers - after sending messages

-> jsa.queue.logs.all-sys-error queue has 1 message:

get messages of jsa.queue.logs.all-sys-error

-> jsa.queue.logs.any-app-error queue has 2 messages:

get messages of jsa.queue.logs.any-app-error

– Run SpringBootRabbitMqConsumer which listen to jsa.queue.logs.all-sys-error queue with configuration: jsa.rabbitmq.queue=jsa.queue.logs.all-sys-error:

-> Console’s logs:


Recieved Message: 2017-10-10 10:57:51.10 ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]

– Run SpringBootRabbitMqConsumer which listen to jsa.queue.logs.any-app-error queue with configuration: jsa.rabbitmq.queue=jsa.queue.logs.any-app-error:

-> Console’s logs:


Recieved Message: 2017-10-10 10:57:51.10 ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
Recieved Message: 2017-10-10 10:57:51.112  ERROR java.lang.Exception: java.lang.Exception

IV. Sourcecode

SpringRabbitMqProducer
SpringRabbitMqConsumer

101 thoughts on “SpringBoot RabbitMq Headers Exchange”

  1. 490851 616005Considerably, the story is in reality the greatest on this noteworthy topic. I agree along with your conclusions and will eagerly watch forward to your next updates. Saying nice one will not just be sufficient, for the great clarity within your writing. I will immediately grab your rss feed to stay privy of any updates! 438421

  2. Hi there, I discovered your website via Google while searching for
    a related topic, your site came up, it seems to be good.
    I have bookmarked it in my google bookmarks.
    Hello there, simply turned into aware of your weblog thru Google, and found that it is truly informative.
    I am gonna be careful for brussels. I’ll appreciate should you proceed this in future.
    Lots of other people shall be benefited out of your writing.
    Cheers!

  3. First of all I want to say wonderful blog! I had a quick question that
    I’d like to ask if you do not mind. I was curious to find out
    how you center yourself and clear your head
    before writing. I’ve had a difficult time clearing my
    mind in getting my thoughts out there. I truly do take pleasure in writing
    but it just seems like the first 10 to 15 minutes tend to be wasted simply just trying to figure
    out how to begin. Any suggestions or tips? Appreciate it!

  4. What’s up every one, here every person is sharing such know-how, thus it’s good to
    read this blog, and I used to go to see this web site everyday.

  5. I think this website contains some real superb information for everyone :D. “Anybody who watches three games of football in a row should be declared brain dead.” by Erma Bombeck.

  6. You are my inhalation, I have few blogs and very sporadically run out from post :). “Yet do I fear thy nature It is too full o’ the milk of human kindness.” by William Shakespeare.

  7. I have not checked in here for a while since I thought it was getting boring, but the last few posts are great quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂

  8. hello!,I like your writing very much! share we keep up a correspondence more about your post on AOL? I need an expert in this house to unravel my problem. Maybe that is you! Taking a look forward to peer you.

  9. Hi, this weekend is pleasant designed for me, for the reason that this point in time i am reading this enormous educational article here at my
    house.

  10. Pretty great post. I just stumbled upon your weblog and wanted to mention that I
    have truly loved browsing your blog posts. In any case I will be subscribing to your feed and I hope you write again very soon!

  11. I’m not sure exactly why but this weblog is loading incredibly slow for me.Is anyone else having this issue or is it a problem on my end?I’ll check back later on and see if the problem still exists.

  12. My spouse and I stumbled over here from a different web address and thought I might as well
    check things out. I like what I see so now i am following you.
    Look forward to going over your web page yet again.

  13. Hi there everybody, here every person is sharing these kinds of experience, thus it’s good to read this blog,
    and I used to pay a quick visit this blog every day.

  14. Thank you for any other informative site. The place else could I
    am getting that kind of info written in such a perfect approach?

    I have a project that I am simply now running on, and I’ve been on the glance out for such information.

  15. Thank you for every other informative website. The place
    else could I get that kind of information written in such a perfect manner?
    I have a venture that I am just now operating on, and I’ve been at the look
    out for such information.

  16. Excellent article. Keep writing such kind of information on your page.Im really impressed by your blog.Hello there, You have done an incredible job. I’ll certainly digg it and in my view suggestto my friends. I’m confident they will be benefited fromthis site.

  17. Hello! I could have sworn I’ve been to this website before but after reading through some of the postI realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be bookmarking andchecking back often!

  18. Wow, wonderful blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your
    site is great, as well as the content!

  19. Aw, this was a really nice post. In idea I wish to put in writing like this moreover ?taking time and actual effort to make an excellent article?however what can I say?I procrastinate alot and on no account appear to get something done.

  20. I’m really impressed together with your writing abilities and also
    with the layout in your weblog. Is this a paid subject or did you modify it yourself?
    Anyway stay up the excellent quality writing, it’s uncommon to peer a great blog like this one
    these days..

  21. Excellent post. I was checking constantly this blog and I’m impressed!
    Extremely helpful information specially the last part
    🙂 I care for such info a lot. I was looking for this particular information for a very long time.

    Thank you and good luck.

  22. Hmm it appears like your blog ate my first comment (it was extremely long)
    so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog writer but I’m still new to
    the whole thing. Do you have any suggestions for novice blog writers?

    I’d genuinely appreciate it.

  23. continuously i used to read smaller content that as well clear their motive,
    and that is also happening with this piece of writing which I
    am reading at this time.

  24. Hello there! I could have sworn I’ve been to this site before but after browsing through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely delighted I found it and I’ll be book-marking
    and checking back often!

  25. you’re truly a good webmaster. The web site loading speed is
    amazing. It seems that you are doing any unique trick.

    In addition, The contents are masterwork. you have
    done a wonderful task in this subject!

  26. I have recently started a blog, the info you offer on this site has helped me greatly. Thanks for all of your time & work. “The inner fire is the most important thing mankind possesses.” by Edith Sodergran.

  27. Thank you for sharing excellent informations. Your website is very cool. I’m impressed by the details that you’ve on this web site. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found simply the information I already searched everywhere and simply couldn’t come across. What a great site.

  28. What i don’t realize is in truth how you are not really a lot more well-favored than you
    might be right now. You’re so intelligent. You realize therefore significantly relating to this
    topic, made me in my view imagine it from numerous numerous angles.

    Its like men and women are not fascinated
    except it’s one thing to do with Lady gaga! Your own stuffs nice.
    All the time handle it up!

  29. Your style is unique compared to other folks I have read stuff from.
    Many thanks for posting when you’ve got the opportunity,
    Guess I will just bookmark this site.

  30. I should say also believe that mesothelioma cancer is a uncommon form of cancer malignancy that is usually found in people previously familiar with asbestos. Cancerous tissue form inside the mesothelium, which is a shielding lining which covers the majority of the body’s areas. These cells normally form from the lining on the lungs, tummy, or the sac that encircles one’s heart. Thanks for giving your ideas.

  31. You made some really good points there. I looked on the internet to learn more about the
    issue and found most people will go along with your views on this website.

  32. Great stuff within you, guy. Ive read your own products prior to and you’re too amazing. I love what youve got the following, love what you are declaring and the way a person say it. You ensure it is entertaining and you still manage to ensure that it stays intelligent. I can’t hold out to learn a lot more of your stuff. This is often a fantastic blog.

  33. I just like the valuable information you provide for your
    articles. I will bookmark your blog and check again here regularly.
    I’m fairly certain I will be informed plenty of new stuff
    right here! Best of luck for the next!

  34. you are in reality a excellent webmaster. The website loading velocity is amazing. It seems that you are doing any unique trick. In addition, The contents are masterwork. you’ve done a excellent activity in this subject!

  35. Good – I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your client to communicate. Excellent task.

  36. Some moms know the great benefits of eating yoghurt because of the probiotics.
    The bacteria found in yoghurts at your local market are good but not great.

    More healthy yoghurts are available that produce gcmaf these are much better as gcmaf has more
    health benefits. These more specific types of probiotic yogurts
    usually contain 40 or more good probiotic bacteria, while shop yoghurts do are made with a much less number of bacteria
    such as 1 or 4 but are there for the flavour not always for the gcmaf production.

  37. Please let me know if you’re looking for a article writer for your site.
    You have some really great posts and I feel I would be a good asset.
    If you ever want to take some of the load off,
    I’d absolutely love to write some material for your blog in exchange for a link back
    to mine. Please send me an email if interested. Thanks!

  38. hello there and thank you for your info – I’ve certainly picked
    up anything new from right here. I did however expertise a few
    technical points using this site, as I experienced to reload the site many times previous to
    I could get it to load correctly. I had been wondering if your web host is OK?
    Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and can damage
    your high quality score if advertising and marketing with
    Adwords. Anyway I’m adding this RSS to my email and could
    look out for much more of your respective intriguing content.

    Make sure you update this again soon.

  39. Hello there, just became alert to your blog
    through Google, and found that it’s truly informative.
    I’m going to watch out for brussels. I will be grateful if you
    continue this in future. Many people will be benefited from your writing.
    Cheers!

  40. What i do not understood is in fact how you’re now not actually a lot more neatly-liked than you might be now. You are very intelligent. You already know therefore considerably on the subject of this subject, produced me in my opinion believe it from numerous various angles. Its like women and men aren’t involved until it’s something to do with Girl gaga! Your individual stuffs outstanding. At all times care for it up!

  41. Hello, Neat post. There is an issue with your site in web explorer, may check this… IE nonetheless is the market chief and a good element of people will pass over your fantastic writing due to this problem.

  42. Very nice post. I just stumbled upon your weblog and wished
    to say that I’ve really enjoyed surfing around your blog posts.
    In any case I’ll be subscribing to your rss feed and I hope you write again very soon!

  43. I’m really impressed with your writing skills and also with the layout on your weblog.
    Is this a paid theme or did you customize it yourself? Anyway keep up the nice quality writing, it’s rare to see a nice blog like this one
    today.

  44. I have been surfing online greater than 3 hours as of late, but I never discovered any fascinating article like yours.
    It is beautiful price enough for me. Personally, if all
    site owners and bloggers made excellent content as you probably did, the internet shall be a lot more useful
    than ever before.

  45. Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the
    shell to her ear and screamed. There was a hermit crab inside and it pinched
    her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  46. Howdy would you mind sharing which blog platform you’re working with?

    I’m going to start my own blog in the near future but I’m having a difficult time making a decision between BlogEngine/Wordpress/B2evolution and
    Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something
    completely unique. P.S Sorry for getting off-topic but I had to
    ask!

  47. Hi! Would you mind if I share your blog with my twitter group?
    There’s a lot of folks that I think would really appreciate
    your content. Please let me know. Many thanks

  48. Hi there to every body, it’s my first pay a quick visit of this web site; this weblog contains awesome and
    in fact excellent information in support of visitors.

  49. I have been absent for a while, but now I remember why I used to love this web site. Thanks, I will try and check back more often. How frequently you update your site?

  50. I haven’t checked in here for some time because I thought it was getting boring, but the last several posts are great quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂

  51. Pretty section of content. I just stumbled upon your website
    and in accession capital to assert that I acquire actually enjoyed account your blog posts.
    Anyway I’ll be subscribing to your feeds and even I achievement you access consistently fast.

  52. I blog quite often and I seriously thank you for your content.
    The article has really peaked my interest. I’m going to take
    a note of your blog and keep checking for new information about once a week.
    I subscribed to your RSS feed too.

  53. Hey, you used to write great, but the last few posts have been kinda boring… I miss your tremendous writings. Past few posts are just a bit out of track! come on!

  54. Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you!
    However, how can we communicate?

  55. obviously like your web site but you need to take a
    look at the spelling on quite a few of your posts. Several of them are
    rife with spelling problems and I in finding it very troublesome to tell the reality
    on the other hand I’ll definitely come back again.

  56. I’m really impressed with your writing skills and also
    with the layout on your blog. Is this a paid theme or did you
    modify it yourself? Either way keep up the nice quality
    writing, it’s rare to see a nice blog like this one these days.

  57. I all the time emailed this website post page to all my
    contacts, for the reason that if like to read it then my friends will too.

  58. Thank you for helping out, wonderful info. “Our individual lives cannot, generally, be works of art unless the social order is also.” by Charles Horton Cooley.

Leave a Reply

Your email address will not be published. Required fields are marked *