Hazelcast Documentation PDF
Hazelcast Documentation PDF
Hazelcast Documentation PDF
version 2.5
Table of Contents
1. Introduction ........................................................................................................................................... 1 1.1. Getting Started (Tutorial) .............................................................................................................. 1 2. Distributed Data Structures ...................................................................................................................... 4 2.1. Distributed Queue ........................................................................................................................ 4 2.2. Distributed Topic ......................................................................................................................... 6 2.3. Distributed Map ........................................................................................................................... 6 2.3.1. Backups ........................................................................................................................... 7 2.3.2. Eviction ........................................................................................................................... 8 2.3.3. Persistence ...................................................................................................................... 10 2.3.4. Query ............................................................................................................................ 11 2.3.5. Near Cache ..................................................................................................................... 14 2.3.6. Entry Statistics ................................................................................................................ 15 2.3.7. Indexing ......................................................................................................................... 16 2.4. Distributed MultiMap .................................................................................................................. 16 2.5. Distributed Set ........................................................................................................................... 17 2.6. Distributed List .......................................................................................................................... 17 2.7. Distributed Lock ........................................................................................................................ 18 2.8. Distributed Events ...................................................................................................................... 18 3. Elastic Memory (Enterprise Edition Only) ......................................................................................................... 20 4. Security (Enterprise Edition Only) .................................................................................................................... 21 4.1. Credentials ................................................................................................................................ 21 4.2. ClusterLoginModule ................................................................................................................... 22 4.3. Cluster Member Security ............................................................................................................. 23 4.4. Native Client Security ................................................................................................................. 24 4.4.1. Authentication ................................................................................................................. 24 4.4.2. Authorization .................................................................................................................. 24 4.4.3. Permissions ..................................................................................................................... 26 5. Data Affinity ....................................................................................................................................... 30 6. Monitoring with JMX ............................................................................................................................ 33 7. Cluster Utilities .................................................................................................................................... 35 7.1. Cluster Interface ......................................................................................................................... 35 7.2. Cluster-wide Id Generator ............................................................................................................ 35 7.3. LiteMember .............................................................................................................................. 35 8. Transactions ......................................................................................................................................... 36 8.1. Transaction Interface .................................................................................................................. 36 8.2. J2EE Integration ........................................................................................................................ 36 8.2.1. Resource Adapter Configuration ......................................................................................... 37 8.2.2. Sample Glassfish v3 Web Application Configuration .............................................................. 38 8.2.3. Sample JBoss Web Application Configuration ...................................................................... 38 9. Distributed Executor Service .................................................................................................................. 39 9.1. Distributed Execution .................................................................................................................. 39 9.2. Execution Cancellation ................................................................................................................ 40 9.3. Execution Callback ..................................................................................................................... 41 10. Http Session Clustering with HazelcastWM ............................................................................................. 43 11. WAN Replication ................................................................................................................................ 46 12. Configuration ..................................................................................................................................... 48 12.1. Creating Separate Clusters ......................................................................................................... 49 12.2. Network Configuration .............................................................................................................. 50 12.2.1. Configuring TCP/IP Cluster ............................................................................................. 50 12.2.2. Specifying Network Interfaces .......................................................................................... 50 12.2.3. EC2 Auto Discovery ....................................................................................................... 51 12.2.4. Network Partitioning (Split-Brain Syndrome) ...................................................................... 51 12.2.5. SSL ............................................................................................................................. 53 12.2.6. Encryption .................................................................................................................... 54 12.2.7. Socket Interceptor .......................................................................................................... 55
iii
Hazelcast Documentation
13. 14.
15.
16.
17.
18.
12.2.8. IPv6 Support ................................................................................................................. 12.2.9. Restricting Outbound Ports .............................................................................................. 12.3. Partition Group Configuration ..................................................................................................... 12.4. Listener Configurations .............................................................................................................. 12.5. Wildcard Configuration ............................................................................................................. 12.6. Advanced Configuration Properties .............................................................................................. 12.7. Logging Configuration .............................................................................................................. 12.8. Setting License Key (Enterprise Edition Only) ....................................................................................... Hibernate Second Level Cache .............................................................................................................. Spring Integration ............................................................................................................................... 14.1. Configuration ........................................................................................................................... 14.2. Spring Managed Context ............................................................................................................ 14.3. Spring Cache ........................................................................................................................... 14.4. Hibernate 2nd Level Cache Config .............................................................................................. 14.5. Spring Data - JPA .................................................................................................................... 14.6. Spring Data - MongoDB ............................................................................................................ Clients .............................................................................................................................................. 15.1. Native Client ........................................................................................................................... 15.1.1. Java Client .................................................................................................................... 15.1.2. CSharp Client (Enterprise Edition Only) ..................................................................................... 15.2. Memcache Client ...................................................................................................................... 15.3. Rest Client .............................................................................................................................. Internals ............................................................................................................................................ 16.1. Internals 2: Serialization ............................................................................................................ 16.2. Internals 3: Cluster Membership .................................................................................................. 16.3. Internals 4: Distributed Map ....................................................................................................... Management Center ............................................................................................................................. 17.1. Introduction ............................................................................................................................. 17.1.1. Installation .................................................................................................................... 17.1.2. User Administration ....................................................................................................... 17.1.3. Tool Overview .............................................................................................................. 17.2. Maps ...................................................................................................................................... 17.2.1. Monitoring Maps ........................................................................................................... 17.2.2. Map Browser ................................................................................................................ 17.2.3. Map Configuration ......................................................................................................... 17.3. Queues ................................................................................................................................... 17.4. Topics .................................................................................................................................... 17.5. Members ................................................................................................................................. 17.5.1. Monitoring .................................................................................................................... 17.5.2. Operations .................................................................................................................... 17.6. Alerting System ....................................................................................................................... 17.7. System Logs ............................................................................................................................ 17.8. Scripting ................................................................................................................................. 17.9. Time Travel ............................................................................................................................. 17.10. Console ................................................................................................................................. Miscellaneous ..................................................................................................................................... 18.1. Common Gotchas ..................................................................................................................... 18.2. Testing Cluster ......................................................................................................................... 18.3. Planned Features ...................................................................................................................... 18.4. Release Notes ..........................................................................................................................
56 57 58 59 62 63 66 67 68 71 71 74 76 76 77 78 79 79 79 80 81 82 83 83 84 85 87 87 87 87 88 88 88 89 89 89 90 90 91 91 91 92 92 93 93 96 96 96 98 98
iv
List of Tables
12.1. Properties Table ............................................................................................................................... 64
Chapter 1. Introduction
Hazelcast is a clustering and highly scalable data distribution platform for Java. Hazelcast helps architects and developers to easily design and develop faster, highly scalable and reliable applications for their businesses. Distributed implementations of java.util.{Queue, Set, List, Map} Distributed implementation of java.util.concurrent.ExecutorService Distributed implementation of java.util.concurrency.locks.Lock Distributed Topic for publish/subscribe messaging Transaction support and J2EE container integration via JCA Distributed listeners and events Support for cluster info and membership events Dynamic HTTP session clustering Dynamic clustering Dynamic scaling to hundreds of servers Dynamic partitioning with backups Dynamic fail-over Super simple to use; include a single jar Super fast; thousands of operations per sec. Super small; less than a MB Super efficient; very nice to CPU and RAM To install Hazelcast: Download hazelcast-_version_.zip from www.hazelcast.com [http://www.hazelcast.com] Unzip hazelcast-_version_.zip file Add hazelcast.jar file into your classpath Hazelcast is pure Java. JVMs that are running Hazelcast will dynamically cluster. Although by default Hazelcast will use multicast for discovery, it can also be configured to only use TCP/IP for environments where multicast is not available or preferred (Click here for more info). Communication among cluster members is always TCP/IP with Java NIO beauty. Default configuration comes with 1 backup so if one node fails, no data will be lost. It is as simple as usingjava.util. {Queue, Set, List, Map}. Just add the hazelcast.jar into your classpath and start coding.
Introduction
import com.hazelcast.core.Hazelcast; import java.util.Map; import java.util.Queue; public class GettingStarted { public static void main(String[] args) { Config cfg = new Config(); HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg); Map<Integer, String> mapCustomers = instance.getMap("customers"); mapCustomers.put(1, "Joe"); mapCustomers.put(2, "Ali"); mapCustomers.put(3, "Avi"); System.out.println("Customer with key 1: "+ mapCustomers.get(1)); System.out.println("Map Size:" + mapCustomers.size()); Queue<String> queueCustomers = instance.getQueue("customers"); queueCustomers.offer("Tom"); queueCustomers.offer("Mary"); queueCustomers.offer("Jane"); System.out.println("First customer: " + queueCustomers.poll()); System.out.println("Second customer: "+ queueCustomers.peek()); System.out.println("Queue size: " + queueCustomers.size()); } }
Run this class second time to get the second node started. Have you seen they formed a cluster? You should see something like this:
Members [2] { Member [127.0.0.1:5701] Member [127.0.0.1:5702] this }
Connecting Hazelcast Cluster with Java Client API Besides hazelcast.jar you should also add hazelcast-client.jar to your classpath. Following code will start a Hazelcast Client, connect to our two node cluster and print the size of our customers map.
package com.hazelcast.test; import import import import com.hazelcast.client.ClientConfig; com.hazelcast.client.HazelcastClient; com.hazelcast.core.HazelcastInstance; com.hazelcast.core.IMap;
public class GettingStartedClient { public static void main(String[] args) { ClientConfig clientConfig = new ClientConfig(); clientConfig.addAddress("127.0.0.1:5701"); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); IMap map = client.getMap("customers"); System.out.println("Map Size:" + map.size()); } }
When you run it, you will see the client properly connects to the cluster and print the map size as 3. What is Next?
Introduction
You can browse documentation [http://www.hazelcast.com/docs.jsp] and resources for detailed features and examples. You can email your questions to Hazelcast mail group [http://groups.google.com/group/hazelcast]. You can browse Hazelcast source code [http://code.google.com/p/hazelcast/source/browse/#svn/trunk].
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); BlockingQueue<MyTask> q = hz.getQueue("tasks"); q.put(new MyTask()); MyTask task = q.take(); boolean offered = q.offer(new MyTask(), 10, TimeUnit.SECONDS); task = q.poll (5, TimeUnit.SECONDS); if (task != null) { //process task }
If you have 10 million tasks in your "tasks" queue and you are running that code over 10 JVMs (or servers), then each server carries 1 million task objects (plus backups). FIFO ordering will apply to all queue operations cluster-wide. User objects (such as MyTask in the example above), that are (en/de)queued have to beSerializable. Maximum capacity per JVM and the TTL (Time to Live) for a queue can be configured. Distributed queues are backed by distributed maps. Thus, queues can have custom backup counts and persistent storage. Hazelcast will generate cluster-wide unique id for each element in the queue. Sample configuration:
<hazelcast> ... <queue name="tasks"> <!-Maximum size of the queue. When a JVM's local queue size reaches the maximum, all put/offer operations will get blocked until the queue size of the JVM goes down below the maximum. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. --> <max-size-per-jvm>10000</max-size-per-jvm> <!-Name of the map configuration that will be used for the backing distributed map for this queue. --> <backing-map-ref>queue-map</backing-map-ref> </queue> <map name="queue-map"> <backup-count>1</backup-count> <map-store enabled="true"> <class-name>com.your,company.storage.DBMapStore</class-name> <write-delay-seconds>0</write-delay-seconds> </map-store> ... </map> </hazelcast>
If the backing map has no map-store defined then your distributed queue will be in-memory only. If the backing map has a map-store defined then Hazelcast will call your MapStore implementation to persist queue elements. Even if you reboot your cluster Hazelcast will rebuild the queue with its content. When implementing a MapStore for the backing map, note that type of the key is always Long and values are the elements you place into the queue. So make sure MapStore.loadAllKeys returns Set<Long> for instance. To learn about wildcard configuration feature, see Wildcard Configuration page.
public class Sample implements MessageListener<MyEvent> { public static void main(String[] args) { Sample sample = new Sample(); Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); ITopic topic = hz.getTopic ("default"); topic.addMessageListener(sample); topic.publish (new MyEvent()); } public void onMessage(MyEvent myEvent) { System.out.println("Message received = " + myEvent.toString()); if (myEvent.isHeavyweight()) { messageExecutor.execute(new Runnable() { public void run() { doHeavyweightStuff(myEvent); } }); } } // ... private static final Executor messageExecutor = Executors.newSingleThreadExecutor(); }
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); Map<String, Customer> mapCustomers = hz.getMap("customers"); mapCustomers.put("1", new Customer("Joe", "Smith")); mapCustomers.put("2", new Customer("Ali", "Selam")); mapCustomers.put("3", new Customer("Avi", "Noyan")); Collection<Customer> colCustomers = mapCustomers.values(); for (Customer customer : colCustomers) { // process customer }
Hazelcast.getMap() actually returns com.hazelcast.core.IMap which extends java.util.concurrent.ConcurrentMap interface. So methods like ConcurrentMap.putIfAbsent(key,value) and ConcurrentMap.replace(key,value) can be used on distributed map as shown in the example below.
import com.hazelcast.core.Hazelcast; import java.util.concurrent.ConcurrentMap; Customer getCustomer (String id) { ConcurrentMap<String, Customer> map = Hazelcast.getMap("customers"); Customer customer = map.get(id); if (customer == null) { customer = new Customer (id); customer = map.putIfAbsent(id, customer); } return customer; } public boolean updateCustomer (Customer customer) { ConcurrentMap<String, Customer> map = Hazelcast.getMap("customers"); return (map.replace(customer.getId(), customer) != null); } public boolean removeCustomer (Customer customer) { ConcurrentMap<String, Customer> map = Hazelcast.getMap("customers"); return map.remove(customer.getId(), customer) ); }
All ConcurrentMap operations such as put and remove might wait if the key is locked by another thread in the local or remote JVM, but they will eventually return with success. ConcurrentMap operations never throwjava.util.ConcurrentModificationException. Also see: Distributed Map internals. Data Affinity. Map Configuration with wildcards..
2.3.1. Backups
Hazelcast will distribute map entries onto multiple JVMs (cluster members). Each JVM holds some portion of the data but we don't want to lose data when a member JVM crashes. To provide data-safety, Hazelcast allows you to specify the number of backup copies you want to have. That way data on a JVM will be copied onto other JVM(s). Hazelcast supports both sync and async backups. Sync backups block operations until backups are successfully copied to backups nodes (or deleted from backup nodes in case of remove) and acknowledgements are received. In contrast, async backups do not block operations, they are fire & forget and do not require acknowledgements. By default, Hazelcast will
have one sync backup copy. If backup count >= 1, then each member will carry both owned entries and backup copies of other member(s). So for the map.get(key) call, it is possible that calling member has backup copy of that key but by default, map.get(key) will always read the value from the actual owner of the key for consistency. It is possible to enable backup reads by changing the configuration. Enabling backup reads will give you greater performance.
<hazelcast> ... <map name="default"> <!-Number of sync-backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. Valid numbers are 0 (no backup), 1, 2, 3. --> <backup-count>1</backup-count> <!-Number of async-backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. Valid numbers are 0 (no backup), 1, 2, 3. --> <async-backup-count>1</async-backup-count> <!-Can we read the local backup entries? Default value is false for strong consistency. Being able to read backup data will give you greater performance. --> <read-backup-data>false</read-backup-data> ... </map> </hazelcast>
2.3.2. Eviction
Hazelcast also supports policy based eviction for distributed map. Currently supported eviction policies are LRU (Least Recently Used) and LFU (Least Frequently Used). This feature enables Hazelcast to be used as a distributed cache. If time-to-live-seconds is not 0 then entries older than time-to-live-seconds value will get evicted, regardless of the eviction policy set. Here is a sample configuration for eviction:
<hazelcast> ... <map name="default"> <!-Number of backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. Valid numbers are 0 (no backup), 1, 2, 3. --> <backup-count>1</backup-count> <!-Maximum number of seconds for each entry to stay in the map. Entries that are older than <time-to-live-seconds> and not updated for <time-to-live-seconds> will get automatically evicted from the map. Any integer between 0 and Integer.MAX_VALUE. 0 means infinite. Default is 0. --> <time-to-live-seconds>0</time-to-live-seconds> <!-Maximum number of seconds for each entry to stay idle in the map. Entries that are idle(not touched) for more than <max-idle-seconds> will get automatically evicted from the map. Entry is touched if get, put or containsKey is called. Any integer between 0 and Integer.MAX_VALUE. 0 means infinite. Default is 0. --> <max-idle-seconds>0</max-idle-seconds> <!-Valid values are: NONE (no extra eviction, <time-to-live-seconds> may still apply), LRU (Least Recently Used), LFU (Least Frequently Used). NONE is the default. Regardless of the eviction policy used, <time-to-live-seconds> will still apply. --> <eviction-policy>LRU</eviction-policy> <!-Maximum size of the map. When max size is reached, map is evicted based on the policy defined. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. --> <max-size policy="cluster_wide_map_size">5000</max-size> <!-When max. size is reached, specified percentage of the map will be evicted. Any integer between 0 and 100. If 25 is set for example, 25% of the entries will get evicted. --> <eviction-percentage>25</eviction-percentage> <!-Specifies when eviction will be started. Default value is 3. So every 3 (+up to 5 for performance reasons) seconds eviction will be kicked of. Eviction is costly operation, setting this number too low, can decrease the performance. --> <eviction-delay-seconds>3</eviction-delay-seconds> </map> </hazelcast>
Max-Size Policies There are 5 defined policies can be used in max-size configuration. 1. cluster_wide_map_size: Cluster-wide total max map size (default policy).
<max-size policy="cluster_wide_map_size">50000</max-size>
2.3.3. Persistence
Hazelcast allows you to load and store the distributed map entries from/to a persistent datastore such as relational database. If a loader implementation is provided, when get(key) is called, if the map entry doesn't exist in-memory then Hazelcast will call your loader implementation to load the entry from a datastore. If a store implementation is provided, when put(key,value) is called, Hazelcast will call your store implementation to store the entry into a datastore. Hazelcast can call your implementation to store the entries synchronously (write-through) with no-delay or asynchronously (write-behind) with delay and it is defined by the write-delay-seconds value in the configuration. If it is write-through, when the map.put(key,value) call returns, you can be sure that MapStore.store(key,value) is successfully called so the entry is persisted. In-Memory entry is updated In-Memory backup copies are successfully created on other JVMs (if backup-count is greater than 0) If it is write-behind, when the map.put(key,value) call returns, you can be sure that In-Memory entry is updated In-Memory backup copies are successfully created on other JVMs (if backup-count is greater than 0) The entry is marked as dirty so that after write-delay-seconds, it can be persisted. Same behavior goes for the remove(key and MapStore.delete(key). If MapStore throws an exception then the exception will be propagated back to the original put or remove call in the form of RuntimeException. When write-through is used, Hazelcast will call MapStore.store(key,value) and MapStore.delete(key) for each entry update. When write-behind is used, Hazelcast will callMapStore.store(map), and MapStore.delete(collection) to do all writes in a single call. Also note that your MapStore or MapLoader implementation should not use Hazelcast Map/Queue/MultiMap/List/Set operations. Your implementation should only work with your data store. Otherwise you may get into deadlock situations. Here is a sample configuration:
10
<hazelcast> ... <map name="default"> ... <map-store enabled="true"> <!-Name of the class implementing MapLoader and/or MapStore. The class should implement at least of these interfaces and contain no-argument constructor. Note that the inner classes are not supported. --> <class-name>com.hazelcast.examples.DummyStore</class-name> <!-Number of seconds to delay to call the MapStore.store(key, value). If the value is zero then it is write-through so MapStore.store(key, value) will be called as soon as the entry is updated. Otherwise it is write-behind so updates will be stored after write-delay-seconds value by calling Hazelcast.storeAll(map). Default value is 0. --> <write-delay-seconds>0</write-delay-seconds> </map-store> </map> </hazelcast>
Initialization on startup: As of 1.9.3 MapLoader has the new MapLoader.loadAllKeys API. It is used for pre-populating the in-memory map when the map is first touched/used. If MapLoader.loadAllKeys returns NULL then nothing will be loaded. Your MapLoader.loadAllKeys implementation can return all or some of the keys. You may select and return only the hot keys, for instance. Also note that this is the fastest way of pre-populating the map as Hazelcast will optimize the loading process by having each node loading owned portion of the entries. Here is MapLoader initialization flow; 1. When getMap() first called from any node, initialization starts 2. Hazelcast will call MapLoader.loadAllKeys() to get all your keys on each node 3. Each node will figure out the list of keys it owns 4. Each node will load all its owned keys by calling MapLoader.loadAll(keys) 5. Each node puts its owned entries into the map by calling IMap.putTransient(key,value)
2.3.4. Query
Hazelcast partitions your data and spreads across cluster of servers. You can surely iterate over the map entries and look for certain entries you are interested in but this is not very efficient as you will have to bring entire entry set and iterate locally. Instead, Hazelcast allows you to run distributed queries on your distributed map. Let's say you have a "employee" map containing values of Employee objects:
11
import java.io.Serializable; public class Employee implements Serializable { private String name; private int age; private boolean active; private double salary; public Employee(String name, int age, boolean live, double price) { this.name = name; this.age = age; this.active = live; this.salary = price; } public Employee() { } public String getName() { return name; } public int getAge() { return age; } public double getSalary() { return salary; } public boolean isActive() { return active; } }
Now you are looking for the employees who are active and with age less than 30. Hazelcast allows you to find these entries in two different ways: Distributed SQL Query SqlPredicate takes regular SQL where clause. Here is an example:
import com.hazelcast.core.IMap; import com.hazelcast.query.SqlPredicate; Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); IMap map = hz.getMap("employee"); Set<Employee> employees = (Set<Employee>) map.values(new SqlPredicate("active AND age < 30"));
Supported SQL syntax: AND/OR <expression> AND <expression> AND <expression>... active AND age>30 active=false OR age = 45 OR name = 'Joe' active AND (age >20 OR salary < 60000) =, !=, <, <=, >, >= <expression> = value age <= 30
12
name ="Joe" salary != 50000 BETWEEN <attribute> [NOT] BETWEEN <value1> AND <value2> age BETWEEN 20 AND 33 (same as age >=20 AND age<=33) age NOT BETWEEN 30 AND 40 (same as age <30 OR age>40) LIKE <attribute> [NOT] LIKE 'expression' % (percentage sign) is placeholder for many characters, _ (underscore) is placeholder for only one character. name LIKE 'Jo%' (true for 'Joe', 'Josh', 'Joseph' etc.) name LIKE 'Jo_' (true for 'Joe'; false for 'Josh') name NOT LIKE 'Jo_' (true for 'Josh'; false for 'Joe') name LIKE 'J_s%' (true for 'Josh', 'Joseph'; false 'John', 'Joe') IN <attribute> [NOT] IN (val1, val2, ...) age IN (20, 30, 40) age NOT IN (60, 70) Examples: active AND (salary >= 50000 OR (age NOT BETWEEN 20 AND 30)) age IN (20, 30, 40) AND salary BETWEEN (50000, 80000) Criteria API If SQL is not enough or programmable queries are preferred then JPA criteria like API can be used. Here is an example:
import import import import import com.hazelcast.core.IMap; com.hazelcast.query.Predicate; com.hazelcast.query.PredicateBuilder; com.hazelcast.query.EntryObject; com.hazelcast.config.Config;
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); IMap map = hz.getMap("employee"); EntryObject e = new PredicateBuilder().getEntryObject(); Predicate predicate = e.is("active").and(e.get("age").lessThan(30)); Set<Employee> employees = (Set<Employee>) map.values(predicate);
Indexing Hazelcast distributed queries will run on each member in parallel and only results will return the caller. When a query runs on a member, Hazelcast will iterate through the entire owned entries and find the matching ones. Can we make this
13
even faster? Yes by indexing the mostly queried fields. Just like you would do for your database. Of course, indexing will add overhead for each write operation but queries will be a lot faster. If you are querying your map a lot then make sure to add indexes for most frequently queried fields. So if your active and age < 30 query, for example, is used a lot then make sure you add index for active and age fields. Here is how:
IMap imap = Hazelcast.getMap("employees"); imap.addIndex("age", true); // ordered, since we have ranged queries for this field imap.addIndex("active", false); // not ordered, because boolean field cannot have range
API IMap.addIndex(fieldName, ordered) is used for adding index. For a each indexed field, if you have ranged- queries such asage>30, age BETWEEN 40 AND 60 then ordered parameter should betrue, otherwise set it tofalse.
14
<hazelcast> ... <map name="my-read-mostly-map"> ... <near-cache> <!-Maximum size of the near cache. When max size is reached, cache is evicted based on the policy defined. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. --> <max-size>5000</max-size> <!-Maximum number of seconds for each entry to stay in the near cache. Entries that are older than <time-to-live-seconds> will get automatically evicted from the near cache. Any integer between 0 and Integer.MAX_VALUE. 0 means infinite. Default is 0. --> <time-to-live-seconds>0</time-to-live-seconds> <!-Maximum number of seconds each entry can stay in the near cache as untouched (not-read). Entries that are not read (touched) more than <max-idle-seconds> value will get removed from the near cache. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. --> <max-idle-seconds>60</max-idle-seconds> <!-Valid values are: NONE (no extra eviction, <time-to-live-seconds> may still apply), LRU (Least Recently Used), LFU (Least Frequently Used). NONE is the default. Regardless of the eviction policy used, <time-to-live-seconds> will still apply. --> <eviction-policy>LRU</eviction-policy> <!-Should the cached entries get evicted if the entries are changed (updated or removed). true of false. Default is true. --> <invalidate-on-change>true</invalidate-on-change> </near-cache> </map> </hazelcast>
15
import com.hazelcast.core.Hazelcast; import com.hazelcast.core.MapEntry; Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); MapEntry entry = hz.getMap("quotes").getMapEntry("1"); System.out.println ("size in memory : " + entry.getCost(); System.out.println ("creationTime : " + entry.getCreationTime(); System.out.println ("expirationTime : " + entry.getExpirationTime(); System.out.println ("number of hits : " + entry.getHits(); System.out.println ("lastAccessedTime: " + entry.getLastAccessTime(); System.out.println ("lastUpdateTime : " + entry.getLastUpdateTime(); System.out.println ("version : " + entry.getVersion(); System.out.println ("isValid : " + entry.isValid(); System.out.println ("key : " + entry.getKey(); System.out.println ("value : " + entry.getValue(); System.out.println ("oldValue : " + entry.setValue(newValue);
2.3.7. Indexing
Map entries can be indexed to be able to query faster. These indexes can be created using IMap API. But this usage has a limitation; all indexes must be created before any value is put into map. Sometimes by design adding an index to map may be impossible before any value is added. For example if a map has MapLoader that loads entries during map creation, then adding indexes to map becomes meaningless. To solve this problem, Hazelcast introduces defining IMap indexes in configuration. Hazelcast XML configuration
<map name="default"> ... <indexes> <index ordered="false">name</index> <index ordered="true">age</index> </indexes> </map>
Config API
<hz:map name="default"> <hz:indexes> <hz:index attribute="name"/> <hz:index attribute="age" ordered="true"/> </hz:indexes> </hz:map>
16
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); // a multimap to hold <customerId, Order> pairs MultiMap<String, Order> mmCustomerOrders = hz.getMultiMap("customerOrders"); mmCustomerOrders.put("1", new Order ("iPhone", 340)); mmCustomerOrders.put("1", new Order ("MacBook", 1200)); mmCustomerOrders.put("1", new Order ("iPod", 79)); // get orders of the customer with customerId 1. Collection<Order> colOrders = mmCustomerOrders.get ("1"); for (Order order : colOrders) { // process order } // remove specific key/value pair boolean removed = mmCustomerOrders.remove("1", new Order ("iPhone", 340));
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); java.util.Set set = hz.getSet("IBM-Quote-History"); set.add(new Price(10, time1)); set.add(new Price(11, time2)); set.add(new Price(12, time3)); set.add(new Price(11, time4)); //.... Iterator it = set.iterator(); while (it.hasNext()) { Price price = (Price) it.next(); //analyze }
17
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); java.util.List list = hz.getList("IBM-Quote-Frequency"); list.add(new Price(10)); list.add(new Price(11)); list.add(new Price(12)); list.add(new Price(11)); list.add(new Price(12)); //.... Iterator it = list.iterator(); while (it.hasNext()) { Price price = (Price) it.next(); //analyze }
java.util.concurrent.locks.Lock.tryLock() with timeout is also supported. All operations on the Lock that Hazelcast.getLock(Object obj) returns are cluster-wide and Lock behaves just like java.util.concurrent.lock.ReentrantLock.
if (lock.tryLock (5000, TimeUnit.MILLISECONDS)) { try { // do some stuff here.. } finally { lock.unlock(); } }
Locks are fail-safe. If a member holds a lock and some of the members go down, cluster will keep your locks safe and available. Moreover, when a member leaves the cluster, all the locks acquired by this dead member will be removed so that these locks can be available for live members immediately.
18
public class Sample implements ItemListener, EntryListener { public static void main(String[] args) { Sample sample = new Sample(); Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); IQueue queue = hz.getQueue ("default"); IMap map = hz.getMap ("default"); ISet set = hz.getSet ("default"); //listen for all added/updated/removed entries queue.addItemListener(sample, true); set.addItemListener (sample, true); map.addEntryListener (sample, true); //listen for an entry with specific key map.addEntryListener (sample, "keyobj"); } public void entryAdded(EntryEvent event) { System.out.println("Entry added key=" + event.getKey() + ", value=" + event.getValue()); } public void entryRemoved(EntryEvent event) { System.out.println("Entry removed key=" + event.getKey() + ", value=" + event.getValue()); } public void entryUpdated(EntryEvent event) { System.out.println("Entry update key=" + event.getKey() + ", value=" + event.getValue()); } public void entryEvicted(EntryEvent event) { System.out.println("Entry evicted key=" + event.getKey() + ", value=" + event.getValue()); } public void itemAdded(Object item) { System.out.println("Item added = " + item); } public void itemRemoved(Object item) { System.out.println("Item removed = " + item); } }
19
By default, Hazelcast stores your distributed data (map entries, queue items) into Java heap which is subject to garbage collection. As your heap gets bigger, garbage collection might cause your application to pause tens of seconds, badly effecting your application performance and response times. Elastic Memory is Hazelcast with off-heap (direct) memory storage to avoid GC pauses. Even if you have terabytes of cache in-memory with lots of updates, GC will have almost no effect; resulting in more predictable latency and throughput. Here are the steps to enable Elastic Memory: Set the maximum direct memory JVM can allocate. Example java -XX:MaxDirectMemorySize=60G ... Enable Elastic Memory by setting hazelcast.elastic.memory.enabled Hazelcast Config Property to true. Set the total direct memory size for HazelcastInstance by setting hazelcast.elastic.memory.total.size Hazelcast Config Property. Size can be in MB or GB and abbreviation can be used, such as 60G and 500M. Set the chunk size in KB by setting hazelcast.elastic.memory.chunk.size Hazelcast Config Property. Hazelcast will partition the entire offheap memory into chunks. Default chunk size is 1. Chunk size has to be power of 2 such as 1, 2, 4 and 8. Configure maps you want them to use Elastic Memory by setting StorageType toOFFHEAP. Default value isHEAP. Using XML configuration:
<hazelcast> ... <map name="default"> ... <storage-type>OFFHEAP</storage-type> </map> </hazelcast>
If NearCache is defined for a map, all near cached items are also going to be stored on the same off-heap. So off-heap storage is used for both near cache and distributed object storage. Also see how to configure license key.
20
Chapter 4. Security
Hazelcast has an extensible, JAAS based security feature which can be used to authenticate both cluster members and clients and to do access control checks on client operations. Access control can be done according to endpoint principal and/or endpoint address. Security can be enabled and configured either in configuration xml or using Config api.
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config http://www.hazelcast.com/schema/config/hazelcast-config-2.5.xsd" xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <security enabled="true"> ... </security> </hazelcast> Config cfg = new Config(); SecurityConfig securityCfg = cfg.getSecurityConfig(); securityCfg.setEnabled(true);
4.1. Credentials
One of the key elements in Hazelcast security is Credentials object. It is used to carry all credentials of an endpoint (member or client). Credentials is an interface which extends Serializable and has three methods to be implemented. Users, according to their needs, can either implement Credentials interface or extend AbstractCredentials class which is an abstract implementation of Credentials.
package com.hazelcast.security; ... public interface Credentials extends Serializable { String getEndpoint(); void setEndpoint(String endpoint) ; String getPrincipal() ; }
Credentials.setEndpoint() method is called by Hazelcast when auth request arrives to node before authentication takes place.
package com.hazelcast.security; ... public abstract class AbstractCredentials implements Credentials, DataSerializable { private transient String endpoint; private String principal; ... }
UsernamePasswordCredentials, a custom implementation of Credentials can be found in Hazelcast com.hazelcast.security package. It is used by default configuration during authentication process of both members and clients.
package com.hazelcast.security; ... public class UsernamePasswordCredentials extends Credentials { private byte[] password; ... }
21
4.2. ClusterLoginModule
All security attributes are carried in Credentials object and Credentials is used by LoginModule [http:// download.oracle.com/javase/1.5.0/docs/api/javax/security/auth/spi/LoginModule.html] s during authentication process. Accessing user supplied attributes from LoginModule [http://download.oracle.com/javase/1.5.0/docs/api/javax/ security/auth/spi/LoginModule.html] s is done by CallbackHandler [http://download.oracle.com/javase/1.5.0/ docs/api/javax/security/auth/callback/CallbackHandler.html] s. To provide access to Credentials object, Hazelcast uses its own specialized CallbackHandler. During initialization of LoginModules Hazelcast will pass this special CallbackHandlerinto LoginModule.initialize() method. LoginModule implementations should create an instance of com.hazelcast.security.CredentialsCallback and call handle(Callback[] callbacks) method of CallbackHandler during login process. CredentialsCallback.getCredentials() will return supplied Credentials object.
public class CustomLoginModule implements LoginModule { CallbackHandler callbackHandler; Subject subject; public final void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { this.subject = subject; this.callbackHandler = callbackHandler; } public final boolean login() throws LoginException { CredentialsCallback callback = new CredentialsCallback(); try { callbackHandler.handle(new Callback[]{callback}); credentials = cb.getCredentials(); } catch (Exception e) { throw new LoginException(e.getMessage()); } ... } ... }
* To use default Hazelcast permission policy, an instance of com.hazelcast.security.ClusterPrincipal that holding Credentials object must be created and added to Subject.principals onLoginModule.commit().
public class MyCustomLoginModule implements LoginModule { ... public boolean commit() throws LoginException { ... final Principal principal = new ClusterPrincipal(credentials); subject.getPrincipals().add(principal); return true; } ... }
Hazelcast also has an abstract implementation of LoginModule that does callback and cleanup operations and holds resulting Credentials instance. LoginModules extending ClusterLoginModule can accessCredentials, Subject, LoginModule instances and options and sharedState maps. Extending ClusterLoginModule is recommended instead of implementing all required stuff.
22
package com.hazelcast.security; ... public abstract class ClusterLoginModule implements LoginModule { protected protected protected protected } abstract abstract abstract abstract boolean boolean boolean boolean onLogin() throws LoginException; onCommit() throws LoginException; onAbort() throws LoginException; onLogout() throws LoginException;
<security enabled="true"> <member-credentials-factory class-name="com.hazelcast.examples.MyCredentialsFactory"> <properties> <property name="property1">value1</property> <property name="property2">value2</property> </properties> </member-credentials-factory> <member-login-modules> <login-module class-name="com.hazelcast.examples.MyRequiredLoginModule" usage="required"> <properties> <property name="property3">value3</property> </properties> </login-module> <login-module class-name="com.hazelcast.examples.MySufficientLoginModule" usage="sufficient"> <properties> <property name="property4">value4</property> </properties> </login-module> <login-module class-name="com.hazelcast.examples.MyOptionalLoginModule" usage="optional"> <properties> <property name="property5">value5</property> </properties> </login-module> </member-login-modules> ... </security>
You can define as many asLoginModules you wanted in configuration. Those are executed in given order. Usage attribute has 4 values; 'required', 'requisite', 'sufficient' and 'optional' as defined in javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.
package com.hazelcast.security; /** * ICredentialsFactory is used to create Credentials objects to be used * during node authentication before connection accepted by master node. */ public interface ICredentialsFactory { void configure(GroupConfig groupConfig, Properties properties); Credentials newCredentials(); void destroy(); }
23
Properties defined in configuration are passed to ICredentialsFactory.configure() method as java.util.Properties and to LoginModule.initialize() method asjava.util.Map.
4.4.1. Authentication
Authentication mechanism just works the same as cluster member authentication. Implementation of client authentication requires a Credentials and one or more LoginModule(s). Client side does not have/need a factory object to create Credentials objects likeICredentialsFactory. Credentials must be created at client side and sent to connected node during connection process.
<security enabled="true"> <client-login-modules> <login-module class-name="com.hazelcast.examples.MyRequiredClientLoginModule" usage="required"> <properties> <property name="property3">value3</property> </properties> </login-module> <login-module class-name="com.hazelcast.examples.MySufficientClientLoginModule" usage="sufficient"> <properties> <property name="property4">value4</property> </properties> </login-module> <login-module class-name="com.hazelcast.examples.MyOptionalClientLoginModule" usage="optional"> <properties> <property name="property5">value5</property> </properties> </login-module> </client-login-modules> ... </security>
You can define as many asLoginModules you wanted in configuration. Those are executed in given order. Usage attribute has 4 values; 'required', 'requisite', 'sufficient' and 'optional' as defined in javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.
final Credentials credentials = new UsernamePasswordCredentials("dev", "dev-pass"); HazelcastInstance client = HazelcastClient.newHazelcastClient(credentials, "localhost");
4.4.2. Authorization
Hazelcast client authorization is configured by a client permission policy. Hazelcast has a default permission policy implementation that uses permission configurations defined in Hazelcast security configuration. Default policy permission checks are done against instance types (map, queue...), instance names (map, queue etc. name), instance actions (put, get, remove, add...), client endpoint addresses and client principal defined by Credentials object. Instance and principal names and endpoint addresses can be defined as wildcards(*). Take a look at Wildcard Name Configuration and Newtwork Configuration pages.
24
<security enabled="true"> <client-permissions> <!-- Principal 'admin' from endpoint '127.0.0.1' has all permissions. --> <all-permissions principal="admin"> <endpoints> <endpoint>127.0.0.1</endpoint> </endpoints> </all-permissions> <!-- Principals named 'dev' from all endpoints have 'create', 'destroy', 'put', 'get' permissions for map named 'default'. --> <map-permission name="default" principal="dev"> <actions> <action>create</action> <action>destroy</action> <action>put</action> <action>get</action> </actions> </map-permission> <!-- All principals from endpoints '127.0.0.1' or matching to '10.10.*.*' have 'put', 'get', 'remove' permissions for map whose name matches to 'com.foo.entity.*'. --> <map-permission name="com.foo.entity.*"> <endpoints> <endpoint>10.10.*.*</endpoint> <endpoint>127.0.0.1</endpoint> </endpoints> <actions> <action>put</action> <action>get</action> <action>remove</action> </actions> </map-permission> <!-- Principals named 'dev' from endpoints matching to either '192.168.1.1-100' or '192.168.2.*' have 'create', 'offer', 'poll' permissions for all queues. --> <queue-permission name="*" principal="dev"> <endpoints> <endpoint>192.168.1.1-100</endpoint> <endpoint>192.168.2.*</endpoint> </endpoints> <actions> <action>create</action> <action>offer</action> <action>poll</action> </actions> </queue-permission> <!-- All principals from all endpoints have transaction permission.--> <transaction-permission /> </client-permissions> </security>
25
package com.hazelcast.security; /** * IPermissionPolicy is used to determine any Subject's * permissions to perform a security sensitive Hazelcast operation. * */ public interface IPermissionPolicy { void configure(SecurityConfig securityConfig, Properties properties); PermissionCollection getPermissions(Subject subject, Class<? extends Permission> type); void destroy(); }
Permission policy implementations can access client-permissions in configuration by using SecurityConfig.getClientPermissionConfigs() during configure(SecurityConfig securityConfig, Properties properties) method is called by Hazelcast. IPermissionPolicy.getPermissions(Subject subject, Class<? extends Permission> type) method is used to determine a client request has been granted permission to do a security-sensitive operation. Permission policy should return a PermissionCollection containing permissions of given type for givenSubject. Hazelcast access controller will call PermissionCollection.implies(Permission) on returning PermissionCollection and will decide if current Subject has permitted to access to requested resources or not.
4.4.3. Permissions
1. All Permission
2. Map Permission
<map-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </map-permission>
Actions: all, create, destroy, put, get, remove, listen, lock, stats 3. Queue Permission
<queue-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </queue-permission>
Actions: all, create, destroy, offer, poll, get, remove, listen, stats 4. Multimap Permission
26
<multimap-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </multimap-permission>
Actions: all, create, destroy, put, get, remove, listen, lock, stats 5. Topic Permission
<topic-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </topic-permission>
<list-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </list-permission>
Actions: all, create, destroy, add, set, get, remove, listen 7. Set Permission
<set-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </set-permission>
Actions: all, create, destroy, add, get, remove, listen 8. Lock Permission
<lock-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </lock-permission>
27
<atomic-number-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </atomic-number-permission>
Actions: all, create, destroy, increment, decrement, get, set, add, stats 10.CountDownLatch Permission
<countdown-latch-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </countdown-latch-permission>
<semaphore-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </semaphore-permission>
Actions: all, create, destroy, acquire, release, drain, stats 12.Executor Service Permission
<executor-service-permission name="name" principal="principal"> <endpoints> ... </endpoints> <actions> ... </actions> </executor-service-permission>
28
29
Config cfg = new Config(); HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg); Map mapa = instance.getMap("mapa"); Map mapb = instance.getMap("mapb"); Map mapc = instance.getMap("mapc"); mapa.put("key1", value); mapb.get("key1"); mapc.remove("key1"); // since map names are different, operation will be manipulating // different entries, but the operation will take place on the // same member since the keys ("key1") are the same instance.getLock ("key1").lock(); // lock operation will still execute on the same member of the cluster // since the key ("key1") is same instance.getExecutorService().execute(new DistributedTask(runnable, "key1")); // distributed execution will execute the 'runnable' on the same member // since "key1" is passed as the key.
So when the keys are the same then entries are stored on the same node. But we sometimes want to have related entries stored on the same node. Consider customer and his/her order entries. We would have customers map with customerId as the key and orders map with orderId as the key. Since customerId and orderIds are different keys, customer and his/ her orders may fall into different members/nodes in your cluster. So how can we have them stored on the same node? The trick here is to create an affinity between customer and orders. If we can somehow make them part of the same partition then these entries will be co-located. We achieve this by making orderIds PartitionAware
public class OrderKey implements Serializable, PartitionAware { int customerId; int orderId; public OrderKey(int orderId, int customerId) { this.customerId = customerId; this.orderId = orderId; } public int getCustomerId() { return customerId; } public int getOrderId() { return orderId; } public Object getPartitionKey() { return customerId; } @Override public String toString() { return "OrderKey{" + "customerId=" + customerId + ", orderId=" + orderId + '}'; } }
30
Data Affinity
Notice that OrderKey implements PartitionAware and getPartitionKey() returns the customerId. This will make sure that Customer entry and its Orders are going to be stored on the same node.
Config cfg = new Config(); HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg); Map mapCustomers = instance.getMap("customers") Map mapOrders = instance.getMap("orders") // create the customer entry with customer id = 1 mapCustomers.put(1, customer); // now create the orders for this customer mapOrders.put(new OrderKey(21, 1), order); mapOrders.put(new OrderKey(22, 1), order); mapOrders.put(new OrderKey(23, 1), order);
Let say you have a customers map where customerId is the key and the customer object is the value. and customer object contains the customer's orders. and let say you want to remove one of the orders of a customer and return the number of remaining orders. Here is how you would normally do it:
public static int removeOrder(long customerId, long orderId) throws Exception { IMap<Long, Customer> mapCustomers = instance.getMap("customers"); mapCustomers.lock (customerId); Customer customer = mapCustomers. get(customerId); customer.removeOrder (orderId); mapCustomers.put(customerId, customer); mapCustomers.unlock(customerId); return customer.getOrderCount(); }
There are couple of things we should consider: 1. There are four distributed operations there.. lock, get, put, unlock.. Can we reduce the number of distributed operations? 2. Customer object may not be that big but can we not have to pass that object through the wire? Notice that, we are actually passing customer object through the wire twice; get and put. So instead, why not moving the computation over to the member (JVM) where your customer data actually is. Here is how you can do this with distributed executor service: 1. Send a PartitionAware Callable task. 2. Callable does the deletion of the order right there and returns with the remaining order count. 3. Upon completion of the Callable task, return the result (remaining order count). Plus you do not have to wait until the the task complete; since distributed executions are asynchronous, you can do other things in the meantime. Here is a sample code:
31
Data Affinity
public static int removeOrder(long customerId, long orderId) throws Exception { ExecutorService es = instance.getExecutorService(); OrderDeletionTask task = new OrderDeletionTask(customerId, orderId); Future future = es.submit(task); int remainingOrders = future.get(); return remainingOrders; } public static class OrderDeletionTask implements Callable<Integer>, PartitionAware, Serializable { private long customerId; private long orderId; public OrderDeletionTask() { } public OrderDeletionTask(long customerId, long orderId) { super(); this.customerId = customerId; this.orderId = orderId; } public Integer call () { IMap<Long, Customer> mapCustomers = Hazelcast.getMap("customers"); mapCustomers.lock (customerId); Customer customer = mapCustomers. get(customerId); customer.removeOrder (orderId); mapCustomers.put(customerId, customer); mapCustomers.unlock(customerId); return customer.getOrderCount(); } public Object getPartitionKey() { return customerId; } }
Benefits of doing the same operation with distributed ExecutorService based on the key are: Only one distributed execution (es.submit(task)), instead of four. Less data is sent over the wire. Since lock/update/unlock cycle is done locally (local to the customer data), lock duration for the Customer entry is much less so enabling higher concurrency.
32
operations: clear, reset statistics Map name size operations: clear Queue name size received and served items operations: clear, reset statistics Topic name number of messages dispatched since creation, in last second max messages dispatched per second
34
7.3. LiteMember
LiteMembers are members with no storage. If -Dhazelcast.lite.member=true JVM parameter is set, then the JVM will join the cluster as a 'lite member' which will not be a 'data partition' (no data on that node) but will have super fast access to the cluster just like any regular member does.
35
Chapter 8. Transactions
8.1. Transaction Interface
Hazelcast can be used in transactional context. Basically start a transaction, work with queues, maps, sets and do other things then commit/rollback in one shot.
import import import import import java.util.Queue; java.util.Map; java.util.Set; com.hazelcast.core.Hazelcast; com.hazelcast.core.Transaction;
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); Queue queue = hz.getQueue("myqueue"); Map map = hz.getMap ("mymap"); Set set = hz.getSet ("myset"); Transaction txn = hz.getTransaction(); txn.begin(); try { Object obj = queue.poll(); //process obj map.put ("1", "value1"); set.add ("value"); //do other things.. txn.commit(); }catch (Throwable t) { txn.rollback(); }
Isolation is always REPEATABLE_READ . If you are in a transaction, you can read the data in your transaction and the data that is already committed and if not in a transaction, you can only read the committed data. Implementation is different for queue and map/set. For queue operations (offer,poll), offered and/or polled objects are copied to the next member in order to safely commit/rollback. For map/set, Hazelcast first acquires the locks for the write operations (put, remove) and holds the differences (what is added/removed/updated) locally for each transaction. When transaction is set to commit, Hazelcast will release the locks and apply the differences. When rolling back, Hazelcast will simply releases the locks and discard the differences. Transaction instance is attached to the current thread and each Hazelcast operation checks if the current thread holds a transaction, if so, operation will be transaction aware. When transaction is committed, rolled back or timed out, it will be detached from the thread holding it.
36
Transactions
import="javax.resource.ResourceException" %> import="javax.transaction.*" %> import="javax.naming.*" %> import="javax.resource.cci.*" %> import="java.util.*" %> import="com.hazelcast.core.Hazelcast" %>
<% UserTransaction txn = null; Connection conn = null; Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); Queue queue = hz.getQueue ("default"); Map map = hz.getMap ("default"); Set set = hz.getSet ("default"); List list = hz.getList ("default"); try { Context context = new InitialContext(); txn = (UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); ConnectionFactory cf = (ConnectionFactory) context.lookup ("java:comp/env/HazelcastCF"); conn = cf.getConnection(); queue.offer("newitem"); map.put ("1", "value1"); set.add ("item1"); list.add ("listitem1"); txn.commit(); } catch (Throwable e) { if (txn != null) { try { txn.rollback(); } catch (Exception ix) {ix.printStackTrace();}; } e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (Exception ignored) {}; } } %>
37
Transactions
Notice that we didn't have to put sun-ra.xml into the rar file because it comes with the hazelcast-ra<version>.rar file already. If Hazelcast resource is used from EJBs, you should configure ejb-jar.xml for resource reference and JNDI definitions, just like we did forweb.xml.
If Hazelcast resource is used from EJBs, you should configure ejb-jar.xml and jboss.xml for resource reference and JNDI definitions.
38
Echo callable above, for instance, in its call() method, is returning the local member and the input passed in. Remember that Hazelcast.getCluster().getLocalMember() returns the local member and toString() returns the member's address (ip + port) in String form, just to see which member actually executed the code for our example. Of course, call() method can do and return anything you like. Executing a task by using executor framework is very straight forward. Simply obtain a ExecutorService instance, generally via Executors and submit the task which returns a Future. After executing task, you don't have to wait for execution to complete, you can process other things and when ready use the future object to retrieve the result as show in code below.
ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<String> future = executorService.submit (new Echo("myinput")); //while it is executing, do some useful stuff //when ready, get the result of your execution String result = future.get();
If you need access to the current HazelcastInstance you are executing the task under, implement the interface HazelcastInstanceAware. This will call the method setHazelcastInstance() prior to executing your task.
39
public void echoOnTheMember(String input, Member member) throws Exception { FutureTask<String> task = new DistributedTask<String>(new Echo(input), member); Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); ExecutorService executorService = hz.getExecutorService(); executorService.execute(task); String echoResult = task.get(); } public void echoOnTheMemberOwningTheKey(String input, Object key) throws Exception { FutureTask<String> task = new DistributedTask<String>(new Echo(input), key); Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); ExecutorService executorService = hz.getExecutorService(); executorService.execute(task); String echoResult = task.get(); } public void echoOnSomewhere(String input) throws Exception { Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); ExecutorService executorService = hz.getExecutorService(); Future<String> task = executorService.submit(new Echo(input)); String echoResult = task.get(); } public void echoOnMembers(String input, Set<Member> members) throws Exception { Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); MultiTask<String> task = new MultiTask<String>(new Echo(input), members); ExecutorService executorService = hz.getExecutorService(); executorService.execute(task); Collection<String> results = task.get(); }
Note that you can obtain the set of cluster members via Hazelcast.getCluster().getMembers() call. You can also extend the MultiTask class to override set(V result), setException(Throwable exception), done() methods for custom behaviour. Just like java.util.concurrent.FutureTask.get() , MultiTask.get() will throw java.util.concurrent.ExecutionException if any of the executions throws exception.
40
public class Fibonacci implements Callable<Long>, Serializable { int input = 0; public Fibonacci() { } public Fibonacci(int input) { this.input = input; } public Long call() { return calculate (input); } private long calculate (int n) { if (Thread.currentThread().isInterrupted()) return 0; if (n <= 1) return n; else return calculate(n-1) + calculate(n-2); } }
The callable class above calculates the fibonacci number for a given number. In the calculate method, we are checking to see if the current thread is interrupted so that code can be responsive to cancellations once the execution started. Following fib() method submits the Fibonacci calculation task for number 'n' and waits maximum 3 seconds for result. If the execution doesn't complete in 3 seconds, future.get() will throw TimeoutException and upon catching it we interruptibly cancel the execution for saving some CPU cycles.
long fib(int n) throws Exception { Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); ExecutorService es = hz.getExecutorService(); Future future = es.submit(new Fibonacci(n)); try { return future.get(3, TimeUnit.SECONDS); } catch (TimeoutException e) { future.cancel(true); } return -1; }
fib(20) will probably will take less than 3 seconds but fib(50) will take way longer. (This is not the example for writing better fibonacci calculation code but for showing how to cancel a running execution that takes too long.) future.cancel(false) can only cancel execution before it is running (executing) but future.cancel(true) can interrupt running executions if your code is able to handle the interruption. So if you are willing to be able to cancel already running task then your task has to be designed to handle interruption. If calculate (int n) method didn't have if (Thread.currentThread().isInterrupted()) line, then you wouldn't be able to cancel the execution after it started.
41
Config cfg = new Config(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); ExecutorService es = hz.getExecutorService(); DistributedTask<String> task = new DistributedTask<String>(new Fibonacci(10)); task.setExecutionCallback(new ExecutionCallback<Long> () { public void done (Future<Long> future) { try { if (! future.isCancelled()) { System.out.println("Fibonacci calculation result = " + future.get()); } } catch (Exception e) { e.printStackTrace(); } } }); es.execute(task);
You could have achieved the same results by extending DistributedTask and overriding the DistributedTask.done() method.
import import import import com.hazelcast.core.Hazelcast; com.hazelcast.core.DistributedTask; java.util.concurrent.ExecutorService; java.util.concurrent.Future;
ExecutorService es = Hazelcast.getExecutorService(); es.execute(new DistributedTask<String>(new Fibonacci(10)) { public void done () { try { if (! isCancelled()) { System.out.println("Fibonacci calculation result = " + get()); } } catch (Exception e) { e.printStackTrace(); } } });
42
43
<filter> <filter-name>hazelcast-filter</filter-name> <filter-class>com.hazelcast.web.WebFilter</filter-class> <!-Name of the distributed map storing your web session objects --> <init-param> <param-name>map-name</param-name> <param-value>my-sessions</param-value> </init-param> <!-How is your load-balancer configured? stick-session means all requests of a session is routed to the node where the session is first created. This is excellent for performance. If sticky-session is set to false, when a session is updated on a node, entry for this session on all other nodes is invalidated. You have to know how your load-balancer is configured before setting this parameter. Default is true. --> <init-param> <param-name>sticky-session</param-name> <param-value>true</param-value> </init-param> <!-Name of session id cookie --> <init-param> <param-name>cookie-name</param-name> <param-value>hazelcast.sessionId</param-value> </init-param> <!-Domain of session id cookie. Default is based on incoming request. --> <init-param> <param-name>cookie-domain</param-name> <param-value>.mywebsite.com</param-value> </init-param> <!-Should cookie only be sent using a secure protocol? Default is false. --> <init-param> <param-name>cookie-secure</param-name> <param-value>false</param-value> </init-param> <!-Should HttpOnly attribute be set on cookie ? Default is false. --> <init-param> <param-name>cookie-http-only</param-name> <param-value>false</param-value> </init-param> <!-Are you debugging? Default is false. --> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <!-Configuration xml location; * as servlet resource OR * as classpath resource OR * as URL Default is one of hazelcast-default.xml or hazelcast.xml in classpath. --> <init-param> <param-name>config-location</param-name> <param-value>/WEB-INF/hazelcast.xml</param-value> </init-param> <!-Do you want to use an existing HazelcastInstance? Default is null. 44 --> <init-param> <param-name>instance-name</param-name> <param-value>default</param-value>
<!-Do you want to connect as a client to an existing cluster? Default is false. --> <init-param> <param-name>use-client</param-name> <param-value>false</param-value> </init-param> <!-Client configuration location; * as servlet resource OR * as classpath resource OR * as URL Default is null. --> <init-param> <param-name>client-config-location</param-name> <param-value>/WEB-INF/hazelcast-client.properties</param-value> </init-param> <!-Do you want to shutdown HazelcastInstance during web application undeploy process? Default is true. --> <init-param> <param-name>shutdown-on-destroy</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>hazelcast-filter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping> <listener> <listener-class>com.hazelcast.web.SessionListener</listener-class> </listener>
3. Package and deploy your war file as you would normally do. It is that easy! All http requests will go through Hazelcast WebFilter and it will put the session objects into Hazelcast distributed map if needed. Info about sticky-sessions: Hazelcast holds whole session attributes in a distributed map and in local http session. Local session is required for fast access to data and distributed map is needed for fail-safety. If sticky-session is not used, whenever a session a attribute is updated in a node (in both node local session and clustered cache), that attribute should be invalidated in all other nodes' local sessions, because now they have dirty value. So when a request arrives one of those other nodes that attribute value is fetched from clustered cache. To overcome performance penalty of sending invalidation messages during updates, sticky-sessions can be used. If Hazelcast knows sessions are sticky, invalidation will not be send, because Hazelcast assumes there is no other local session at the moment. When a server is down, requests belonging to a session hold in that server will routed to other one and that server will fetch session data from clustered cache. That means using sticky-sessions, one will not suffer performance penalty of accessing clustered data and can benefit recover from a server failure.
45
<hazelcast> <wan-replication name="my-wan-cluster"> <target-cluster group-name="tokyo" group-password="tokyo-pass"> <replication-impl>com.hazelcast.impl.wan.WanNoDelayReplication</replication-impl> <end-points> <address>10.2.1.1:5701</address> <address>10.2.1.2:5701</address> </end-points> </target-cluster> <target-cluster group-name="london" group-password="london-pass"> <replication-impl>com.hazelcast.impl.wan.WanNoDelayReplication</replication-impl> <end-points> <address>10.3.5.1:5701</address> <address>10.3.5.2:5701</address> </end-points> </target-cluster> </wan-replication> <network> ... </network> </network> ... </hazelcast>
This can be the configuration of the cluster running in NY, replicating to Tokyo and London. Tokyo and London clusters should have similar configurations if they are also active replicas. If NY and London cluster configurations contain wan-replication element and Tokyo cluster doesn't then it means NY and London are active endpoints and Tokyo is passive endpoint. As noted earlier you can have Hazelcast replicate some or all of the data in your clusters. You might have 5 different distributed maps but you might want only one of these maps replicating across clusters. So you mark which maps to replicate by adding wan-replication-ref element into map configuration.
46
WAN Replication
<hazelcast> <wan-replication name="my-wan-cluster"> ... </wan-replication> <network> ... </network> <map name="my-shared-map"> ... <wan-replication-ref name="my-wan-cluster"> <merge-policy>hz.PASS_THROUGH</merge-policy> </wan-replication-ref> </map> </network> ... </hazelcast>
Here we have my-shared-map is configured to replicate itself to the cluster targets defined in the wanreplication element. Note that you will also need to define a merge policy for merging replica entries and resolving conflicts during the merge. Default merge policy is hz.PASS_THROUGH which will apply all in-coming updates as is.
47
48
Configuration
Config cfg = new Config(); cfg.setPort(5900); cfg.setPortAutoIncrement(false); NetworkConfig network = cfg.getNetworkConfig(); Join join = network.getJoin(); join.getMulticastConfig().setEnabled(false); join.getTcpIpConfig().addMember("10.45.67.32").addMember("10.45.67.100") .setRequiredMember("192.168.10.100").setEnabled(true); network.getInterfaces().setEnabled(true).addInterface("10.45.67.*"); MapConfig mapCfg = new MapConfig(); mapCfg.setName("testMap"); mapCfg.setBackupCount(2); mapCfg.getMaxSizeConfig().setSize(10000); mapCfg.setTimeToLiveSeconds(300); MapStoreConfig mapStoreCfg = new MapStoreConfig(); mapStoreCfg.setClassName("com.hazelcast.examples.DummyStore").setEnabled(true); mapCfg.setMapStoreConfig(mapStoreCfg); NearCacheConfig nearCacheConfig = new NearCacheConfig(); nearCacheConfig.setMaxSize(1000).setMaxIdleSeconds(120).setTimeToLiveSeconds(300); mapCfg.setNearCacheConfig(nearCacheConfig); cfg.addMapConfig(mapCfg);
After creating Config object, you can use it to initialize default Hazelcast instance or create a new Hazelcast instance. Hazelcast.init(cfg); Hazelcast.newHazelcastInstance(cfg);
To retrieve an existing HazelcastInstance using its name, use; Hazelcast.getHazelcastInstanceByName('my-instance'); To retrieve all existingHazelcastInstances, use; Hazelcast.getAllHazelcastInstances();
49
Configuration
You can also set the groupName with Config API. JVM can host multiple Hazelcast instances (nodes). Each node can only participate in one group and it only joins to its own group, does not mess with others. Following code creates 3 separate Hazelcast nodes, h1 belongs to app1 cluster, while h2 and h3 are belong to app2 cluster.
Config configApp1 = new Config(); configApp1.getGroupConfig().setName("app1"); Config configApp2 = new Config(); configApp2.getGroupConfig().setName("app2"); HazelcastInstance h1 = Hazelcast.newHazelcastInstance(configApp1); HazelcastInstance h2 = Hazelcast.newHazelcastInstance(configApp2); HazelcastInstance h3 = Hazelcast.newHazelcastInstance(configApp2);
50
Configuration
<hazelcast> ... <network> .... <interfaces enabled="true"> <interface>10.3.16.*</interface> <interface>10.3.10.4-18</interface> <interface>192.168.1.3</interface> </interfaces> </network> ... </hazelcast>
<join> <multicast enabled="false"> <multicast-group>224.2.2.3</multicast-group> <multicast-port>54327</multicast-port> </multicast> <tcp-ip enabled="false"> <interface>192.168.1.2</interface> </tcp-ip> <aws enabled="true"> <access-key>my-access-key</access-key> <secret-key>my-secret-key</secret-key> <region>us-west-1</region> <!-- optional, default is us-east-1 --> <host-header>ec2.amazonaws.com</host-header> <!-- optional, default is ec2.amazonaws.com If set, region shouldn't be set as it will override this prop <security-group-name>hazelcast-sg</security-group-name> <!-- optional --> <tag-key>type</tag-key> <!-- optional --> <tag-value>hz-nodes</tag-value> <!-- optional --> </aws> </join>
You need to add hazelcast-cloud.jar dependency into your project. Note that it is also bundled inside hazelcast-all.jar. hazelcast-cloud module doesn't depend on any other third party modules.
51
Configuration
pause take locally owned map entries close all its network connections (detach from its cluster) join to the new cluster send merge request for each its locally owned map entry resume So each member of the merging cluster is actually rejoining to the new cluster and sending merge request for each its locally owned map entry. Q: Which cluster will merge into the other? A. Smaller cluster will merge into the bigger one. If they have equal number of members then a hashing algorithm determines the merging cluster. Q. Each cluster may have different versions of the same key in the same map. How is the conflict resolved? A. Destination cluster will decide how to handle merging entry based on the MergePolicy set for that map. There are built-in merge policies such as hz.NO_MERGE, hz.ADD_NEW_ENTRY and hz.LATEST_UPDATE but you can develop your own merge policy by implementing com.hazelcast.merge.MergePolicy. You should register your custom merge policy in the configuration so that Hazelcast can find it by name.
public interface MergePolicy { /** * Returns the value of the entry after the merge * of entries with the same key. Returning value can be * You should consider the case where existingEntry is null. * * @param mapName name of the map * @param mergingEntry entry merging into the destination cluster * @param existingEntry existing entry in the destination cluster * @return final value of the entry. If returns null then no change on the entry. */ Object merge(String mapName, MapEntry mergingEntry, MapEntry existingEntry); }
Here is how merge policies are registered and specified per map.
52
Configuration
<hazelcast> ... <map name="default"> <backup-count>1</backup-count> <eviction-policy>NONE</eviction-policy> <max-size>0</max-size> <eviction-percentage>25</eviction-percentage> <!-While recovering from split-brain (network partitioning), map entries in the small cluster will merge into the bigger cluster based on the policy set here. When an entry merge into the cluster, there might an existing entry with the same key already. Values of these entries might be different for that same key. Which value should be set for the key? Conflict is resolved by the policy set here. Default policy is hz.ADD_NEW_ENTRY There are built-in merge policies such as hz.NO_MERGE ; no entry will merge. hz.ADD_NEW_ENTRY ; entry will be added if the merging entry's key doesn't exist in the cluster. hz.HIGHER_HITS ; entry with the higher hits wins. hz.LATEST_UPDATE ; entry with the latest update wins. --> <merge-policy>MY_MERGE_POLICY</merge-policy> </map> <merge-policies> <map-merge-policy name="MY_MERGE_POLICY"> <class-name>com.acme.MyOwnMergePolicy</class-name> </map-merge-policy> </merge-policies> ... </hazelcast>
12.2.5. SSL
Hazelcast allows you to use SSL socket communication among all Hazelcast members. You need to implement com.hazelcast.nio.ssl.SSLContextFactory and configure SSL section in network configuration.
public class MySSLContextFactory implements SSLContextFactory { public void init(Properties properties) throws Exception { } public SSLContext getSSLContext() { ... SSLContext sslCtx = SSLContext.getInstance(protocol); return sslCtx; } } <hazelcast> ... <network> ... <ssl enabled="true"> <factory-class-name>com.hazelcast.examples.MySSLContextFactory</factory-class-name> <properties> <property name="foo">bar</property> </properties> </ssl> </network> ... </hazelcast>
Hazelcast provides a default SSLContextFactory; com.hazelcast.nio.ssl.BasicSSLContextFactory which uses configured keystore to initialize SSLContext. All required is to define keyStore
53
Configuration
and keyStorePassword. Also you can set keyManagerAlgorithm (default SunX509), trustManagerAlgorithm (default SunX509) and protocol (default TLS).
<hazelcast> ... <network> ... <ssl enabled="true"> <factory-class-name>com.hazelcast.nio.ssl.BasicSSLContextFactory</factory-class-name> <properties> <property name="keyStore">keyStore</property> <property name="keyStorePassword">keyStorePassword</property> <property name="keyManagerAlgorithm">SunX509</property> <property name="trustManagerAlgorithm">SunX509</property> <property name="protocol">TLS</property> </properties> </ssl> </network> ... </hazelcast>
You can also set keyStore and keyStorePassword through javax.net.ssl.keyStore and javax.net.ssl.keyStorePassword system properties. Note that, you can not use SSL when Hazelcast Encryption is enabled.
12.2.6. Encryption
Hazelcast allows you to encrypt entire socket level communication among all Hazelcast members. Encryption is based on Java Cryptography Architecture [http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html] and both symmetric and asymmetric encryption are supported. In symmetric encryption, each node uses the same key, so the key is shared. Here is a sample configuration for symmetric encryption:
<hazelcast> ... <network> ... <!-Make sure to set enabled=true Make sure this configuration is exactly the same on all members --> <symmetric-encryption enabled="true"> <!-encryption algorithm such as DES/ECB/PKCS5Padding, PBEWithMD5AndDES, Blowfish, DESede --> <algorithm>PBEWithMD5AndDES</algorithm> <!-- salt value to use when generating the secret key --> <salt>thesalt</salt> <!-- pass phrase to use when generating the secret key --> <password>thepass</password> <!-- iteration count to use when generating the secret key --> <iteration-count>19</iteration-count> </symmetric-encryption> </network> ... </hazelcast>
In asymmetric encryption, public and private key pair is used. Data is encrypted with one of these keys and decrypted with the other. The idea is that each node has to have its own private key and other trusted members' public key. So that means, for each member, we should do the followings:
54
Configuration
Pick a unique name for the member. We will use the name as the key alias. Let's name them as member1, member2...memberN. Generate the keystore and the private key for the member1. keytool -genkey -alias member1 -keyalg RSA -keypass thekeypass -keystore keystore -storetype JKS Remember all the parameters you used here because you will need this information when you configure asymmetric-encryption in your hazelcast.xml file. Create a public certificate file so that we can add it to the other members' keystore keytool -export -alias member1 -keypass thekeypass -storepass thestorepass -keystore keystore -rfc file member1.cer Now take all the other members' public certificates, and add (import) them into member1's keystore
keytool -import -alias member2 -file member2.cer -keystore keystore -storepass thestorepass keytool -import -alias member3 -file member3.cer -keystore keystore -storepass thestorepass ... keytool -import -alias memberN -file memberN.cer -keystore keystore -storepass thestorepass
You should repeat these steps for each trusted member in your cluster. Here is a sample configuration for asymmetric encryption:
<hazelcast> ... <network> ... <!-Make sure to set enabled=true --> <asymmetric-encryption enabled="true"> <!-- encryption algorithm --> <algorithm>RSA/NONE/PKCS1PADDING</algorithm> <!-- private key password --> <keyPassword>thekeypass</keyPassword> <!-- private key alias --> <keyAlias>member1</keyAlias> <!-- key store type --> <storeType>JKS</storeType> <!-- key store password --> <storePassword>thestorepass</storePassword> <!-- path to the key store --> <storePath>keystore</storePath> </asymmetric-encryption> </network> ... </hazelcast>
55
Configuration
public class MySocketInterceptor implements MemberSocketInterceptor { public void init(SocketInterceptorConfig socketInterceptorConfig) { // initialize interceptor } void onConnect(Socket connectedSocket) throws IOException { // do something meaningful when connected } public void onAccept(Socket acceptedSocket) throws IOException { // do something meaningful when accepted a connection } } <hazelcast> ... <network> ... <socket-interceptor enabled="true"> <class-name>com.hazelcast.examples.MySocketInterceptor</class-name> <properties> <property name="kerberos-host">kerb-host-name</property> <property name="kerberos-config-file">kerb.conf</property> </properties> </socket-interceptor> </network> ... </hazelcast>
public class MyClientSocketInterceptor implements SocketInterceptor { void onConnect(Socket connectedSocket) throws IOException { // do something meaningful when connected } } ClientConfig clientConfig = new ClientConfig(); clientConfig.setGroupConfig(new GroupConfig("dev","dev-pass")).addAddress("10.10.3.4"); MyClientSocketInterceptor myClientSocketInterceptor = new MyClientSocketInterceptor(); clientConfig.setSocketInterceptor(myClientSocketInterceptor); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
56
Configuration
<hazelcast> ... <network> <port auto-increment="true">5701</port> <join> <multicast enabled="false"> <multicast-group>FF02:0:0:0:0:0:0:1</multicast-group> <multicast-port>54327</multicast-port> </multicast> <tcp-ip enabled="true"> <member>[fe80::223:6cff:fe93:7c7e]:5701</member> <interface>192.168.1.0-7</interface> <interface>192.168.1.*</interface> <interface>fe80:0:0:0:45c5:47ee:fe15:493a</interface> </tcp-ip> </join> <interfaces enabled="true"> <interface>10.3.16.*</interface> <interface>10.3.10.4-18</interface> <interface>fe80:0:0:0:45c5:47ee:fe15:*</interface> <interface>fe80::223:6cff:fe93:0-5555</interface> </interfaces> ... </network>
JVM has two system properties for setting the preferred protocol stack IPv4 or IPv6 as well as the preferred address family types inet4 or inet6. On a dual stack machine IPv6 stack is preferred by default, this can be changed through java.net.preferIPv4Stack=<true|false> system property. And when querying name services JVM prefers IPv4 addressed over IPv6 addresses and will return an IPv4 address if possible. This can be changed through java.net.preferIPv6Addresses=<true|false> system property. Also see additional details on IPv6 support in Java [http://docs.oracle.com/javase/1.5.0/docs/guide/net/ipv6_guide/ index.html#details]. Note: IPv6 support has been switched off by default, since some platforms have issues in use of IPv6 stack. And some other platforms such as Amazon AWS have no support at all. To enable IPv6 support, just set configuration property hazelcast.prefer.ipv4.stack to false. See Configuration Properties.
57
Configuration
... NetworkConfig networkConfig = config.getNetworkConfig(); networkConfig.addOutboundPortDefinition("35000-35100"); // ports between 35000 and 35100 networkConfig.addOutboundPortDefinition("36001, 36002, 36003"); // comma separated ports networkConfig.addOutboundPort(37000); networkConfig.addOutboundPort(37001); ...
Second one is custom grouping using Hazelcast's interface matching configuration. This way, you can add different and multiple interfaces to a group. You can also use wildcards in interface addresses.
<partition-group enabled="true" group-type="CUSTOM"> <member-group> <interface>10.10.0.*</interface> <interface>10.10.3.*</interface> <interface>10.10.5.*</interface> </member-group> <member-group> <interface>10.10.10.10-100</interface> <interface>10.10.1.*</interface> <interface>10.10.2.*</interface> </member-group </partition-group>
58
Configuration
Config config = ...; PartitionGroupConfig partitionGroupConfig = config.getPartitionGroupConfig(); partitionGroupConfig.setEnabled(true).setGroupType(MemberGroupType.CUSTOM); MemberGroupConfig memberGroupConfig = new MemberGroupConfig(); memberGroupConfig.addInterface("10.10.0.*") .addInterface("10.10.3.*").addInterface("10.10.5.*"); MemberGroupConfig memberGroupConfig2 = new MemberGroupConfig(); memberGroupConfig2.addInterface("10.10.10.10-100") .addInterface("10.10.1.*").addInterface("10.10.2.*"); partitionGroupConfig.addMemberGroupConfig(memberGroupConfig); partitionGroupConfig.addMemberGroupConfig(memberGroupConfig2);
Downside of attaching listeners using API is possibility of missing events between creation of object and registering listener. To overcome this race condition Hazelcast introduces registration of listeners in configuration. Listeners can be registered using either Hazelcast XML configuration, Config API or Spring configuration. MembershipListener Hazelcast XML configuration
<listeners> <listener>com.hazelcast.examples.MembershipListener</listener> </listeners>
Config API
59
Configuration
config.addListenerConfig(new ListenerConfig("com.hazelcast.examples.MembershipListener"));
Config API
config.addListenerConfig(new ListenerConfig("com.hazelcast.examples.InstanceListener"));
Config API
config.addListenerConfig(new ListenerConfig("com.hazelcast.examples.MigrationListener"));
60
Configuration
Config API
config.addListenerConfig(new ListenerConfig("com.hazelcast.examples.LifecycleListen
Config API
<hz:map name="default"> <hz:entry-listeners> <hz:entry-listener class-name="com.hazelcast.spring.DummyEntryListener" include-value="true"/> <hz:entry-listener implementation="dummyEntryListener" local="true"/> </hz:entry-listeners> </hz:map>
Config API
61
Configuration
<hz:multimap name="default" value-collection-type="LIST"> <hz:entry-listeners> <hz:entry-listener class-name="com.hazelcast.spring.DummyEntryListener" include-value="true"/> <hz:entry-listener implementation="dummyEntryListener" local="true"/> </hz:entry-listeners> </hz:multimap>
Config API
<hz:queue name="default" max-size-per-jvm="1000" backing-map-ref="default"> <hz:item-listeners> <hz:item-listener class-name="com.hazelcast.spring.DummyItemListener" include-value="true"/> </hz:item-listeners> </hz:queue>
Config API
topicConfig.addMessageListenerConfig(new ListenerConfig("com.hazelcast.examples.MessageListener"));
Configuration
Note that, with a limitation of a single usage, asterisk (*) can be placed anywhere inside the configuration name. For instance a map named 'com.hazelcast.test.mymap' can be configured using one of these configurations;
<map name="com.hazelcast.test.*"> ... </map> <map name="com.hazel*"> ... </map> <map name="*.test.mymap"> ... </map> <map name="com.*test.mymap"> ... </map>
Or a queue 'com.hazelcast.test.myqueue'
<queue name="*hazelcast.test.myqueue"> ... </queue> <queue name="com.hazelcast.*.myqueue"> ... </queue>
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config http://www.hazelcast.com/schema/config/hazelcast-config-2.5.xsd" xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> .... <properties> <property name="hazelcast.property.foo">value</property> .... </properties> </hazelcast>
Configuration API
System Property 1. Using JVM parameter: java -Dhazelcast.property.foo=value 2. Using System class: System.setProperty("hazelcast.property.foo", "value"); 63
Configuration
Enable (strict) redo for b node failures, but genera backups are restored. Wh #hazelcast.partition.migr
hazelcast.max.operation.timeout hazelcast.max.concurrent.operation.limit hazelcast.socket.bind.any hazelcast.socket.server.bind.any hazelcast.socket.client.bind.any hazelcast.socket.receive.buffer.size hazelcast.socket.send.buffer.size hazelcast.socket.keep.alive hazelcast.socket.no.delay hazelcast.prefer.ipv4.stack hazelcast.shutdownhook.enabled hazelcast.wait.seconds.before.join hazelcast.max.wait.seconds.before.join hazelcast.heartbeat.interval.seconds hazelcast.max.no.heartbeat.seconds hazelcast.icmp.enabled hazelcast.icmp.timeout hazelcast.icmp.ttl hazelcast.master.confirmation.interval.seconds hazelcast.max.no.master.confirmation.seconds hazelcast.member.list.publish.interval.seconds
Socket receive buffer siz Socket set keep alive Socket set TCP no delay
64
Configuration
Property Name hazelcast.prefer.ipv4.stack hazelcast.initial.min.cluster.size hazelcast.initial.wait.seconds hazelcast.restart.on.max.idle hazelcast.map.partition.count hazelcast.map.max.backup.count hazelcast.map.remove.delay.seconds hazelcast.map.cleanup.delay.seconds hazelcast.executor.query.thread.count hazelcast.executor.event.thread.count hazelcast.executor.client.thread.count hazelcast.executor.store.thread.count hazelcast.log.state hazelcast.jmx hazelcast.jmx.detailed hazelcast.mc.map.excludes hazelcast.mc.queue.excludes hazelcast.mc.topic.excludes hazelcast.version.check.enabled hazelcast.topic.flow.control.enabled hazelcast.mc.max.visible.instance.count hazelcast.connection.monitor.interval hazelcast.connection.monitor.max.faults hazelcast.partition.migration.interval hazelcast.partition.migration.timeout hazelcast.immediate.backup.interval hazelcast.graceful.shutdown.max.wait hazelcast.force.throw.interrupted.exception hazelcast.mc.url.change.enabled hazelcast.elastic.memory.enabled hazelcast.elastic.memory.total.size hazelcast.elastic.memory.chunk.size hazelcast.elastic.memory.shared.storage hazelcast.enterprise.license.key hazelcast.system.log.enabled
Description
65
Configuration
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config http://www.hazelcast.com/schema/config/hazelcast-config-2.5.xsd" xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> .... <properties> <property name="hazelcast.logging.type">jdk</property> .... </properties> </hazelcast>
Configuration API
System Property 1. Using JVM parameter: java -Dhazelcast.logging.type=slf4j 2. Using System class: System.setProperty("hazelcast.logging.type", "none"); To use custom logging feature you should implement com.hazelcast.logging.LoggerFactory and com.hazelcast.logging.ILogger interfaces and set system property hazelcast.logging.class to your custom LoggerFactory class name.
java -Dhazelcast.logging.class=foo.bar.MyLoggingFactory
You can also listen to logging events generated by Hazelcast runtime by registering LogListeners toLoggingService.
LogListener listener = new LogListener() { public void log(LogEvent logEvent) { // do something } } LoggingService loggingService = Hazelcast.getLoggingService(); loggingService.addLogListener(Level.INFO, listener):
66
Configuration
Through the LoggingService you can get the current used ILogger implementation and log your own messages too.
To be able to use Hazelcast Enterprise Edition, you need to set license key in configuration.
67
To configure Hazelcast for Hibernate, it is enough to put configuration file named hazelcast.xml into root of your classpath. If Hazelcast can not find hazelcast.xml then it will use default configuration from hazelcast.jar. You can define custom named Hazelcast configuration xml file with one of these Hibernate configuration properties.
<property name="hibernate.cache.provider_configuration_file_resource_path"> hazelcast-custom-config.xml </property>
or
<property name="hibernate.cache.hazelcast.configuration_file_path"> hazelcast-custom-config.xml </property>
You can set up Hazelcast to connect cluster as LiteMember. LiteMember is a member of the cluster, it has socket connection to every member in the cluster and it knows where the data, but does not contain any data.
<property name="hibernate.cache.hazelcast.use_lite_member">true</property>
You can set up Hazelcast to connect cluster as Native Client. Native client is not member and it connects to one of the cluster members and delegates all cluster wide operations to it. When the relied cluster member dies, client will transparently switch to another live member. (Native Client property takes precedence over LiteMember property.)
<property name="hibernate.cache.hazelcast.use_native_client">true</property>
To setup Native Client properly, you should add Hazelcast group-name, group-password and cluster member address properties. Native Client will connect to defined member and will get addresses of all members in the cluster. If the connected member will die or leave the cluster, client will automatically switch to another member in the cluster.
<property name="hibernate.cache.hazelcast.native_client_address">10.34.22.15</property> <property name="hibernate.cache.hazelcast.native_client_group">dev</property> <property name="hibernate.cache.hazelcast.native_client_password">dev-pass</property>
To use Native Client you should add hazelcast-client-<version>.jar into your classpath. Read more about NativeClient & LiteMember If you are using one of Hibernate pre-3.3 version, add following property. 68
If you are using Hibernate 3.3.x (or newer) version, you can choose to use either configuration property above (Hibernate has a built-in bridge to use old-style cache implementations) or following property.
<property name="hibernate.cache.region.factory_class"> com.hazelcast.hibernate.HazelcastCacheRegionFactory </property>
Or as an alternative you can use HazelcastLocalCacheRegionFactory which stores data in local node and sends invalidation messages when an entry is updated on local.
<property name="hibernate.cache.region.factory_class"> com.hazelcast.hibernate.HazelcastLocalCacheRegionFactory </property>
Hazelcast creates a separate distributed map for each Hibernate cache region. So these regions can be configured easily via Hazelcast map configuration. You can define backup, eviction, TTL and Near Cache properties. Backup Configuration Eviction And TTL Configuration Near Cache Configuration Hibernate has four cache concurrency strategies: read-only, read-write, nonstrict-read-write and transactional. But Hibernate does not forces cache providers to support all strategies. And Hazelcast supports first three (read-only, readwrite, nonstrict-read-write) of these four strategies. Hazelcast has no support fortransactional strategy yet. If you are using xml based class configurations, you should add a cache element into your configuration with usage attribute with one of read-only, read-write, nonstrict-read-write.
<class name="eg.Immutable" mutable="false"> <cache usage="read-only"/> .... </class> <class name="eg.Cat" .... > <cache usage="read-write"/> .... <set name="kittens" ... > <cache usage="read-write"/> .... </set> </class>
If you are using Hibernate-Annotations then you can add class-cache or collection-cache element into your Hibernate configuration file with usage attribute with one of read only, read/write, nonstrict read/write.
<class-cache usage="read-only" class="eg.Immutable"/> <class-cache usage="read-write" class="eg.Cat"/> <collection-cache collection="eg.Cat.kittens" usage="read-write"/>
OR Alternatively, you can put Hibernate Annotation's @Cache annotation on your entities and collections.
69
The last thing you should be aware of is to drop hazelcast-hibernate-<version>.jar into your classpath.
Additional Properties:
Accessing underlying HazelcastInstance Using com.hazelcast.hibernate.instance.HazelcastAccessor you can access the underlying HazelcastInstance used by Hibernate SessionFactory.
SessionFactory sessionFactory = ...; HazelcastInstance hazelcastInstance = HazelcastAccessor.getHazelcastInstance(sessionFactory);
Changing/setting lock timeout value of read-write strategy Lock timeout value can be set using hibernate.cache.hazelcast.lock_timeout Hibernate property. Value should be in milliseconds and default value is 10000 ms (10 seconds). Using named HazelcastInstance Instead of creating a new HazelcastInstance for each SessionFactory, an existing instance can be used by setting hibernate.cache.hazelcast.instance_name Hibernate property to HazelcastInstance's name. For more information see Named HazelcastInstance. Disabling shutdown during SessionFactory.close() Shutting down HazelcastInstance can be disabled during SessionFactory.close() by setting hibernate.cache.hazelcast.shutdown_on_session_factory_close Hibernate property to false. (In this case Hazelcast property hazelcast.shutdownhook.enabled should not be set to false.) Default value is true.
70
Hazelcast has Spring integration (requires version 2.5 or greater) since 1.9.1 using hazelcast namespace. Add namespace xmlns:hz="http://www.hazelcast.com/schema/spring" to beans tag in context file:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hz="http://www.hazelcast.com/schema/spring" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.hazelcast.com/schema/spring http://www.hazelcast.com/schema/spring/hazelcast-spring-2.5.xsd">
Use hz namespace shortcuts to declare cluster, its items and so on. After that you can configure Hazelcast instance (node):
<hz:hazelcast id="instance"> <hz:config> <hz:group name="dev" password="password"/> <hz:network port="5701" port-auto-increment="false"> <hz:join> <hz:multicast enabled="false" multicast-group="224.2.2.3" multicast-port="54327"/> <hz:tcp-ip enabled="true"> <hz:members>10.10.1.2, 10.10.1.3</hz:members> </hz:tcp-ip> </hz:join> </hz:network> <hz:map name="map" backup-count="2" max-size="0" eviction-percentage="30" read-backup-data="true" cache-value="true" eviction-policy="NONE" merge-policy="hz.ADD_NEW_ENTRY"/> </hz:config> </hz:hazelcast>
You can easily configure map-store and near-cache too. (For map-store you should set either class-name or implementation attribute.)
71
Spring Integration
<hz:config> <hz:map name="map1"> <hz:near-cache time-to-live-seconds="0" max-idle-seconds="60" eviction-policy="LRU" max-size="5000" invalidate-on-change="true"/> <hz:map-store enabled="true" class-name="com.foo.DummyStore" write-delay-seconds="0"/> </hz:map> <hz:map name="map2"> <hz:map-store enabled="true" implementation="dummyMapStore" write-delay-seconds="0"/> </hz:map> <bean id="dummyMapStore" class="com.foo.DummyStore" /> </hz:config>
It's possible to use placeholders instead of concrete values. For instance, use property file app-default.properties for group configuration:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/app-default.properties</value> </list> </property> </bean> <hz:hazelcast id="instance"> <hz:config> <hz:group name="${cluster.group.name}" password="${cluster.group.password}"/> <!-- ... --> </hz:config> </hz:hazelcast>
You can declare beans for the following Hazelcast objects: map multiMap queue topic set
72
Spring Integration
Injecting Typed Collections/Maps Spring tries to create a new Map/Collection instance and fill the new instance by iterating and converting values of the original Map/Collection (IMap, IQueue etc.) to required types when generic type parameters of the original Map/Collection and the target property/attribute do not match. Since Hazelcast Maps/Collections are designed to hold very large data which a single machine can not carry, iterating through whole values can cause out of memory errors. To avoid this issue either target property/attribute can be declared as un-typed Map/Collection
public class SomeBean { @Autowired IMap map; // instead of IMap<K, V> map @Autowired IQueue queue; // instead of IQueue<E> queue ... }
73
Spring Integration
public class SomeBean { IMap<K, V> map; IQueue<E> queue; public SomeBean(IMap map) { // instead of IMap<K, V> map this.map = map; } ... public void setQueue(IQueue queue) { // instead of IQueue<E> queue this.queue = queue; } ... }
ExecutorService example:
74
Spring Integration
@SpringAware public class SomeTask implements Callable<Long>, ApplicationContextAware, Serializable { private transient ApplicationContext context; private transient SomeBean someBean; public Long call() throws Exception { return someBean.value; } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { context = applicationContext; } @Autowired public void setSomeBean(final SomeBean someBean) { this.someBean = someBean; } }
HazelcastInstance hazelcast = (HazelcastInstance) context.getBean("hazelcast"); SomeBean bean = (SomeBean) context.getBean("someBean"); Future<Long> f = hazelcast.getExecutorService().submit(new SomeTask()); Assert.assertEquals(bean.value, f.get().longValue()); // choose a member Member member = hazelcast.getCluster().getMembers().iterator().next(); Future<Long> f2 = (Future<Long>) hazelcast.getExecutorService() .submit(new DistributedTask<Long>(new SomeTask(), member)); Assert.assertEquals(bean.value, f2.get().longValue());
On Node-1;
75
Spring Integration
HazelcastInstance hazelcast = (HazelcastInstance) context.getBean("hazelcast"); SomeValue value = (SomeValue) context.getBean("someValue") IMap<String, SomeValue> map = hazelcast.getMap("values"); map.put("key", value);
On Node-2;
HazelcastInstance hazelcast = (HazelcastInstance) context.getBean("hazelcast"); IMap<String, SomeValue> map = hazelcast.getMap("values"); SomeValue value = map.get("key"); Assert.assertTrue(value.init);
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" scope="singleton <property name="dataSource" ref="dataSource"/> <property name="cacheProvider" ref="cacheProvider" /> ... </bean>
<hz:hibernate-region-factory id="regionFactory" instance-ref="instance" /> ... <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" scope="singleton <property name="dataSource" ref="dataSource"/> <property name="cacheRegionFactory" ref="regionFactory" /> ... </bean>
76
Spring Integration
package com.hazelcast.jpa.repository; import com.hazelcast.jpa.Product; import org.springframework.data.repository.CrudRepository; public interface ProductRepository extends CrudRepository<Product, Long> { }
Then you should add your data source and repository definition to you Spring configuration,
<jpa:repositories base-package="com.hazelcast.jpa.repository" /> <bean class="com.hazelcast.jpa.SpringJPAMapStore" id="jpamapstore"> <property name="crudRepository" ref="productRepository" /> </bean> <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/YOUR_DB"/> <property name="username" value="YOUR_USERNAME"/> <property name="password" value="YOUR_PASSWORD"/> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="generateDdl" value="true" /> <property name="database" value="MYSQL" /> </bean> </property> <property name="persistenceUnitName" value="jpa.sample" /> </bean> <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> <property name="jpaDialect"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /> </property> </bean>
In the example configuration above, Hibernate and MYSQL is configured, you change them according your ORM and database selection. Also you should define your persistence unit with persistence.xml under META-INF directory.
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/X <persistence-unit name="jpa.sample" /> </persistence>
By default, the key is expected to be the same with id of the JPA object. You can change this behaviour and customize MapStore implementation extending SpringJPAMapStore class. For more info see Spring Data JPA Reference [http:// static.springsource.org/spring-data/data-jpa/docs/current/reference/html/].
77
Spring Integration
Then you can set this as mapstore for maps that you want to persist into MongoDB.
<hz:map name="user"> <hz:map-store enabled="true" implementation="mongomapstore" write-delay-seconds="0"> </hz:map-store> </hz:map>
By default, the key is set as id of the MongoDB object. You can override MongoMapStore class for you custom needs. For more info see Spring Data MongoDB Reference [http://static.springsource.org/spring-data/data-mongodb/docs/ current/reference/html/].
78
ClientConfig clientConfig = new ClientConfig(); clientConfig.getGroupConfig().setName("dev").setPassword("dev-pass"); clientConfig.addAddress("10.90.0.1", "10.90.0.2:5702"); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); //All cluster operations that you can do with ordinary HazelcastInstance Map<String, Customer> mapCustomers = client.getMap("customers"); mapCustomers.put("1", new Customer("Joe", "Smith")); mapCustomers.put("2", new Customer("Ali", "Selam")); mapCustomers.put("3", new Customer("Avi", "Noyan")); Collection<Customer> colCustomers = mapCustomers.values(); for (Customer customer : colCustomers) { // process customer }
79
Clients
Near Cache on Java Client By default, near Cache on Java Client is not enabled. Near Cache implementation on client side is based on the Google Guava [http://code.google.com/p/guava-libraries/wiki/CachesExplained] cache. To enable it the following System property should be set to "true": "hazelcast.client.near.cache.enabled" and the related Guava jar's should be added to classpath. The current implementation uses 13.0.1 version of it. You can add the maven dependency as follows:
Client will use the near cache configuration on server for the maps. Only the maps having proper near cache configuration will be cached on client. If max size is set, entries will be evicted based on LRU eviction policy, as this is the only policy that Guava supports.
You can use native C# client to connect to the running Hazelcast instances. All you need is to include Hazelcast.Client.dll into your C# project. The API is very similar to Java native client. Note that C# client doesn't have automatic reconnection feature. If the node that it connected dies, it will not switch to another member. User must connect to another member itself.
using System; using System.Collections.Generic; using Hazelcast.Client; using Hazelcast.Core; ClientConfig clientConfig = new ClientConfig(); clientConfig.GroupConfig.Name = "dev"; clientConfig.GroupConfig.Password = "dev-pass"; clientConfig.addAddress("10.90.0.1"); HazelcastClient client = HazelcastClient.newHazelcastClient(clientConfig); //Allmost all cluster operations that you can do with ordinary HazelcastInstance //Note that the Customer class must have Serializable attribute or implement Hazelcast.IO.DataSerializable IMap<String, Customer> mapCustomers = client.getMap("customers"); mapCustomers.put("1", new Customer("Joe", "Smith")); mapCustomers.put("2", new Customer("Ali", "Selam")); mapCustomers.put("3", new Customer("Avi", "Noyan")); ICollection<Customer> colCustomers = mapCustomers.values(); foreach (Customer customer in colCustomers) { // process customer }
You can serialize back and forth Java and C# Objects between C# client and Hazelcast server. All you need is to have your classes that you want to share to implement DataSerializable both on Java and C# in the exact same way. And on C# ClientConfig you must set a TypeConverter implementation that will convert Java Class name into C# Type and vice versa. A basic TypeConverter might look like this.
80
Clients
public class MyTypeConverter: Hazelcast.IO.ITypeConverter { public string getJavaName(Type type) { if(type.Equals(typeof(Hazelcast.Client.Examples.MyCSharpClass))) return "com.hazelcast.examples.MyClass"; return null; } public Type getType(String javaName) { if("com.hazelcast.examples.MyClass".Equals(javaName)) return typeof(Hazelcast.Client.Examples.MyCSharpClass); return null; } }
using System; using Hazelcast.IO; public class MyCSharpClass: Hazelcast.IO.DataSerializable { String field1 = ""; int field2; public MyCSharpClass () { } public MyCSharpClass (String f1, int f2) { this.field1 = f1; this.field2 = f2; } public void writeData(IDataOutput dout){ dout.writeUTF(field1); dout.writeInt(field2); } public void readData(IDataInput din){ field1 = din.readUTF(); field2 = din.readInt(); } }
81
Clients
And you have a PHP application that uses PHP Memcache client to cache things in Hazelcast. All you need to do is have your PHP memcache client connect to one of these members. It doesn't matter which member the client connects to because Hazelcast cluster looks as one giant machine (Single System Image). PHP client code sample:
<?php $memcache = new Memcache; $memcache->connect('10.20.17.1', 5701) or die ("Could not connect"); $memcache->set('key1','value1',0,3600); $get_result = $memcache->get('key1'); //retrieve your data var_dump($get_result); //show it ?>
Notice that memcache client is connecting to 10.20.17.1 and using port5701. Java client code sample with SpyMemcached client:
MemcachedClient client = new MemcachedClient(AddrUtil.getAddresses("10.20.17.1:5701 10.20.17.2:5701")); client.set("key1", 3600, "value1"); System.out.println(client.get("key1"));
An entry written with a memcache client can be read by another memcache client written in another language.
And you have a distributed map named 'stocks'. You can put a new key1/value1 entry into this map by issuing HTTP POST call to http://10.20.17.1:5701/hazelcast/rest/maps/stocks/key1 URL. Your http post call's content body should contain the value (value1). You can retrieve this entry via HTTP GET call to http://10.20.17.1:5701/hazelcast/rest/maps/stocks/key1. You can also retrieve this entry from another member such ashttp://10.20.17.3:5701/hazelcast/rest/maps/stocks/key1. RESTful access is provided through any member of your cluster. So you can even put an HTTP load-balancer in-front of your cluster members for load-balancing and fault-tolerance. Now go ahead and install a REST plugin for your browser and explore further. Hazelcast also stores the mime-type of your POST request if it contains any. So if, for example, you post binary of an image file and set the mime-type of the HTTP POST request to image/jpeg then this mime-type will be part of the response of your HTTP GET request for that entry. Let's say you also have a task queue named 'tasks'. You can offer a new item into the queue via HTTP POST and take and item from the queue via HTTP DELETE. HTTP POST http://10.20.17.1:5701/hazelcast/rest/queues/tasks <CONTENT> means
Hazelcast.getQueue("tasks").offer(<CONTENT>);
Note that you will have to handle the failures on REST polls as there is no transactional guarantee.
82
83
Internals
public class Employee implements com.hazelcast.nio.DataSerializable { private String firstName; private String lastName; private int age; private double salary; private Address address; //address itself is DataSerializable public Employee() {} //getters setters.. public void writeData(DataOutput out) throws IOException { out.writeUTF(firstName); out.writeUTF(lastName); out.writeInt(age); out.writeDouble (salary); address.writeData (out); } public void readData (DataInput in) throws IOException { firstName = in.readUTF(); lastName = in.readUTF(); age = in.readInt(); salary = in.readDouble(); address = new Address(); // since Address is DataSerializable let it read its own internal state address.readData (in); } }
As you can see, since address field itself isDataSerializable, it is calling address.writeData(out) when writing and address.readData(in) when reading. Caution: Hazelcast serialization is done on the user thread and it assumes that there will be only one object serialization at a time. So putting any Hazelcast operation that will require to serialize anything else will break the serialization. For Example: Putting
Hazelcast.getMap("anyMap").put("key", "dummy value");
line in readData or writeData methods will break the serialization. If you have to perform such an operation, at least it should be performed in another thread which will force the serialization to take on different thread.
84
Internals
tell members to sync data in order to balance the data load Every member in the cluster has the same member list in the same order. First member is the oldest member so if the oldest member dies, second member in the list becomes the first member in the list and the new oldest member. See com.hazelcast.impl.Node and com.hazelcast.impl.ClusterManager for details. Q. If, let say 50+, nodes are trying to join the cluster at the same time, are they going to join the cluster one by one? No. As soon as the oldest member receives the first valid join request, it will wait 5 seconds for others to join so that it can join multiple members in one shot. If there is no new node willing to join for the next 5 seconds, then oldest member will start the join process. If a member leaves the cluster though, because of a JVM crash for example, cluster will immediately take action and oldest member will start the data recovery process.
Locally owned entries can be obtained by callingmap.localKeySet(). Q. What happens when a new member joins? Just like any other member in the cluster, the oldest member also knows who owns which partition and what the oldest member knows is always right. The oldest member is also responsible for redistributing the partition ownerships when a new member joins. Since there is new member, oldest member will take ownership of some of the partitions and give them to the new member. It will try to move the least amount of data possible. New ownership information of all partitions is then sent to all members. Notice that the new ownership information may not reach each member at the same time and the cluster never stops responding to user map operations even during joins so if a member routes the operation to a wrong member, target member will tell the caller to re-do the operation. If a member's partition is given to the new member, then the member will send all entries of that partition to the new member (Migrating the entries). Eventually every member in the cluster will own almost same number of partitions, and almost same number of entries. Also eventually every member will know the owner of each partition (and each key). You can listen for migration events. MigrationEvent contains thepartitionId,oldOwner, and newOwner information.
85
Internals
PartitionService partitionService = Hazelcast.getPartitionService(); partitionService.addMigrationListener(new MigrationListener () { public void migrationStarted(MigrationEvent migrationEvent) { System.out.println(migrationEvent); } public void migrationCompleted(MigrationEvent migrationEvent) { System.out.println(migrationEvent); } });
Q. How about distributed set and list? Both distributed set and list are implemented on top of distributed map. The underlying distributed map doesn't hold value; it only knows the key. Items added to both list and set are treated as keys. Unlike distributed set, since distributed list can have duplicate items, if an existing item is added again, copyCount of the entry (com.hazelcast.impl.ConcurrentMapManager.Record) is incremented. Also note that index based methods of distributed list, such as List.get(index) andList.indexOf(Object), are not supported because it is too costly to keep distributed indexes of list items so it is not worth implementing. Check out the com.hazelcast.impl.ConcurrentMapManager class for the implementation. As you will see, the implementation is lock-free because ConcurrentMapManager is a singleton and processed by only one thread, theServiceThread.
86
17.1.1. Installation
It is important to understand how it actually works. Basically you will deploy mancenter.war application into your Java web server and then tell Hazelcast nodes to talk to that web application. That means, your Hazelcast nodes should know the URL of mancenter application before they start. Here are the steps: Download the latest Hazelcast zip from hazelcast.com [http://www.hazelcast.com/downloads.jsp] Zip contains mancenter.war file. Deploy it to your web server (Tomcat, Jetty etc.) Let's say it is running athttp://localhost:8080/mancenter. Start your web server and make sure http://localhost:8080/mancenter is up. Configure your Hazelcast nodes by adding the URL of your web app to your hazelcast.xml. Hazelcast nodes will send their states to this URL.
<management-center enabled="true">http://localhost:8080/mancenter</management-center>
Start your hazelcast cluster. Browse to http://localhost:8080/mancenter and login. Initial login username/passwords is admin/ admin Management Center creates a directory with name "mancenter" under your "user/home" directory to save data files. You can change the data directory setting "hazelcast.mancenter.home" system property.
87
Management Center
17.2. Maps
Map instances are listed on the left panel. When you click on a map, a new tab for monitoring this map instance is opened on the right. In this tab, you can monitor metrics also re-configure the map.
88
Management Center
[images/mapbrowse.jpg]
17.3. Queues
Queues is the second data structure that you can monitor in management center. You can activate the Queue Tab by clicking the instance name listed on the left panel under queues part. The queue page consists of the charts monitoring
89
Management Center
data about the queue. You can change the data to be monitored by clicking on the chart. Available options are Size, Polls, Offers.
17.4. Topics
You can monitor your topics' metrics by clicking the topic name listed on the left panel under topics part. There are two charts which reflects live data, and a datatable lists the live data distributed among members.
17.5. Members
The current members in the cluster are listed on the bottom side of the left panel. You can monitor each member on tab page displayed by clicking on member items.
90
Management Center
17.5.1. Monitoring
In members page there are 4 inner tab pages to monitor meber's state and properties. Runtime: Runtime properties about memory, threads are given. This data updates dynamically. Properties: System properties are displayed. Configuration: Configuration xml initially set can be viewed here. Partitions: The partitions belongs to this member are listed.
17.5.2. Operations
Besides monitoring you can perform certain actions on members. You can take thread dump of the member and you can perform garbage collection on the selected member.
91
Management Center
17.8. Scripting
In scripting part, you can execute your own code on your cluster. In the left part you can select members, on which the code will be executed. Also you can select over scripting languages: Javascript, Groovy, JRuby, BeanShell. This part is only enabled for users with read/write permissions for current cluster.
92
Management Center
17.10. Console
The console tool enables you execute commands on the cluster. You can read or write on instances but first you should set namespace. For example if you have a map with name "mapCustomers". To get a customer with key "Jack" you should first set the namespace with command "ns mapCustomers". Then you can take the object by "m.get Jack" Here is the command list:
93
Management Center
-- General commands echo true|false //turns on/off echo of commands (default false) silent true|false //turns on/off silent of command output (default false) #<number> <command> //repeats <number> time <command>, replace $i in <command> with current &<number> <command> //forks <number> threads to execute <command>, replace $t in <command> w When using #x or &x, is is advised to use silent true as well. When using &x with m.putmany and m.removemany, each thread will get a different share of keys unless a s jvm //displays info about the runtime who //displays info about the cluster whoami //displays info about this cluster member ns <string> //switch the namespace for using the distributed queue/map/set/list <str @<file> //executes the given <file> script. Use '//' for comments in the script -- Queue commands q.offer <string> q.poll q.offermany <number> [<size>] q.pollmany <number> q.iterator [remove] q.size q.clear -- Set commands s.add <string> s.remove <string> s.addmany <number> s.removemany <number> s.iterator [remove] s.size s.clear -- Lock commands lock <key> tryLock <key> tryLock <key> <time> unlock <key>
//adds a string object to the queue //takes an object from the queue //adds indicated number of string objects to the queue ('obj<i>' or byte //takes indicated number of objects from the queue //iterates the queue, remove if specified //size of the queue //clears the queue
//adds a string object to the set //removes the string object from the set //adds indicated number of string objects to the set ('obj<i>') //takes indicated number of objects from the set //iterates the set, removes if specified //size of the set //clears the set
as as as as
-- Map commands m.put <key> <value> //puts an entry to the map m.remove <key> //removes the entry of given key from the map m.get <key> //returns the value of given key from the map m.putmany <number> [<size>] [<index>]//puts indicated number of entries to the map ('key<i>':byte[<size>], <i m.removemany <number> [<index>] //removes indicated number of entries from the map ('key<i>', <index>+(0 When using &x with m.putmany and m.removemany, each thread will get a different share of keys unless a s m.keys //iterates the keys of the map m.values //iterates the values of the map m.entries //iterates the entries of the map m.iterator [remove] //iterates the keys of the map, remove if specified m.size //size of the map m.clear //clears the map m.destroy //destroys the map m.lock <key> //locks the key m.tryLock <key> //tries to lock the key and returns immediately m.tryLock <key> <time> //tries to lock the key within given seconds m.unlock <key> //unlocks the key -- List commands: l.add <string> l.add <index> <string> l.contains <string> l.remove <string> l.remove <index> l.set <index> <string> l.iterator [remove] l.size l.clear -- AtomicNumber commands: a.get a.set <long> a.inc a.dec -- Executor Service commands: execute <echo-input> //executes an echo task on random member execute0nKey <echo-input> <key> //executes an echo task on the member that owns the given key execute0nMember <echo-input> <key> //executes 94 an echo task on the member with given index execute0nMembers <echo-input> //executes an echo task on all of the members
Management Center
95
If cache-value is true (default is true), Hazelcast caches that returned value for fast access in local node. Modifications done to this cached value without putting it back to map will be visible to only local node, successive get calls will return the same cached value. To reflect modifications to distributed map, you should put modified value back into map. 3. Collections which return values of methods such as IMap.keySet, IMap.values, IMap.entrySet, MultiMap.get, MultiMap.remove, IMap.keySet, IMap.values, contain cloned values. These collections are NOT backup by related Hazelcast objects. So changes to the these are NOT reflected in the originals, and viceversa. 4. Most of the Hazelcast operations throw an RuntimeInterruptedException (which is unchecked version of InterruptedException) if a user thread is interrupted while waiting a response. Hazelcast uses RuntimeInterruptedException to pass InterruptedException up through interfaces that don't have InterruptedException in their signatures. Users should be able to catch and handle RuntimeInterruptedException in such cases as if their threads are interrupted on a blocking operation. 5. Some of Hazelcast operations can throw ConcurrentModificationException under transaction while trying to acquire a resource, although operation signatures don't define such an exception. Exception is thrown if resource can not be acquired in a specific time. Users should be able to catch and handle ConcurrentModificationException while they are using Hazelcast transactions.
96
Miscellaneous
@Test public void testTwoMemberMapSizes() { // start the first member HazelcastInstance h1 = Hazelcast.newHazelcastInstance(null); // get the map and put 1000 entries Map map1 = h1.getMap("testmap"); for (int i = 0; i < 1000; i++) { map1.put(i, "value" + i); } // check the map size assertEquals(1000, map1.size()); // start the second member HazelcastInstance h2 = Hazelcast.newHazelcastInstance(null); // get the same map from the second member Map map2 = h2.getMap("testmap"); // check the size of map2 assertEquals(1000, map2.size()); // check the size of map1 again assertEquals(1000, map1.size()); }
In the test above, everything happened in the same thread. When developing multi-threaded test, coordination of the thread executions has to be carefully handled. Usage of CountDownLatch for thread coordination is highly recommended. You can certainly use other things. Here is an example where we need to listen for messages and make sure that we got these messages:
@Test public void testTopic() { // start two member cluster HazelcastInstance h1 = Hazelcast.newHazelcastInstance(null); HazelcastInstance h2 = Hazelcast.newHazelcastInstance(null); String topicName = "TestMessages"; // get a topic from the first member and add a messageListener ITopic<String> topic1 = h1.getTopic(topicName); final CountDownLatch latch1 = new CountDownLatch(1); topic1.addMessageListener(new MessageListener() { public void onMessage(Object msg) { assertEquals("Test1", msg); latch1.countDown(); } }); // get a topic from the second member and add a messageListener ITopic<String> topic2 = h2.getTopic(topicName); final CountDownLatch latch2 = new CountDownLatch(2); topic2.addMessageListener(new MessageListener() { public void onMessage(Object msg) { assertEquals("Test1", msg); latch2.countDown(); } }); // publish the first message, both should receive this topic1.publish("Test1"); // shutdown the first member h1.shutdown(); // publish the second message, second member's topic should receive this topic2.publish("Test1"); try { // assert that the first member's topic got the message assertTrue(latch1.await(5, TimeUnit.SECONDS)); // assert that the second members' topic got two messages assertTrue(latch2.await(5, TimeUnit.SECONDS)); } catch (InterruptedException ignored) { } }
You can surely start Hazelcast members with different configuration. Let's say we want to test if Hazelcast LiteMember can shutdown fine.
97
Miscellaneous
@Test(timeout = 60000) public void shutdownLiteMember() { // first config for normal cluster member Config c1 = new XmlConfigBuilder().build(); c1.setPortAutoIncrement(false); c1.setPort(5709); // second config for LiteMember Config c2 = new XmlConfigBuilder().build(); c2.setPortAutoIncrement(false); c2.setPort(5710); // make sure to set LiteMember=true c2.setLiteMember(true); // start the normal member with c1 HazelcastInstance hNormal = Hazelcast.newHazelcastInstance(c1); // start the LiteMember with different configuration c2 HazelcastInstance hLite = Hazelcast.newHazelcastInstance(c2); hNormal.getMap("default").put("1", "first"); assert hLite.getMap("default").get("1").equals("first"); hNormal.shutdown(); hLite.shutdown(); }
Also remember to call Hazelcast.shutdownAll() after each test case to make sure that there is no other running member left from the previous tests.
@After public void cleanup() throws Exception { Hazelcast.shutdownAll(); }
98
Miscellaneous
New Feature: Java Client has now 'near-cache' support. See Near Cache on Java Client for additional details. New Feature: Management Center alert system, receive alerts based on custom filters. See Management Center Alerting System for additional details. Management Center has now better support for Hazelcast cluster running in OSGI environment. Nodes can be easily shutdown or restarted using Management Center interface. Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=17&state=closed] 377, 386, 389, 392, 394 2.4.1 Added Hibernate 2nd level cache local/invalidation mode. See com.hazelcast.hibernate.HazelcastLocalCacheRegionFactory. Added quick clear feature for maps. Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=15&state=closed] 304, 308, 312, 315, 321, 322, 323, 328, 331, 333, 334, 337, 338, 339, 347, 349, 351, 353, 354, 356, 359, 368 2.4 Client threads is no longer fixed size, now on it is going to use internal Hazelcast cached thread pool. Added ability to restrict outbound ports that Hazelcast uses to connect other nodes. See OutboundPorts documentation. Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=15&state=closed] 168, 251, 260, 262, 267, 268, 269, 270, 274, 275, 276, 277, 279, 282, 284, 288, 290, 292, 301 2.3.1 Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=13&state=closed] 256, 258 Changed hazelcast.partition.migration.interval value from 1 to 0. ILock.newCondition() now throws UnsupportedOperationException. 2.3 Changed hazelcast.max.operation.timeout unit from seconds to milliseconds. Added hazelcast.max.concurrent.operation.limit parameter to be able to limit number of concurrent operations can be submitted to Hazelcast. Added hazelcast.backup.redo.enabled parameter to enable/disable redo for backup operations. Added MultiMap and Distributed ExecutorService statistics to Management Center [http://hazelcast.com/ mancenter.jsp] application. MigrationListener has now an additional method to receive failed migration events; void migrationFailed(MigrationEvent migrationEvent). ItemEvent has now an additional method returning Member firing that event; public Member getMember(). Improved out of memory (OOM) error detection and handling. Now it is possible to register custom hook when OutOfMemoryError is thrown. See Hazelcast.setOutOfMemoryHandler(OutOfMemoryHandler) and OutOfMemoryHandler javadocs for additional details.
99
Miscellaneous
Fixed some issues related to domain name handling and networking/join. During cluster merge after a network split-brain, merging side will now fire MERGING and MERGED before and after RESTARTING and RESTARTED LifecycleEvents. Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=12&state=closed] 167, 182, 188, 209, 217, 218, 220, 222, 223, 225, 226, 227, 228, 229, 230, 233, 234, 235, 237, 241, 243, 244, 247, 250 2.2 Improved redo logs and added max call/operation timeout. See configuration properties hazelcast.max.operation.timeout and hazelcast.redo.giveup.threshold Improved domain name handling; Hazelcast will use defined addresses/domain-names in TCP-IP Config as they are, without resolving an IP address. Added Cluster Health Check to Management Center [http://hazelcast.com/mancenter.jsp] application. Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=5&state=closed] 39, 93, 152, 153, 163, 164, 169 2.1.3 Fixed join and split brain issues. Improved domain name handling. Fixed host aware partition group when all members are lite but one. Fixed jmx management service dead-lock issue. Fixed IMap replace-if-same and and remove-if-same concurrency issues. Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=7&state=closed] 176, 177, 179, 181, 183, 185, 186, 189, 195, 196, 198 2.1.2 Fixed interruption handling to avoid dead-locks and inconsistency. See configuration property hazelcast.force.throw.interrupted.exception in ConfigurationProperties page. Replaced ExecutorService used by migration process with a custom one. Fixed ExecutorService a memory leak during executor thread termination. Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=6&state=closed] 161, 174 2.1.1 Fixed issues: [https://github.com/hazelcast/hazelcast/issues?milestone=4&state=closed] 73, 142, 146, 148, 149, 153, 158, 162, 163, 164 Fixed issues from 2.0.4 branch: [https://github.com/hazelcast/hazelcast/issues?milestone=3&state=closed] 96, 98, 131, 132, 135, 140, 166 2.1 IPv6 Support: Hazelcast now supports IPv6 addresses seamlessly.
100
Miscellaneous
Async backup support. Spring Cache support: Hazelcast can be used as Spring Cache [http://static.springsource.org/spring/docs/3.1.x/springframework-reference/html/cache.html] provider. Spring Dependency Injection support: Hazelcast can apply bean properties or to apply factory callbacks such as ApplicationContextAware, BeanNameAware or to apply bean post-processing such as InitializingBean, @PostConstruct like annotations while using Hazelcast distributed ExecutorService or DistributedTasks or more generally any Hazelcast managed object. Persistence support with Spring-Data MongoDB and JPA integration. Member.getUuid() will return UUID for node. Improved session clustering configuration. Fixed issues: Google Code [http://code.google.com/p/hazelcast/issues/list] 809, 811, 816, 818 Github [https://github.com/hazelcast/hazelcast/issues] 6, 7, 92, 98, 99, 101, 102, 103, 104, 108, 109, 110, 114, 116, 117, 118, 119, 120, 126, 127, 128, 130, 131, 132, 134, 135 2.0 New Elastic Memory(Enterprise Edition Only): By default, Hazelcast stores your distributed data (map entries, queue items) into Java heap which is subject to garbage collection. As your heap gets bigger, garbage collection might cause your application to pause tens of seconds, badly effecting your application performance and response times. Elastic Memory is Hazelcast with off-heap memory storage to avoid GC pauses. Even if you have terabytes of cache in-memory with lots of updates, GC will have almost no effect; resulting in more predictable latency and throughput. Security Framework(Enterprise Edition Only): Hazelcast Security is JAAS based pluggable security framework which can be used to authenticate both cluster members and clients and do access control checks on client operations. With the security framework, take control of who can be part of the cluster or connect as client and which operations are allowed or not. Native C# Client(Enterprise Edition Only): Just like our Native Java Client, it supports all map, multimap, queue, topic operations including listeners and queries. Distributed Backups: Data owned by a member will be evenly backed up by all the other members. In other word, every member takes equal responsibility to backup every other node. This leads to better memory usage and less influence in the cluster when you add/remove nodes. The new backup system makes it possible to form backup-groups so that you can have backups and owners fall into different groups. Parallel IO: Number of socket selector threads can be configured. You can have more IO threads, if you have good number of CPU/cores and high-throughput network. Connection Management: Hazelcast 2.0 is more tolerant to connection failures. On connection failure it tries to repair it before declaring the member as dead. So now it is ok to have short socket disconnections No problem if your virtual server migrates to a new host. Listeners such as migration, membership and map indexes can be added with configuration. New Event Objects: Event Listeners for Queue/List/Set/Topic were delivering the item itself on event methods. Thats why the items had to be deserialized by Hazelcast Threads before invoking the listeners. Sometimes this was causing class loader problems too. With 2.0, we have introduced new event containers for Queue/List/Set and Topic just like Map has EntryEvent. The new listeners now receive ItemEvent and Message objects respectively. The actual items are
101
Miscellaneous
deserialized only if you call the appropriate get method on the event objects. This is where we brake the compatibility with the older versions of Hazelcast. ClientConfig API: We had too many of factory methods to instantiate a HazelcastClient. Now all we need isHazelcastClient.newHazelcastClient(ClientConfig). SSL communication support among cluster nodes. Distributed MultiMap value collection can be either List or Set. SuperClient is renamed to LiteMember to avoid confusion. Be careful! It is a member, not a client. New IMap.set (key, value, ttl, TimeUnit) implementation, which is optimized put(key, value) operation as set doesnt return the old value. HazelcastInstance.getLifecycleService().kill() will forcefully kill the node. Useful for testing. forceUnlock, to unlock the locked entry from any node and any thread regardless of the owner. Enum type query support.. new SqlPredicate (level = Level.WARNING) for example Fixed issues: 430, 459, 471, 567, 574, 582, 629, 632, 646, 666, 686, 669, 690, 692, 693, 695, 698, 705, 708, 710, 711, 712, 713, 714, 715, 719 , 721, 722, 724, 727, 728, 729, 730, 731, 732, 733, 735, 738, 739, 740, 741, 742, 747, 751, 752, 754, 756, 758, 759, 760, 761, 765, 767, 770, 773, 779, 781, 782, 783, 787, 790, 795, 796 1.9.4 New WAN Replication (synchronization of separate active clusters) New Data Affinity (co-location of related entries) feature. New EC2 Auto Discovery for your Hazelcast cluster running on Amazon EC2 platform. New Distributed CountDownLatch implementation. [http://www.hazelcast.com/docs/1.9.4/javadoc/com/hazelcast/ core/ICountDownLatch.html] New Distributed Semaphore implementation. [http://www.hazelcast.com/docs/1.9.4/javadoc/com/hazelcast/core/ ISemaphore.html] Improvement: Distribution contains HTML and PDF documentation besides Javadoc. Improvement: Better TCP/IP and multicast join support. Handling more edge cases like multiple nodes starting at the same time. Improvement: Memcache protocol: Better integration between Java and Memcache clients. Put from memcache, get from Java client. Monitoring Tool is removed from the project. 200+ commits 25+ bug fixes and several other enhancements. 1.9.3 Re-implementation of distributed queue. Configurable backup-count and synchronous backup. Persistence support based on backing MapStore Auto-recovery from backing MapStore on startup. Re-implementation of distributed list supporting index based operations.
102
Miscellaneous
New distributed semaphore implementation. Optimized IMap.putAll for much faster bulk writes. New IMap.getAll for bulk reads which is calling MapLoader.loadAll if necessary. New IMap.tryLockAndGet and IMap.putAndUnlock API New IMap.putTransient API for storing only in-memory. New IMap.addLocalEntryListener() for listening locally owned entry events. New IMap.flush() for flushing the dirty entries into MapStore. New MapLoader.getAllKeys API for auto-pre-populating the map when cluster starts. Support for min. initial cluster size to enable equally partitioned start. Graceful shutdown. Faster dead-member detection. 1.9 Memcache interface support. Memcache clients written in any language can access Hazelcast cluster. RESTful access support. http://<ip>:5701/hazelcast/rest/maps/mymap/key1 Split-brain (network partitioning) handling New LifecycleService API to restart, pause Hazelcast instances and listen for the lifecycle events. New asynchronous put and get support for IMap via IMap.asyncPut() and IMap.asyncGet() New AtomicNumber API; distributed implementation of java.util.concurrent.atomic.AtomicLong So many bug fixes. 1.8.4 Significant performance gain for multi-core servers. Higher CPU utilization and lower latency. Reduced the cost of map entries by 50%. Better thread management. No more idle threads. Queue Statistics API and the queue statistics panel on the Monitoring Tool. Monitoring Tool enhancements. More responsive and robust. Distribution contains hazelcast-all-<version>.jar to simplify jar dependency. So many bug fixes. 1.8.3 Bug fixes Sorted index optimization for map queries. 1.8.2 A major bug fix
103
Miscellaneous
Minor optimizations 1.8.1 Hazelcast Cluster Monitoring Tool (see the hazelcast-monitor-1.8.1.war in the distro) New Partition API. Partition and key owner, migration listeners. New IMap.lockMap() API. New Multicast+TCP/IP join feature. Try multicast first, if not found, try tcp/ip. New Hazelcast.getExecutorService(name) API. Have separate named ExecutorServices. Do not let your big tasks blocking your small ones. New Logging API. Build your own logging. or simply use Log4j or get logs as LogEvents. New MapStatistics API. Get statistics for your Map operations and entries. HazelcastClient automatically updates the member list. no need to pass all members. Ability to start the cluster members evenly partitioned. so no migration. So many bug fixes and enhancements. There are some minor Config API change. Just make sure to re-compile. 1.8 Java clients for accessing the cluster remotely. (C# is next) Distributed Query for maps. Both Criteria API and SQL support. Near cache for distributed maps. TTL (time-to-live) for each individual map entry. IMap.put(key,value, ttl, timeunit) IMap.putIfAbsent(key,value, ttl, timeunit) Many bug fixes. 1.7.1 Multiple Hazelcast members on the same JVM. New HazelcastInstance API. Better API based configuration support. Many performance optimizations. Fastest Hazelcast ever! Smoother data migration enables better response times during joins. Many bug fixes. 1.7 Persistence via Loader/Store interface for distributed map. Socket level encryption. Both symmetric and asymmetric encryption supported. New JMX support. (many thanks to Marco) New Hibernate second level cache provider (many thanks to Leo)
104
Miscellaneous
Instance events for getting notified when a data structure instance (map, queue, topic etc.) is created or destroyed. Eviction listener. EntryListener.entryEvicted(EntryEvent) Fully 'maven'ized. Modularized... hazelcast (core library) hazelcast-wm (http session clustering tool) hazelcast-ra (JCA adaptor) hazelcast-hibernate (hibernate cache provider) 1.6 Support for synchronous backups and configurable backup-count for maps. Eviction support. Timed eviction for queues. LRU, LFU and time based eviction for maps. Statistics/history for entries. create/update time, number of hits, cost. see IMap.getMapEntry(key) MultiMap implementation. similar to google-collections and apache-common-collections MultiMap but distributed and thread-safe. Being able to destroy() the data structures when not needed anymore. Being able to Hazelcast.shutdown() the local member. Get the list of all data structure instances viaHazelcast.getInstances(). 1.5 Major internal refactoring Full implementation ofjava.util.concurrent.BlockingQueue. Now queues can have configurable capacity limits. Super Clients (a.k.a LiteMember): Members with no storage. If -Dhazelcast.super.client=true JVM parameter is set, that JVM will join the cluster as a 'super client' which will not be a 'data partition' (no data on that node) but will have super fast access to the cluster just like any regular member does. Http Session sharing support for Hazelcast Web Manager. Different webapps can share the same sessions. Ability to separate clusters by creating groups. ConfigGroup java.util.logging support. 1.4 Add, remove and update events for queue, map, set and list Distributed Topic for pub/sub messaging Integration with J2EE transactions via JCA complaint resource adapter ExecutionCallback interface for distributed tasks Cluster-wide unique id generator 1.3
105
Miscellaneous
Transactional Distributed Queue, Map, Set and List 1.2 Distributed Executor Service Multi member executions Key based execution routing Task cancellation support 1.1 Session Clustering with Hazelcast Webapp Manager Full TCP/IP clustering support 1.0 Distributed implementation of java.util.{Queue,Map,Set,List} Distributed implementation of java.util.concurrency.Lock Cluster Membership Events
106