SlideShare una empresa de Scribd logo
1 de 57
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
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
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

Más contenido relacionado

La actualidad más candente

Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryWilliam Candillon
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Sunghyouk Bae
 
Protect your app from Outages
Protect your app from OutagesProtect your app from Outages
Protect your app from OutagesRon Zavner
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
What is the ServiceStack?
What is the ServiceStack?What is the ServiceStack?
What is the ServiceStack?Demis Bellot
 
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB
 
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...
CQL performance with Apache Cassandra 3.0 (Aaron Morton, The Last Pickle) | C...DataStax
 
Volodymyr Lyubinets "Introduction to big data processing with Apache Spark"
Volodymyr Lyubinets "Introduction to big data processing with Apache Spark"Volodymyr Lyubinets "Introduction to big data processing with Apache Spark"
Volodymyr Lyubinets "Introduction to big data processing with Apache Spark"IT Event
 
Bulk Loading into Cassandra
Bulk Loading into CassandraBulk Loading into Cassandra
Bulk Loading into CassandraBrian Hess
 
Bulk Loading Data into Cassandra
Bulk Loading Data into CassandraBulk Loading Data into Cassandra
Bulk Loading Data into CassandraDataStax
 
What istheservicestack
What istheservicestackWhat istheservicestack
What istheservicestackDemis Bellot
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring SessionDavid Gómez García
 
MongoDB as Message Queue
MongoDB as Message QueueMongoDB as Message Queue
MongoDB as Message QueueMongoDB
 
Webinar: Was ist neu in MongoDB 2.4
Webinar: Was ist neu in MongoDB 2.4Webinar: Was ist neu in MongoDB 2.4
Webinar: Was ist neu in MongoDB 2.4MongoDB
 

La actualidad más candente (19)

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

Destacado

Phoenix for Rubyists
Phoenix for RubyistsPhoenix for Rubyists
Phoenix for RubyistsMike North
 
Async Gateway или Разработка системы распределенных вычислений с нуля
Async Gateway или Разработка системы распределенных вычислений с нуляAsync Gateway или Разработка системы распределенных вычислений с нуля
Async Gateway или Разработка системы распределенных вычислений с нуляVitebsk Miniq
 
HighLoad++ 2009 In-Memory Data Grids
HighLoad++ 2009 In-Memory Data GridsHighLoad++ 2009 In-Memory Data Grids
HighLoad++ 2009 In-Memory Data GridsAlexey Kharlamov
 
50 nouvelles choses que l'on peut faire en Java 8
50 nouvelles choses que l'on peut faire en Java 850 nouvelles choses que l'on peut faire en Java 8
50 nouvelles choses que l'on peut faire en Java 8José Paumard
 
Алексей Николаенков, Devexperts
Алексей Николаенков, DevexpertsАлексей Николаенков, Devexperts
Алексей Николаенков, DevexpertsNata_Churda
 
Hazelcast for Terracotta Users
Hazelcast for Terracotta UsersHazelcast for Terracotta Users
Hazelcast for Terracotta UsersHazelcast
 
Amazon cloud – готовим вместе
Amazon cloud – готовим вместеAmazon cloud – готовим вместе
Amazon cloud – готовим вместеVitebsk Miniq
 
50 new things we can do with Java 8
50 new things we can do with Java 850 new things we can do with Java 8
50 new things we can do with Java 8José Paumard
 
JFokus 50 new things with java 8
JFokus 50 new things with java 8JFokus 50 new things with java 8
JFokus 50 new things with java 8José Paumard
 
Gamification in outsourcing company: experience report.
Gamification in outsourcing company: experience report.Gamification in outsourcing company: experience report.
Gamification in outsourcing company: experience report.Mikalai Alimenkou
 
Java 8, the Good, the Bad and the Ugly
Java 8, the Good, the Bad and the UglyJava 8, the Good, the Bad and the Ugly
Java 8, the Good, the Bad and the UglyMikalai Alimenkou
 
Очень вкусный фрукт Guava
Очень вкусный фрукт GuavaОчень вкусный фрукт Guava
Очень вкусный фрукт GuavaEgor Chernyshev
 
ArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateauArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateauJosé Paumard
 
Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuningMikalai Alimenkou
 
Going reactive in java
Going reactive in javaGoing reactive in java
Going reactive in javaJosé Paumard
 
Hazelcast Deep Dive (Paris JUG-2)
Hazelcast Deep Dive (Paris JUG-2)Hazelcast Deep Dive (Paris JUG-2)
Hazelcast Deep Dive (Paris JUG-2)Emrah Kocaman
 
Maven 3 : уличная магия
Maven 3 : уличная магияMaven 3 : уличная магия
Maven 3 : уличная магияAleksey Solntsev
 

Destacado (20)

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

Similar a Hazelcast and MongoDB at Cloud CMS

Camel one v3-6
Camel one v3-6Camel one v3-6
Camel one v3-6wxdydx
 
Hidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-PersistenceHidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-PersistenceSven Ruppert
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныTimur Safin
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationBen Hall
 
How lagom helps to build real world microservice systems
How lagom helps to build real world microservice systemsHow lagom helps to build real world microservice systems
How lagom helps to build real world microservice systemsMarkus Eisele
 
Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...
Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...
Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...OpenCredo
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
AWS Lambda with Serverless Framework and Java
AWS Lambda with Serverless Framework and JavaAWS Lambda with Serverless Framework and Java
AWS Lambda with Serverless Framework and JavaManish Pandit
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebJames Rakich
 

Similar a Hazelcast and MongoDB at Cloud CMS (20)

Camel one v3-6
Camel one v3-6Camel one v3-6
Camel one v3-6
 
Hidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-PersistenceHidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-Persistence
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоны
 
EIP In Practice
EIP In PracticeEIP In Practice
EIP In Practice
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
How lagom helps to build real world microservice systems
How lagom helps to build real world microservice systemsHow lagom helps to build real world microservice systems
How lagom helps to build real world microservice systems
 
Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...
Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...
Microservices Manchester: How Lagom Helps to Build Real World Microservice Sy...
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
AWS Lambda with Serverless Framework and Java
AWS Lambda with Serverless Framework and JavaAWS Lambda with Serverless Framework and Java
AWS Lambda with Serverless Framework and Java
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the Web
 

Último

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Último (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Hazelcast and MongoDB at Cloud CMS

  • 1. Distributed Caching with Hazelcast + MongoDB at Cloud CMS Michael Uzquiano uzi@cloudcms.com @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
  • 13.
  • 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
  • 17.
  • 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 • uzi@cloudcms.com • @uzquiano • Cloud CMS • http://www.cloudcms.com • @cloudcms • Hazelcast • http://www.hazelcast.com • https://github.com/hazelcast/hazelcast