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.
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:
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
– Add queue:
Go to http://localhost:15672/#/queues
, add 2 queues: jsa.queue.logs.all-sys-error
, jsa.queue.logs.any-app-error
.
– Binding the queues with above 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:
-> jsa.queue.logs.all-sys-error
queue has 1 message:
-> jsa.queue.logs.any-app-error
queue has 2 messages:
– 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
Best view i have ever seen !
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
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!
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!
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.
{
Post writing is also a fun, if you be familiar with after that you can write otherwise it is complicated to write.|
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.
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.
Hi my family member! I want to say that this article is awesome, nice written and include approximately all significant infos. I would like to see extra posts like this.
Hey, you used to write magnificent, but the last few posts have been kinda boring… I miss your tremendous writings. Past several posts are just a bit out of track! come on!
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 🙂
Enjoyed examining this, very good stuff, appreciate it. “What the United States does best is to understand itself. What it does worst is understand others.” by Carlos Fuentes.
Keep up the excellent work , I read few articles on this website and I believe that your website is rattling interesting and has got bands of superb info .
I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thanks again!
You are my inhalation , I possess few web logs and infrequently run out from to brand.
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.
I was reading through some of your blog posts on this internet site and I believe this website is really informative ! Retain putting up.
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.
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!
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.
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.
Amazing! Its actually remarkable piece of writing, I havegot much clear idea regarding from this piece of writing.
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.
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.
Your means of describing the whole thing in this post is in fact pleasant, every one be capable of effortlessly know it, Thanks a lot.
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.
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.
I have read so many articles concerning the blogger lovers however this paragraph
is really a fastidious paragraph, keep it up.
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!
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!
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.
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..
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.
You can certainly see your enthusiasm in the work you write.
The sector hopes for more passionate writers like you who aren’t afraid to say how
they believe. At all times go after your heart.
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.
Hi there mates, fastidious post and pleasant arguments commented here, I am actually enjoying by these.
Helpful information. Fortunate me I discovered your website by accident, and I am surprised why this
accident did not took place earlier! I bookmarked it.
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.
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!
Your method of telling everything in this post is genuinely nice,
all be able to simply be aware of it, Thanks a lot.
This is a topic which is close to my heart… Best wishes!
Exactly where are your contact details though?
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!
Baccarat und Blackjack sind Karte Aktivitäten, wo
einzigartige Fakten sehr wichtig, und Einsätze werden positioniert als jedes Palme
ist arbeitet.
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.
I view something truly special in this site.
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.
This has become a very special place in my heart. I have made many
friends and hope to continue the road of recovery after
I leave here.
Inspiring quest there. What happened after? Good luck!
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!
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.
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.
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.
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.
Hey, what kind of anti-spam plugin do you use for your blog..:~;-
Very interesting information!Perfect just what I was searching for! “The only gift is a portion of thyself.” by Ralph Waldo Emerson.
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!
I love reading a post that will make men and women think. Also, many thanks for allowing me
to comment!
You can definitely see your enthusiasm within the article you
write. The world hopes for even more passionate writers
like you who aren’t afraid to mention how they believe.
Always follow your heart.
Hmm is anyone else encountering problems with the images
on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog.
Any suggestions would be greatly appreciated.
Asking questions are really fastidious thing if you
are not understanding something completely, however this paragraph provides good understanding yet.
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!
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.
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.
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!
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.
Hi i am kavin, its my first time to commenting anyplace,
when i read this post i thought i could also create comment due to this sensible paragraph.
Marvelous, what a web site it is! This website presents useful data to us, keep it up.
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!
867595 235077I conceive this website has got some real excellent info for everyone : D. 578317
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!
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.
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!
What a stuff of un-ambiguity and preserveness of valuable know-how on the topic of unexpected emotions.
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.
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.
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!
I get pleasure from, result in I found just what I used to be having a look
for. You have ended my four day long hunt!
God Bless you man. Have a great day. Bye
My family always say that I am wasting my time here at web, except I know I am
getting familiarity daily by reading such fastidious articles or reviews.
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!
I am regular visitor, how are you everybody?
This article posted at this web page is in fact good.
Hello my friend! I wish to say that this article is amazing, great written and include almost all significant infos. I’d like to look more posts like this.
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
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.
Merely wanna input on few general things, The website layout is perfect, the content is real excellent : D.
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?
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 🙂
It’s not my first time to pay a quick visit this web site,
i am visiting this web site dailly and get pleasant data from here every day.
obviously like your web site but you need to take a look at
the spelling on several of your posts. Several of them are rife with
spelling issues and I in finding it very bothersome to inform the reality however I’ll
definitely come again again.
Quality articles is the crucial to invite the visitors to pay a
visit the web site, that’s what this web page is providing.
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.
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.
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!
excellent points altogether, you just received a emblem new reader. What may you recommend about your publish that you simply made some days ago? Any positive?
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?
Because the admin of this web page is working, no uncertainty very soon it will
be well-known, due to its feature contents.
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.
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.
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.
Hi there! Would you mind if I share your blog with my facebook group?
There’s a lot of folks that I think would really appreciate your content.
Please let me know. Many thanks
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.