SlideShare a Scribd company logo
Distributed Caching with
 Hazelcast + MongoDB
      at Cloud CMS
     Michael Uzquiano
      uzi@cloudcms.com
          @uzquiano
Agenda

• What is Cloud CMS?

• Why we chose MongoDB

• What is Hazelcast?

• Code Samples

• Implementation with MongoDB
http://www.cloudcms.com
• The fastest, easiest and most cost-effective way
  to build cloud-connected web and mobile
  applications.

• An application server in the cloud for cloud-
  connected applications

• Built to leverage the strengths of MongoDB

• Hosted or On-Premise
Mobile Apps
Touch Apps
Application Experiences
Consumer Experiences
Cloud CMS provides

• Content Management
• Users, Groups, Roles, Permissions
• Personalization (Behavioral Targeting)
• Analytics, Reporting
• Identity Management
• Integrated Services
• Email Campaigns, CRM, Integrated Billing
Silos
Keep things cost-effective
Mobile Ready
• iOS, Android, Windows Mobile

• JavaScript, Java, PHP, Ruby, Node.js

• jQuery, jQuery Mobile, Dojo, YUI,
  Sencha Touch, Titanium,
  PhoneGap
Hazelcast and MongoDB at Cloud CMS
The right tool for the job

• JSON

• Query and Indexing

• Doesn’t overstep into application domain
  • No transactions
  • No referential integrity
  • No triggers, foreign keys, procedures

• Gets out of the way so we can tackle these
Community + Momentum

• Really great language drivers

• Community contributors

• Frequent release schedule

• Exciting roadmap
Performance

• Very fast
  • Anywhere from 2 to 10x faster than MySQL
  • About 50 times faster than CouchDB
  • Lots of benchmarks but the point is, it’s fast!

• Sharding built-in, automatic, and *Just Works™
  • *Just Works™ guarantee applies only if you have a cluster of shard replica sets
    with config servers and routing servers and you define your own shard key(s) with
    appropriate uniformity and granularity


• Asynchronous replication for
  redundancy/failover
Hazelcast and MongoDB at Cloud CMS
What is Hazelcast?
• In-Memory Data Grid (IMDG)
• Clustering and highly scalable data distribution
  solution for Java
• Distributed Data Structures for Java
• Distributed Hashtable (DHT) and more
What does Hazelcast do?
•   Scale your application
•   Share data across cluster
•   Partition your data
•   Send/receive messages
•   Balance load across cluster
•   Process in parallel on many JVM
Advantages
• Open source (Apache License)
• Super light, simple, no-dependency
• Distributed/partitioned implementation of map,
  queue, set, list, lock and executor service
• Transactional (JCA support)
• Topic for pub/sub messaging
• Cluster info and membership events
• Dynamic clustering, backup, fail-over
Data Partitioning in a Cluster
 If you have 5 million objects in your 5-node cluster,
 then each node will carry
 1 million objects and 1 million backup objects.




Server1    Server2       Server3       Server4           Server5
SuperClient in a Cluster
          • -Dhazelcast.super.client=true
          • As fast as any member in the cluster
          • Holds no-data




Server1        Server2     Server3       Server4   Server5
Code Samples
Code Samples – Cluster Interface

importcom.hazelcast.core.*;
importjava.util.Set;

Cluster cluster = Hazelcast.getCluster();
cluster.addMembershipListener(listener);

Member localMember = cluster.getLocalMember();
System.out.println (localMember.getInetAddress());

Set setMembers   = cluster.getMembers();
Code Samples – Distributed Map

importcom.hazelcast.core.Hazelcast;
importjava.util.Map;

