Saturday, July 5, 2014

Implementing a Distributed Counter Service Using Hazelcast, Jersey 2 and Guice

Modern web services are often required to scale horizontally in order to handle growing load.
Here I present an example distributed Counter service, which uses modern technology stack consisting of Hazelcast, Jersey 2 and Guice.

The sample is based on an excellent example posted by Piersy and can be downloaded from here:
http://github.com/rafalrusin/jersey2-guice-example-with-test

The counter is just a shared value across all participating nodes within a cluster. All nodes can query for data and increase it's value by specified delta. Note that Hazelcast handles synchronization within distributed environment. In order to update the state atomically, we use Hazelcast EntryProcessor.

@Singleton
public class CounterService {

    public int increase(final int delta) {
        return (Integer) map.executeOnKey("counterKey", new CounterEntryProcessor(delta));
    }
}

public class CounterEntryProcessor implements EntryProcessor<String, Integer>, EntryBackupProcessor<String, Integer> {
    private final int delta;

    public CounterEntryProcessor(int delta) {
        this.delta = delta;
    }

    @Override
    public Integer process(Map.Entry<String, Integer> entry) {
        int newValue = entry.getValue() + delta;
        entry.setValue(newValue);
        return newValue;
    }
}

The service is just a Guice Singleton. It has an operation called 'increase', which takes a delta and creates EntryProcessor job for Hazelcast to submit to a node, which owns the value at the time and will update it atomically.
Hazelcast is a library, which implements Java Collections in distributed fashion. It handles replication, cluster membership and distributed locking.

Web service is a simple JAXRS REST Resource. Following code invokes Guice service layer from Resouce implementation:

@RequestScoped
@Path("counter")
public class CounterResource {

    private CounterService service;

    @Inject
    public CounterResource(CounterService service) {
        this.service = service;
    }

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    public String increase(String delta) {
        return "" + service.increase(Integer.parseInt(delta));
    }
}

We also have a test case, which invokes the whole stack and does a request to the service. The whole stack is very lightweight. In runs on Jersey with Embedded Tomcat. The test case completes within a few seconds.

In order to run the example, you need to build distribution first (run dist.sh), then start nodes in separate shells and invoke curl POST requests to manipulate counter state. Here's a sample interaction:

./run.sh 8090
./run.sh 8092
...
Jul 05, 2014 10:20:06 AM com.hazelcast.cluster.ClusterService
INFO: [10.0.0.12]:5702 [dev] [3.2.3]

Members [2] {
        Member [10.0.0.12]:5701
        Member [10.0.0.12]:5702 this
}

Jul 05, 2014 10:20:08 AM com.hazelcast.core.LifecycleService
INFO: [10.0.0.12]:5702 [dev] [3.2.3] Address[10.0.0.12]:5702 is STARTED
...

$ curl -d '1' -H 'Content-Type: text/plain;' http://localhost:8092/webapp/api/counter
22
$ curl -d '1' -H 'Content-Type: text/plain;' http://localhost:8090/webapp/api/counter
23
$ curl -d '5' -H 'Content-Type: text/plain;' http://localhost:8090/webapp/api/counter
28

I think that Hazelcast is a very good step forward into distributed computing. For an every day programmer, it's a set of primitives to manipulate in order to implement a distributed system. It is very easy to integrate it into existing project, which could be either JavaEE or standalone app.