Map<String, User>map = Hazelcast.getMap(”users");

map.put ("1", user);

User user = map.get("1");
Code Samples – Distributed Queue

importcom.hazelcast.core.Hazelcast;
importjava.util.concurrent.BlockingQueue;
importjava.util.concurrent.TimeUnit;

BlockingQueue<Task>queue = Hazelcast.getQueue(“tasks");

queue.offer(task);

Task t = queue.poll();
Task t = queue.poll(5, TimeUnit.SECONDS);
Code Samples – Distributed Set

importcom.hazelcast.core.Hazelcast;
importjava.util.Set;

Set<Price>set= Hazelcast.getSet(“IBM-Quote-History");

set.add (new Price (10, time1));
set.add (new Price (11, time2));
set.add (new Price (13, time3));

for (Price price : set) {
// process price
}
Code Samples – Distributed Lock

importcom.hazelcast.core.Hazelcast;
importjava.util.concurrent.locks.Lock;

Lockmylock= Hazelcast.getLock(mylockobject);
mylock.lock();
try {
// do something
} finally {
mylock.unlock();
}
Code Samples – Distributed Topic

importcom.hazelcast.core.*;

public class Sample implements MessageListener {

    public static void main(String[] args) {
        Sample sample = new Sample();
        Topic topic = Hazelcast.getTopic ("default");
        topic.addMessageListener(sample);
        topic.publish ("my-message-object");
    }

    public void onMessage(Object msg) {
        System.out.println("Got msg :" + msg);
    }
}
Code Samples – Distributed Events
importcom.hazelcast.core.IMap;
importcom.hazelcast.core.Hazelcast;
importcom.hazelcast.core.EntryListener;
importcom.hazelcast.core.EntryEvent;

publicclassSampleimplementsEntryListener{
publicstaticvoidmain(String[]args){
        Sample sample =newSample();
      IMap    map   =Hazelcast.getMap("default");
      map.addEntryListener(sample,true);
      map.addEntryListener(sample,"key");
    }

 publicvoidentryAdded(EntryEventevent){
System.out.println("Added "+event.getKey()+":"+event.getValue());
  }

        publicvoidentryRemoved(EntryEventevent){
          System.out.println("Removed "+event.getKey()+":"+event.getValue());
    }

    publicvoidentryUpdated(EntryEventevent){
         System.out.println("Updated "+event.getKey()+":"+event.getValue());
     }
}
Code Samples – Executor Service

FutureTask<String>futureTask= new
DistributedTask<String>(new Echo(input), member);

ExecutorServicees=Hazelcast.getExecutorService();

es.execute(futureTask);

String result = futureTask.get();
Sample Configuration
<hazelcast>
         <group>
                   <name>dev</name>
                   <password>dev-pass</password>
         </group>
         <network>
                  <portauto-increment="true">5701</port>
                  <join>
                            <multicastenabled="true">
                                      <multicast-group>224.2.2.3</multicast-group>
                                      <multicast-port>54327</multicast-port>
                            </multicast>
                            <tcp-ipenabled="false">
                                      <interface>192.168.1.2-5</interface>
<hostname>istanbul.acme</hostname>
                            </tcp-ip>
                  </join>
                  <interfacesenabled="false">
                            <interface>10.3.17.*</interface>
                  </interfaces>
         </network>
         <executor-service>
                  <core-pool-size>16</core-pool-size>
                  <max-pool-size>64</max-pool-size>
                  <keep-alive-seconds>60</keep-alive-seconds>
         </executor-service>
         <queuename="tasks">
                  <max-size-per-jvm>10000</max-size-per-jvm>
         </queue>
</hazelcast>
Distributed Job Queue
      Elasticity with Cloud CMS
Distributed Job Queue
Distributed Job Queue

                     Upload of a 20 page PDF




    Write PDF to GridFS
    Add 2 jobs to Queue
    (each to build 10 pngs)
Distributed Job Queue

                     Upload of a 20 page PDF




    Write PDF to GridFS
    Add 2 jobs to Queue
    (each to build 10 pngs)
Distributed Job Queue

                     Upload of a 20 page PDF




    Write PDF to GridFS
    Add 2 jobs to Queue
    (each to build 10 pngs)
Distributed Job Queue

                     Upload of a 20 page PDF




    Write PDF to GridFS
    Add 2 jobs to Queue
    (each to build 10 pngs)
Distributed Job Queue


                                     Jobs may run asynchronously
                                     (returns once transaction complete)




Picks job from                                      Picks Job from
queue and works on it                               queue and works on it



                        Job Scheduler determines
                        which jobs get priority
Distributed Job Queue
Implementation with
     MongoDB
  com.hazelcast.core.MapStore
MapStore
public interface MapStore<K,V> extends MapLoader<K,V>
{
    void store(Kk, V v);
    void storeAll(Map<K,V>kvMap);
    void delete(Kk);
    void deleteAll(Collection<K>ks);
}

public interface MapLoader<K,V>
{
    V load(Kk);
    Map<K,V>loadAll(Collection<K>ks);
    Set<K>loadAllKeys();
}
MapLoaderLifecycleSupport
public interface MapLoaderLifecycleSupport
{
    void init(HazelcastInstancehazelcastInstance,
              Properties properties,
              String mapName);

    void destroy();
    Set<K>loadAllKeys();
}
public class MongoUsersMapStore
    implements MapStore, MapLoaderLifecycleSupport
{




}
public class MongoUsersMapStore
    implements MapStore, MapLoaderLifecycleSupport
{
    private Mongo mongo;
    private DBCollectioncol;

   public void init(HazelcastInstancehazelcastInstance,
             Properties properties, String mapName) {

this.mongo = new Mongo(“localhost”, 27017);

       String dbname = properties.get(“db”);
       String cname = properties.get(“collection”);

        DB db = this.mongo.getDB(dbname);
this.col = db.getCollection(cname);
    }
}
public class MongoUsersMapStore
    implements MapStore, MapLoaderLifecycleSupport
{
    private Mongo mongo;
    private DBCollectioncol;

    ...

    public void destroy() {
this.mongo.close();
    }

    public Set<K>loadAllKeys() {
        return null;
    }
}
public class MongoUsersMapStore
    implements MapStore, MapLoaderLifecycleSupport
{
    private Mongo mongo;
    private DBCollectioncol;

    ...

    public Set loadAllKeys() {
        Set keys = new HashSet();

BasicDBList fields = new BasicDBList();
fields.add(“_id”);

DBCursor cursor = this.col.find(null, fields);
        while (cursor.hasNext()) {
keys.add(cursor.next().get(“_id”));
        }

          return keys;
    }
}
public class MongoUsersMapStore
    implements MapStore, MapLoaderLifecycleSupport
{
    ...

    public void store(Kk, V v) {
DBObjectdbObject = convert(v);
dbObject.put(“_id”, k);

this.col.save(dbObject);
    }

    public void delete(Kk) {
DBObjectdbObject = new BasicDBObject();
dbObject.put(“_id”, k);

this.col.remove(dbObject);
    }
}
public class MongoUsersMapStore
    implements MapStore, MapLoaderLifecycleSupport
{
    ...

    public void storeAll(Map map) {
        for (Object key : map.keySet()) {
store(key, map.get(key));
        }
    }

    public void deleteAll(Collection keys) {
        for (Object key: keys) {
delete(key);
        }
    }
}
public class MongoUsersMapStore
    implements MapStore, MapLoaderLifecycleSupport
{
    ...

    public void storeAll(Map map) {
        for (Object key : map.keySet()) {
store(key, map.get(key));
        }
    }

    public void deleteAll(Collection keys) {
BasicDBListdbo = new BasicDBList();
        for (Object key : keys) {
dbo.add(newBasicDBObject("_id", key));
        }
BasicDBObjectdbb = new BasicDBObject("$or", dbo);
this.col.remove(dbb);
    }
}
Spring Config
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:hz="http://www.hazelcast.com/schema/spring">

<hz:hazelcast id="hzInstance”>
<hz:config>
<hz:map name=”users” backup-count="1"
                max-size="2000” eviction-percentage="25"
                eviction-policy="LRU"
                merge-policy="hz.LATEST_UPDATE">
<hz:map-store enabled="true"
                          write-delay-seconds="0"
                          implementation="mymap" />
</hz:map>
</hz:config>
</hz:hazelcast>

<bean id=”mymap” class="org.sample.MongoUsersMapStore" />
Implementation with
     MongoDB
  com.hazelcast.core.EntryListener
EntryListener
public interface EntryListener<K,V>
{
    void entryAdded(EntryEvent<K, V> event);
    void entryUpdated(EntryEvent<K, V> event);
    void entryRemoved(EntryEvent<K, V> event);
    void entryEvicted(EntryEvent<K, V> event);
}
EntryListener
public class UserCacheEntryListener<String, User>
{
    private Map<String, User> cache;

    public User getUser(String key) {
        return cache.get(key);
    }

    public void entryAdded(EntryEvent<String, User> event) {
cache.put(event.getKey(), event.getValue());
    }




}
EntryListener
Spring Framework

• Spring Data for MongoDB
     • http://www.springsource.org/spring-data/mongodb
     • com.hazelcast.spring.mongodb.MongoMapStore

• Based on Spring API Template pattern
 •    com.hazelcast.spring.mongodb.MongoTemplate


• Easy to get started, base implementation

• You still might want to roll your own
Questions?

• Michael Uzquiano
  • uzi@cloudcms.com
  • @uzquiano

• Cloud CMS
  • http://www.cloudcms.com
  • @cloudcms

• Hazelcast
  • http://www.hazelcast.com
  • https://github.com/hazelcast/hazelcast

More Related Content

PDF
Hazelcast
PDF
[263] s2graph large-scale-graph-database-with-hbase-2
PDF
Practicing Continuous Deployment
PDF
Async and Non-blocking IO w/ JRuby
KEY
What is the ServiceStack?
PDF
Scaling Hibernate with Terracotta
PDF
Cassandra summit 2013 - DataStax Java Driver Unleashed!
PDF
Scalable XQuery Processing with Zorba on top of MongoDB
Hazelcast
[263] s2graph large-scale-graph-database-with-hbase-2
Practicing Continuous Deployment
Async and Non-blocking IO w/ JRuby
What is the ServiceStack?
Scaling Hibernate with Terracotta
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Scalable XQuery Processing with Zorba on top of MongoDB

What's hot (19)

PDF
Requery overview
PDF
Cutting Edge Data Processing with PHP & XQuery
PDF
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
PPTX
Python database interfaces
PPTX
Protect your app from Outages
PDF
[245] presto 내부구조 파헤치기
KEY
What is the ServiceStack?
PDF
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
PDF
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
PPTX
Volodymyr Lyubinets "Introduction to big data processing with Apache Spark"
PDF
Bulk Loading into Cassandra
PDF
Bulk Loading Data into Cassandra
KEY
What istheservicestack
PPTX
PPTX
C#을 이용한 task 병렬화와 비동기 패턴
PDF
Apache Zookeeper
PDF
Managing user's data with Spring Session
PDF
MongoDB as Message Queue
PDF
Webinar: Was ist neu in MongoDB 2.4
Requery overview
Cutting Edge Data Processing with PHP & XQuery
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Python database interfaces
Protect your app from Outages
[245] presto 내부구조 파헤치기
What is the ServiceStack?
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
Volodymyr Lyubinets "Introduction to big data processing with Apache Spark"
Bulk Loading into Cassandra
Bulk Loading Data into Cassandra
What istheservicestack
C#을 이용한 task 병렬화와 비동기 패턴
Apache Zookeeper
Managing user's data with Spring Session
MongoDB as Message Queue
Webinar: Was ist neu in MongoDB 2.4
Ad

Viewers also liked (20)

PDF
Phoenix for Rubyists
PDF
Async Gateway или Разработка системы распределенных вычислений с нуля
PPT
HighLoad++ 2009 In-Memory Data Grids
PDF
50 nouvelles choses que l'on peut faire en Java 8
PDF
Алексей Николаенков, Devexperts
PDF
Hazelcast for Terracotta Users
PDF
Amazon cloud – готовим вместе
PPTX
Code review at large scale
PDF
50 new things we can do with Java 8
PPTX
JFokus 50 new things with java 8
PDF
ЖК Зорге 9
PPTX
Gamification in outsourcing company: experience report.
PPTX
Java 8, the Good, the Bad and the Ugly
PDF
Очень вкусный фрукт Guava
PDF
ArrayList et LinkedList sont dans un bateau
PPTX
Hibernate performance tuning
PDF
Going reactive in java
PPTX
Hazelcast Deep Dive (Paris JUG-2)
PPTX
Maven 3 : уличная магия
PDF
Free your lambdas
Phoenix for Rubyists
Async Gateway или Разработка системы распределенных вычислений с нуля
HighLoad++ 2009 In-Memory Data Grids
50 nouvelles choses que l'on peut faire en Java 8
Алексей Николаенков, Devexperts
Hazelcast for Terracotta Users
Amazon cloud – готовим вместе
Code review at large scale
50 new things we can do with Java 8
JFokus 50 new things with java 8
ЖК Зорге 9
Gamification in outsourcing company: experience report.
Java 8, the Good, the Bad and the Ugly
Очень вкусный фрукт Guava
ArrayList et LinkedList sont dans un bateau
Hibernate performance tuning
Going reactive in java
Hazelcast Deep Dive (Paris JUG-2)
Maven 3 : уличная магия
Free your lambdas
Ad

Similar to Hazelcast and MongoDB at Cloud CMS (20)

PPTX
Distributed in memory data grid
PDF
Clustering your Application with Hazelcast
PPT
Hazelcast
PDF
Easy Scaling with Open Source Data Structures, by Talip Ozturk
PPTX
Think Distributed: The Hazelcast Way
PDF
Building scalable applications with hazelcast
PDF
Building scalable applications with hazelcast
PPTX
Hazelcast Essentials
PPTX
Distributed caching and computing v3.7
PDF
Hazelcast 101
PPTX
Distributed caching-computing v3.8
PDF
Support distributed computing and caching avec hazelcast
PPTX
Hazelcast
PDF
Where is my cache architectural patterns for caching microservices by example
PDF
Where is my cache architectural patterns for caching microservices by example
PDF
Where is my cache? Architectural patterns for caching microservices by example
PDF
Web session replication with Hazelcast
PDF
Where is my cache? Architectural patterns for caching microservices by example
PDF
Where is my cache? Architectural patterns for caching microservices by example
PDF
Architectural patterns for high performance microservices in kubernetes
Distributed in memory data grid
Clustering your Application with Hazelcast
Hazelcast
Easy Scaling with Open Source Data Structures, by Talip Ozturk
Think Distributed: The Hazelcast Way
Building scalable applications with hazelcast
Building scalable applications with hazelcast
Hazelcast Essentials
Distributed caching and computing v3.7
Hazelcast 101
Distributed caching-computing v3.8
Support distributed computing and caching avec hazelcast
Hazelcast
Where is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by example
Where is my cache? Architectural patterns for caching microservices by example
Web session replication with Hazelcast
Where is my cache? Architectural patterns for caching microservices by example
Where is my cache? Architectural patterns for caching microservices by example
Architectural patterns for high performance microservices in kubernetes

Recently uploaded (20)

PPTX
Tartificialntelligence_presentation.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Empathic Computing: Creating Shared Understanding
PDF
Getting Started with Data Integration: FME Form 101
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
Machine Learning_overview_presentation.pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
1. Introduction to Computer Programming.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Approach and Philosophy of On baking technology
Tartificialntelligence_presentation.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Spectroscopy.pptx food analysis technology
Empathic Computing: Creating Shared Understanding
Getting Started with Data Integration: FME Form 101
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
cuic standard and advanced reporting.pdf
Machine Learning_overview_presentation.pptx
Big Data Technologies - Introduction.pptx
1. Introduction to Computer Programming.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
SOPHOS-XG Firewall Administrator PPT.pptx
A Presentation on Artificial Intelligence
Advanced methodologies resolving dimensionality complications for autism neur...
“AI and Expert System Decision Support & Business Intelligence Systems”
The Rise and Fall of 3GPP – Time for a Sabbatical?
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Programs and apps: productivity, graphics, security and other tools
Dropbox Q2 2025 Financial Results & Investor Presentation
Approach and Philosophy of On baking technology

Hazelcast and MongoDB at Cloud CMS

  • 1. Distributed Caching with Hazelcast + MongoDB at Cloud CMS Michael Uzquiano [email protected] @uzquiano
  • 2. Agenda • What is Cloud CMS? • Why we chose MongoDB • What is Hazelcast? • Code Samples • Implementation with MongoDB
  • 4. • The fastest, easiest and most cost-effective way to build cloud-connected web and mobile applications. • An application server in the cloud for cloud- connected applications • Built to leverage the strengths of MongoDB • Hosted or On-Premise
  • 9. Cloud CMS provides • Content Management • Users, Groups, Roles, Permissions • Personalization (Behavioral Targeting) • Analytics, Reporting • Identity Management • Integrated Services • Email Campaigns, CRM, Integrated Billing
  • 10. Silos
  • 12. Mobile Ready • iOS, Android, Windows Mobile • JavaScript, Java, PHP, Ruby, Node.js • jQuery, jQuery Mobile, Dojo, YUI, Sencha Touch, Titanium, PhoneGap
  • 14. The right tool for the job • JSON • Query and Indexing • Doesn’t overstep into application domain • No transactions • No referential integrity • No triggers, foreign keys, procedures • Gets out of the way so we can tackle these
  • 15. Community + Momentum • Really great language drivers • Community contributors • Frequent release schedule • Exciting roadmap
  • 16. Performance • Very fast • Anywhere from 2 to 10x faster than MySQL • About 50 times faster than CouchDB • Lots of benchmarks but the point is, it’s fast! • Sharding built-in, automatic, and *Just Works™ • *Just Works™ guarantee applies only if you have a cluster of shard replica sets with config servers and routing servers and you define your own shard key(s) with appropriate uniformity and granularity • Asynchronous replication for redundancy/failover
  • 18. What is Hazelcast? • In-Memory Data Grid (IMDG) • Clustering and highly scalable data distribution solution for Java • Distributed Data Structures for Java • Distributed Hashtable (DHT) and more
  • 19. What does Hazelcast do? • Scale your application • Share data across cluster • Partition your data • Send/receive messages • Balance load across cluster • Process in parallel on many JVM
  • 20. Advantages • Open source (Apache License) • Super light, simple, no-dependency • Distributed/partitioned implementation of map, queue, set, list, lock and executor service • Transactional (JCA support) • Topic for pub/sub messaging • Cluster info and membership events • Dynamic clustering, backup, fail-over
  • 21. Data Partitioning in a Cluster If you have 5 million objects in your 5-node cluster, then each node will carry 1 million objects and 1 million backup objects. Server1 Server2 Server3 Server4 Server5
  • 22. SuperClient in a Cluster • -Dhazelcast.super.client=true • As fast as any member in the cluster • Holds no-data Server1 Server2 Server3 Server4 Server5
  • 24. Code Samples – Cluster Interface importcom.hazelcast.core.*; importjava.util.Set; Cluster cluster = Hazelcast.getCluster(); cluster.addMembershipListener(listener); Member localMember = cluster.getLocalMember(); System.out.println (localMember.getInetAddress()); Set setMembers = cluster.getMembers();
  • 25. Code Samples – Distributed Map importcom.hazelcast.core.Hazelcast; importjava.util.Map; Map<String, User>map = Hazelcast.getMap(”users"); map.put ("1", user); User user = map.get("1");
  • 26. Code Samples – Distributed Queue importcom.hazelcast.core.Hazelcast; importjava.util.concurrent.BlockingQueue; importjava.util.concurrent.TimeUnit; BlockingQueue<Task>queue = Hazelcast.getQueue(“tasks"); queue.offer(task); Task t = queue.poll(); Task t = queue.poll(5, TimeUnit.SECONDS);
  • 27. Code Samples – Distributed Set importcom.hazelcast.core.Hazelcast; importjava.util.Set; Set<Price>set= Hazelcast.getSet(“IBM-Quote-History"); set.add (new Price (10, time1)); set.add (new Price (11, time2)); set.add (new Price (13, time3)); for (Price price : set) { // process price }
  • 28. Code Samples – Distributed Lock importcom.hazelcast.core.Hazelcast; importjava.util.concurrent.locks.Lock; Lockmylock= Hazelcast.getLock(mylockobject); mylock.lock(); try { // do something } finally { mylock.unlock(); }
  • 29. Code Samples – Distributed Topic importcom.hazelcast.core.*; public class Sample implements MessageListener { public static void main(String[] args) { Sample sample = new Sample(); Topic topic = Hazelcast.getTopic ("default"); topic.addMessageListener(sample); topic.publish ("my-message-object"); } public void onMessage(Object msg) { System.out.println("Got msg :" + msg); } }
  • 30. Code Samples – Distributed Events importcom.hazelcast.core.IMap; importcom.hazelcast.core.Hazelcast; importcom.hazelcast.core.EntryListener; importcom.hazelcast.core.EntryEvent; publicclassSampleimplementsEntryListener{ publicstaticvoidmain(String[]args){ Sample sample =newSample(); IMap map =Hazelcast.getMap("default"); map.addEntryListener(sample,true); map.addEntryListener(sample,"key"); } publicvoidentryAdded(EntryEventevent){ System.out.println("Added "+event.getKey()+":"+event.getValue()); } publicvoidentryRemoved(EntryEventevent){ System.out.println("Removed "+event.getKey()+":"+event.getValue()); } publicvoidentryUpdated(EntryEventevent){ System.out.println("Updated "+event.getKey()+":"+event.getValue()); } }
  • 31. Code Samples – Executor Service FutureTask<String>futureTask= new DistributedTask<String>(new Echo(input), member); ExecutorServicees=Hazelcast.getExecutorService(); es.execute(futureTask); String result = futureTask.get();
  • 32. Sample Configuration <hazelcast> <group> <name>dev</name> <password>dev-pass</password> </group> <network> <portauto-increment="true">5701</port> <join> <multicastenabled="true"> <multicast-group>224.2.2.3</multicast-group> <multicast-port>54327</multicast-port> </multicast> <tcp-ipenabled="false"> <interface>192.168.1.2-5</interface> <hostname>istanbul.acme</hostname> </tcp-ip> </join> <interfacesenabled="false"> <interface>10.3.17.*</interface> </interfaces> </network> <executor-service> <core-pool-size>16</core-pool-size> <max-pool-size>64</max-pool-size> <keep-alive-seconds>60</keep-alive-seconds> </executor-service> <queuename="tasks"> <max-size-per-jvm>10000</max-size-per-jvm> </queue> </hazelcast>
  • 33. Distributed Job Queue Elasticity with Cloud CMS
  • 35. Distributed Job Queue Upload of a 20 page PDF Write PDF to GridFS Add 2 jobs to Queue (each to build 10 pngs)
  • 36. Distributed Job Queue Upload of a 20 page PDF Write PDF to GridFS Add 2 jobs to Queue (each to build 10 pngs)
  • 37. Distributed Job Queue Upload of a 20 page PDF Write PDF to GridFS Add 2 jobs to Queue (each to build 10 pngs)
  • 38. Distributed Job Queue Upload of a 20 page PDF Write PDF to GridFS Add 2 jobs to Queue (each to build 10 pngs)
  • 39. Distributed Job Queue Jobs may run asynchronously (returns once transaction complete) Picks job from Picks Job from queue and works on it queue and works on it Job Scheduler determines which jobs get priority
  • 41. Implementation with MongoDB com.hazelcast.core.MapStore
  • 42. MapStore public interface MapStore<K,V> extends MapLoader<K,V> { void store(Kk, V v); void storeAll(Map<K,V>kvMap); void delete(Kk); void deleteAll(Collection<K>ks); } public interface MapLoader<K,V> { V load(Kk); Map<K,V>loadAll(Collection<K>ks); Set<K>loadAllKeys(); }
  • 43. MapLoaderLifecycleSupport public interface MapLoaderLifecycleSupport { void init(HazelcastInstancehazelcastInstance, Properties properties, String mapName); void destroy(); Set<K>loadAllKeys(); }
  • 44. public class MongoUsersMapStore implements MapStore, MapLoaderLifecycleSupport { }
  • 45. public class MongoUsersMapStore implements MapStore, MapLoaderLifecycleSupport { private Mongo mongo; private DBCollectioncol; public void init(HazelcastInstancehazelcastInstance, Properties properties, String mapName) { this.mongo = new Mongo(“localhost”, 27017); String dbname = properties.get(“db”); String cname = properties.get(“collection”); DB db = this.mongo.getDB(dbname); this.col = db.getCollection(cname); } }
  • 46. public class MongoUsersMapStore implements MapStore, MapLoaderLifecycleSupport { private Mongo mongo; private DBCollectioncol; ... public void destroy() { this.mongo.close(); } public Set<K>loadAllKeys() { return null; } }
  • 47. public class MongoUsersMapStore implements MapStore, MapLoaderLifecycleSupport { private Mongo mongo; private DBCollectioncol; ... public Set loadAllKeys() { Set keys = new HashSet(); BasicDBList fields = new BasicDBList(); fields.add(“_id”); DBCursor cursor = this.col.find(null, fields); while (cursor.hasNext()) { keys.add(cursor.next().get(“_id”)); } return keys; } }
  • 48. public class MongoUsersMapStore implements MapStore, MapLoaderLifecycleSupport { ... public void store(Kk, V v) { DBObjectdbObject = convert(v); dbObject.put(“_id”, k); this.col.save(dbObject); } public void delete(Kk) { DBObjectdbObject = new BasicDBObject(); dbObject.put(“_id”, k); this.col.remove(dbObject); } }
  • 49. public class MongoUsersMapStore implements MapStore, MapLoaderLifecycleSupport { ... public void storeAll(Map map) { for (Object key : map.keySet()) { store(key, map.get(key)); } } public void deleteAll(Collection keys) { for (Object key: keys) { delete(key); } } }
  • 50. public class MongoUsersMapStore implements MapStore, MapLoaderLifecycleSupport { ... public void storeAll(Map map) { for (Object key : map.keySet()) { store(key, map.get(key)); } } public void deleteAll(Collection keys) { BasicDBListdbo = new BasicDBList(); for (Object key : keys) { dbo.add(newBasicDBObject("_id", key)); } BasicDBObjectdbb = new BasicDBObject("$or", dbo); this.col.remove(dbb); } }
  • 51. Spring Config <beans xmlns="http://www.springframework.org/schema/beans" xmlns:hz="http://www.hazelcast.com/schema/spring"> <hz:hazelcast id="hzInstance”> <hz:config> <hz:map name=”users” backup-count="1" max-size="2000” eviction-percentage="25" eviction-policy="LRU" merge-policy="hz.LATEST_UPDATE"> <hz:map-store enabled="true" write-delay-seconds="0" implementation="mymap" /> </hz:map> </hz:config> </hz:hazelcast> <bean id=”mymap” class="org.sample.MongoUsersMapStore" />
  • 52. Implementation with MongoDB com.hazelcast.core.EntryListener
  • 53. EntryListener public interface EntryListener<K,V> { void entryAdded(EntryEvent<K, V> event); void entryUpdated(EntryEvent<K, V> event); void entryRemoved(EntryEvent<K, V> event); void entryEvicted(EntryEvent<K, V> event); }
  • 54. EntryListener public class UserCacheEntryListener<String, User> { private Map<String, User> cache; public User getUser(String key) { return cache.get(key); } public void entryAdded(EntryEvent<String, User> event) { cache.put(event.getKey(), event.getValue()); } }
  • 56. Spring Framework • Spring Data for MongoDB • http://www.springsource.org/spring-data/mongodb • com.hazelcast.spring.mongodb.MongoMapStore • Based on Spring API Template pattern • com.hazelcast.spring.mongodb.MongoTemplate • Easy to get started, base implementation • You still might want to roll your own
  • 57. Questions? • Michael Uzquiano [email protected] • @uzquiano • Cloud CMS • http://www.cloudcms.com • @cloudcms • Hazelcast • http://www.hazelcast.com • https://github.com/hazelcast/hazelcast