112 comments:

  1. Thank you for such a fantastic blog. Where else could anyone get that kind of info written in such a perfect way? I have a presentation that I am presently working on, and I have been on the lookout for such information.
    corporate wear and uniforms

    ReplyDelete
  2. I prefer to study this kind of material. Nicely written information in this post, the quality of content is fine and the conclusion is lovely. Things are very open and intensely clear explanation of issues
    Data Science Training in Indira nagar
    Data Science Training in btm layout
    Python Training in Kalyan nagar
    Data Science training in Indira nagar
    Data Science Training in Marathahalli | Data Science training in Bangalore

    ReplyDelete
  3. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.
    AWS Training in Marathahalli | Best AWS Training in Bangalore
    Amazon Web Services Training in Chennai | No.1 AWS Training for Solution Architect in Chennai
    Amazon Web Services Training in Pune | Best AWS Training in Pune

    ReplyDelete
  4. I believe that your blog will surely help the readers who are really in need of this vital piece of information. Waiting for your updates.
    honor mobile service centre
    honor service center chennai
    honor service center in chennai

    ReplyDelete
  5. For Devops training in Bangalore Visit:
    Devops training in Bangalore

    ReplyDelete
  6. Such a great information for blogger i am a professional blogger thanks…

    Get Best SAP HR HCM Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.

    ReplyDelete
  7. Such a great word which you use in your article and article is amazing knowledge. thank you for sharing it.

    Looking for SAP S4 HANA Simple Logistics Training in Bangalore , learn from eTechno Soft Solutions SAP S4 HANA Simple Logistics Training on online training and classroom training. Join today!

    ReplyDelete
  8. Learned a lot of new things from your post! Good creation and HATS OFF to the creativity of your mind.Hadoop Training in Bangalore

    ReplyDelete
  9. I really impressed to visit your great blog. Thank you for sharing with us...
    Informatica Training in Bangalore
    Informatica Bangalore

    ReplyDelete
  10. I enjoyed by reading your blog post. Your blog gives us information that is very useful for us, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again.



    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery


    ReplyDelete
  11. If people that write articles cared more about writing great material like you, more readers would read their content. It's refreshing to find such original content in an otherwise copy-cat world. Thank you so much.
    Best Data Science training in Mumbai

    Data Science training in Mumbai

    ReplyDelete
  12. I like how this article is written. Your points are sound, original, fresh and interesting. This information has been made so clear there's no way to misunderstand it. Thank you.
    SAP training in Kolkata
    SAP training Kolkata
    Best SAP training in Kolkata
    SAP course in Kolkata
    SAP training institute Kolkata

    ReplyDelete
  13. This all came together as a dialogue between Merlin and Arthur and, with some literary license, the subjects fit neatly into the four Ancient Elements. machine learning training in hyderabad

    ReplyDelete
  14. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

    MongoDB Online Training

    MongoDB Classes Online

    MongoDB Training Online

    Online MongoDB Course

    MongoDB Course Online

    ReplyDelete
  15. A debt of gratitude is in order for sharing the information, keep doing awesome... I truly delighted in investigating your site. great asset...

    Data Science Course

    ReplyDelete
  16. I have a mission that I’m just now working on, and I have been at the look out for such information.

    Data Science Training

    ReplyDelete
  17. This material makes for great reading. It's full of useful information that's interesting,well-presented and easy to understand. I like articles that are well done.
    SAP training in Kolkata
    SAP training Kolkata
    Best SAP training in Kolkata
    SAP course in Kolkata

    ReplyDelete
  18. Thank you for your attention to detail and great writing style. Your professionalism shows in your article. I like your interesting views and appreciate your unique ideas. This is quality.
    Data Science training in Mumbai
    Data Science course in Mumbai
    SAP training in Mumbai

    ReplyDelete
  19. Thank you for your attention to detail and great writing style. Your professionalism shows in your article. I like your interesting views and appreciate your unique ideas. This is quality.


    AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training

    ReplyDelete
  20. Honestly speaking this blog is absolutely amazing in learning the subject that is building up the knowledge of every individual and enlarging to develop the skills which can be applied in to practical one. Finally, thanking the blogger to launch more further too.

    Data Science training

    ReplyDelete
  21. Speaking honestly this blog is absolutely amazing in learning the subject that is building up the knowledge of every individual and enlarging to develop the skills which can be applied in to practical one. Finally, thanking the blogger to launch more further too.

    Data Science training in Bhilai

    ReplyDelete
  22. Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

    Digital Marketing training

    ReplyDelete
  23. First You got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks.
    Best Data Science Courses in Hyderabad

    ReplyDelete
  24. I feel a lot more people need to read this, very good info!. ExcelR Data Analytics Course

    ReplyDelete
  25. Really, this article is truly one of the best, information shared was valuable and resourceful Very good work thank you.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  26. I like this post and there is obviously a lot to know about this. I think you made some good points in Features also i figure that they having a great time to peruse this post. They might take a decent site to make an information, thanks for sharing it to me Keep working, great job!
    Braces in Bangalore

    ReplyDelete

  27. I finally found a great article here with valuable information and just added your blog to my bookmarking sites thank you.
    Data Science Course in Bangalore

    ReplyDelete
  28. Very awesome!!! When I searched for this I found this website at the top of all blogs in search engines
    business analytics course

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ...
    Data Analytics Courses in Bangalore

    ReplyDelete
  31. First of all, you have a great blog. I will be interested in more similar topics. I see you have some very useful topics, I will always check your blog thank you.
    Data Science In Bangalore

    ReplyDelete
  32. Well done for this excellent article. I really enjoyed reading this article today and think it might be one of the best articles I have read so far. Please keep this work of the same quality.

    Data Science Institute in Bangalore

    ReplyDelete
  33. Really, this article is truly one of the best in article history. I am a collector of old "items" and sometimes read new items if I find them interesting. And this one that I found quite fascinating and should be part of my collection. Very good work!
    Data Science Institute in Bangalore

    ReplyDelete
  34. He's really nice and mean. it's a really cool blog. The link is a very useful thing. You have really helped a lot of people who visit the blog and give them useful information.
    Data Analytics Courses in Bangalore

    ReplyDelete
  35. It's good to visit your blog again, it's been months for me. Well, this article that I have been waiting for so long. I will need this post to complete my college homework, and it has the exact same topic with your article. Thanks, have a good game.
    Data Science Training in Pune

    ReplyDelete
  36. I think I actually have never seen such blogs ever before that has complete things with all details that i would like. therefore kindly update this ever for us.
    data scientist certification

    ReplyDelete
  37. Even if you are armed with an abundance of knowledge in SEO, you may still need the services of a professional SEO company. Having strong knowledge of SEO is hardly sufficient in some cases. 2000 Backlink at cheapest
    5000 Backlink at cheapest
    Boost DA upto 15+ at cheapest
    Boost DA upto 25+ at cheapest
    Boost DA upto 35+ at cheapest
    Boost DA upto 45+ at cheapest
    Even if you are doing your best to attempt to obtain a good ranking for your website, you might still wind up wondering why your website is simply not doing well.

    ReplyDelete


  38. Very awesome!!! When I searched for this I found this website at the top of all blogs in search engines.

    Data Science Training in Hyderabad


    ReplyDelete
  39. Hey Nice Blog!! Thanks For Sharing!!! Wonderful blog & good post. Its really helpful for me. If you want to learn Digital Marketing, then attend Free Digital Marketing Seminar in Gurgaon. 99 Digital Academy is the best Training Institute for Learning Digital Marketing. Join Today.

    ReplyDelete
  40. It is always so interesting to visit your site. What a great information, thanks for sharing. it will help me a lot in my learning.

    Best Data Science Courses in Bangalore

    ReplyDelete
  41. wow ... what a great blog, this writer who wrote this article is really a great blogger, this article inspires me so much to be a better person.
    Data Analytics Course in Bangalore

    ReplyDelete
  42. So luck to come across your excellent blog. Your blog brings me a great deal of fun.. Good luck with the site.
    data scientist training in hyderabad

    ReplyDelete
  43. I have expressed a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…

    best data science institute in hyderabad

    ReplyDelete
  44. Really nice and informative blog, keep it up. Thanks for sharing and I have some suggestions.
    Click Here For Visit My Site thanks .

    ReplyDelete
  45. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
    business analytics course


    ReplyDelete
  46. What an incredible message this is. Truly one of the best posts I have ever seen in my life. Wow, keep it up.
    Best Data Science Courses in Bangalore

    ReplyDelete
  47. It took a while to understand all the comments, but I really enjoyed the article. It turned out to be really helpful for me and I'm positive for all the reviewers here! It's always nice to be able to not only be informed, but also entertained! I'm sure you enjoyed writing this article.
    Data Analytics Course in Bangalore

    ReplyDelete
  48. I read that Post and got it fine and informative. Please share more like that...
    Best Data Science courses in Hyderabad

    ReplyDelete
  49. https://360digitmg.com/india/data-science-using-python-and-r-programming-bangalore
    I am a new user of this site, so here I saw several articles and posts published on this site, I am more interested in some of them, hope you will provide more information on these topics in your next articles.
    Data Science Training in Bangalore

    ReplyDelete
  50. Thank you for your blog , it was usefull and informative "AchieversIT is the best Training institute for Full Stack development training. Full Stack developement training in bangalore "

    ReplyDelete
  51. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    DevOps Training in Hyderabad
    DevOps Course in Hyderabad

    ReplyDelete
  52. I bookmarked your website because this site contains valuable information. I am very satisfied with the quality and the presentation of the articles. Thank you so much for saving great things. I am very grateful for this site.
    Business Analytics Course

    ReplyDelete
  53. I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ...

    Digital Marketing Training in Bangalore


    ReplyDelete
  54. The Web basics for Digital Marketing will be discussed in this chapter.



    We being digital marketers, we are expected to have strong web basics for digital marketing.

    ReplyDelete
  55. I am overwhelmed by your post with such a beautiful subject. I usually visit their blogs and update myself through the information they contain, but today's blog would be most appreciated. Well done!
    Best Data Science Courses in Bangalore

    ReplyDelete
  56. A great website with interesting and unique material what else would you need.
    data science training

    ReplyDelete
  57. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
    data science course in malaysia

    ReplyDelete
  58. Well we really like to visit this site, many useful information we can get here.
    data scientist training in malaysia

    ReplyDelete
  59. Thanks for posting the best information and the blog is very good and the.Cloud Computing course in Bangalore

    ReplyDelete
  60. It's like you've got the point right, but forgot to include your readers. Maybe you should think about it from different angles.

    Best Data Science Courses in Bangalore

    ReplyDelete

  61. Very good message. I came across your blog and wanted to tell you that I really enjoyed reading your articles.
    Data Analytics Course in Bangalore

    ReplyDelete
  62. Very awesome!!! When I seek for this I found this website at the top of all blogs in search engine.
    data science course

    ReplyDelete
  63. You have completed certain reliable points there. I did some research on the subject and found that almost everyone will agree with your blog.

    Cloud Computing Certification in Bangalore

    ReplyDelete


  64. I am impressed by the information that you have on this blog. It shows how well you understand this subject. ethical hacking course fees in jaipur


    ReplyDelete
  65. Thank a lot. You have done excellent job. I enjoyed your blog . Nice efforts
    data science course

    ReplyDelete
  66. It's like you've got the point right, but forgot to include your readers. Maybe you should think about it from different angles.

    Best Ethical Hacking Institute in Bangalore

    ReplyDelete
  67. You should be a part of a contest for one of the highest quality sites online. I will highly recommend this website! Feel free to visit my website; 온라인카지노

    ReplyDelete
  68. Truly, this article is really one of the very best in the history of articles. I am an antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work!
    data science institutes in hyderabad

    ReplyDelete
  69. It's like you've got the point right, but forgot to include your readers. Maybe you should think about it from different angles.
    Data Analytics Course in Bangalore

    ReplyDelete
  70. This is also a primarily fantastic distribute which I really specialized confirming out data science training in gurgaon

    ReplyDelete
  71. I’ve been browsing on-line greater than 3 hours as of late, but I by no means found any attention-grabbing article like yours. It’s pretty value sufficient for me. In my view, if all web owners and bloggers made just right content material as you did, the web can be a lot more useful than ever before. data science course in delhi with placement

    ReplyDelete
  72. I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Good day! data scientist course in kanpur

    ReplyDelete
  73. Really, this article is truly one of the best in article history. I am a collector of old "items" and sometimes read new items if I find them interesting. And this one that I found quite fascinating and should be part of my collection. Very good work!

    Data Scientist Training in Bangalore

    ReplyDelete
  74. Very informative message! There is so much information here that can help any business start a successful social media campaign!


    Data Science Course in Nashik

    ReplyDelete
  75. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one.
    cyber security course in malaysia

    ReplyDelete
  76. Great to become visiting your weblog once more, it has been a very long time for me. Pleasantly this article i've been sat tight for such a long time. I will require this post to add up to my task in the school, and it has identical subject along with your review. Much appreciated, great offer.. data analytics course

    ReplyDelete
  77. 360DigiTMG is the most recommended Data Science course institute in Chennai. Get trained by top professionals from IIT, IIM and, ISB. Enroll now!
    business analytics course in bhubaneswar

    ReplyDelete
  78. Data scientists must strive “massive knowledge expeditions” to discover the data for previously undiscovered worth – the first common software of data science and big knowledge analytics.

    Data Science Course in Bangalore with Placement

    ReplyDelete
  79. The increase in big data has led to a boom in the field of Data Science spiking ample career opportunities. Enroll in the Data Science training in Bangalore and invest in emerging skills and transform any business by wrangling, analyzing, and visualizing data. Give your career a makeover and gain in-depth knowledge on how to extract valuable insights from complex and large sets of data. Get to work on a live project which is designed to give hands-on experience to you along with career guidance and mentorship.

    Data Science in Bangalore

    ReplyDelete
  80. Start your career preparation with the best Data Science courses offered by 360DigiTMG. Aworld-class curriculum, LMS Access, assignments, and real-time project to grab a high-paying job.
    business analytics course in borivali

    ReplyDelete
  81. This comment has been removed by the author.

    ReplyDelete
  82. This comment has been removed by the author.

    ReplyDelete
  83. My Lear Nest Training Academy is one of the best SAP HCM course which is located in Hyderabad KPHB and the training which they provide is very good and they make it easy to learn. They will clear all your doubts as soon as possible. classes will be scheduled on time and trainers are very punctual.

    ReplyDelete
  84. Thanks for sharing I am very Happy to read this very useful post
    Best Junior Colleges in Hyderabad for CEC

    ReplyDelete
  85. Nice Article Thanks for Sharing it was really helpful for me

    Best CA Coaching in Hyderabad

    ReplyDelete
  86. This was a nice blog. I am very impressed with your post because this post is very helpful to me, Thanks for sharing this post.

    Best Junior Colleges in Hyderabad for CEC

    ReplyDelete
  87. Thanks for posting the best information and the blog is very good

    AI Training in Hyderabad

    ReplyDelete
  88. There are some fascinating cut-off dates in this article however I don’t know if I see all of them heart to heart. There’s some validity but I will take hold opinion until I look into it further. Good article , thanks and we wish extra! Added to FeedBurner as well roof cleaning service

    ReplyDelete
  89. This is my first-time i visit here. I found a multitude of entertaining stuff as part of your blog, especially its discourse. From the tons of comments on the posts, I guess I am not the only one having most of the enjoyment the following! Keep in the excellent job. Cheap Movers Victorville, California Near Me | Victorville Cheap Moving Companies - Three Movers

    ReplyDelete
  90. Amazing this hit it at the dot we will post to Bebo and also Fb Город Электросталь активно застраивается | Профессиональные новости | ООО “Белго+” – Двери производства Белоруси. Продажа, установка was great instagram pro 2

    ReplyDelete
  91. How much of an significant content, keep on penning significant other bhutan teer result

    ReplyDelete
  92. Simply a smiling visitor here to share the love (:, btw great pattern . Canon 6 Liter Instant Gas Geyser 16D-Plus Dual

    ReplyDelete
  93. The search for the best AI essay writer is a journey towards efficiency and excellence, where technology complements and enhances our writing capabilities. gpt essay generator

    ReplyDelete