package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
public class MapSample {
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get the Distributed Map from Cluster.
IMap map = hz.getMap("my-distributed-map");
//Standard Put and Get.
map.put("key", "value");
map.get("key");
//Concurrent Map methods, optimistic updating
map.putIfAbsent("somekey", "somevalue");
map.replace("key", "value", "newvalue");
// Shutdown the Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.AccessedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.expiry.ExpiryPolicy;
import com.hazelcast.cache.ICache;
public class JCacheSample {
public static void main(String[] args) {
// Run as a Hazelcast Member
System.setProperty("hazelcast.jcache.provider.type", "server");
// Create the JCache CacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
MutableConfiguration configuration = new MutableConfiguration();
// Expire entries after 1 minute
configuration.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
// Get a Cache called "myCache" and configure with 1 minute expiry
Cache myCache = manager.createCache("myCache", configuration);
// Put and Get a value from "myCache"
myCache.put("key", "value");
String value = myCache.get("key");
System.out.println(value);
//ICache is a Hazelcast interface that extends JCache, provides more functionality
ICache icache = myCache.unwrap(ICache.class);
//Async Get and Put using ICache interface
icache.getAsync("key");
icache.putAsync("key", "value");
//ICache allows custom expiry per cache entry
final ExpiryPolicy customExpiryPolicy = AccessedExpiryPolicy.factoryOf(Duration.TEN_MINUTES).create();
icache.put("key", "newValue", customExpiryPolicy);
//Size of the Cache should reflect the ICache and JCache operations
icache.size();
//Shutdown the underlying Hazelcast Cluster Member
manager.getCachingProvider().close();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ReplicatedMap;
public class ReplicatedMapSample {
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get a Replicated Map called "my-replicated-map"
ReplicatedMap map = hz.getReplicatedMap("my-replicated-map");
// Put and Get a value from the Replicated Map
// key/value replicated to all members
map.put("key", "value");
// the value retrieved from local member
map.get("key");
// Shutdown the Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.MultiMap;
import java.util.Collection;
public class MultiMapSample {
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get the Distributed MultiMap from Cluster.
MultiMap multiMap = hz.getMultiMap("my-distributed-multimap");
// Put values in the map against the same key
multiMap.put("my-key", "value1");
multiMap.put("my-key", "value2");
multiMap.put("my-key", "value3");
// Print out all the values for associated with key called "my-key"
Collection values = multiMap.get("my-key");
System.out.println(values);
// remove specific key/value pair
multiMap.remove("my-key", "value2");
// Shutdown the Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.Set;
public class SetSample {
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get the Distributed Set from Cluster.
Set set = hz.getSet("my-distributed-set");
// Add items to the set with duplicates
set.add("item1");
set.add("item1");
set.add("item2");
set.add("item2");
set.add("item2");
set.add("item3");
// Get the items. Note that there are no duplicates.
for (String item: set) {
System.out.println(item);
}
// Shutdown the Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.List;
public class ListSample {
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get the Distributed List from Cluster.
List list = hz.getList("my-distributed-list");
// Add elements to the list
list.add("item1");
list.add("item2");
// Remove the first element
System.out.println("Removed: " + list.remove(0));
// There is only one element left
System.out.println("Current size is " + list.size());
// Clear the list
list.clear();
// Shutdown this Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class QueueSample {
public static void main(String[] args) throws InterruptedException {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get a Blocking Queue called "my-distributed-queue"
BlockingQueue queue = hz.getQueue("my-distributed-queue");
// Offer a String into the Distributed Queue
queue.offer("item");
// Poll the Distributed Queue and return the String
queue.poll();
//Timed blocking Operations
queue.offer("anotheritem", 500, TimeUnit.MILLISECONDS);
queue.poll(5, TimeUnit.SECONDS);
//Indefinitely blocking Operations
queue.put("yetanotheritem");
System.out.println(queue.take());
// Shutdown the Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;
public class TopicSample implements MessageListener {
@Override
public void onMessage(Message message) {
System.out.println("Got message " + message.getMessageObject());
}
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get a Topic called "my-distributed-topic"
ITopic topic = hz.getTopic("my-distributed-topic");
// Add a Listener to the Topic
topic.addMessageListener(new TopicSample());
// Publish a message to the Topic
topic.publish("Hello to distributed world");
// Shutdown the Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.Predicates;
import com.hazelcast.query.SqlPredicate;
import java.io.Serializable;
import java.util.Collection;
public class QuerySample {
public static class User implements Serializable {
String username;
int age;
boolean active;
public User(String username, int age, boolean active) {
this.username = username;
this.age = age;
this.active = active;
}
@Override
public String toString() {
return "User{"
+ "username='" + username + '\''
+ ", age=" + age
+ ", active=" + active
+ '}';
}
}
private static void generateUsers(IMap users) {
users.put("Rod", new User("Rod", 19, true));
users.put("Jane", new User("Jane", 20, true));
users.put("Freddy", new User("Freddy", 23, true));
}
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get a Distributed Map called "users"
IMap users = hz.getMap("users");
// Add some users to the Distributed Map
generateUsers(users);
// Create a Predicate from a String (a SQL like Where clause)
Predicate sqlQuery = new SqlPredicate("active AND age BETWEEN (18 AND 21)");
// Creating the same Predicate as above but with a builder
Predicate criteriaQuery = Predicates.and(
Predicates.equal("active", true),
Predicates.between("age", 18, 21)
);
// Get result collections using the two different Predicates
Collection result1 = users.values(sqlQuery);
Collection result2 = users.values(criteriaQuery);
// Print out the results
System.out.println(result1);
System.out.println(result2);
// Shutdown the Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package member;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.concurrent.locks.Lock;
public class LockSample {
public static void main(String[] args) {
// Start the Embedded Hazelcast Cluster Member.
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Get a distributed lock called "my-distributed-lock"
Lock lock = hz.getLock("my-distributed-lock");
// Now create a lock and execute some guarded code.
lock.lock();
try {
//do something here
} finally {
lock.unlock();
}
// Shutdown this Hazelcast Cluster Member
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
public class MapSample {
public static void main(String[] args) {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get the Distributed Map from Cluster.
IMap map = hz.getMap("my-distributed-map");
//Standard Put and Get.
map.put("key", "value");
map.get("key");
//Concurrent Map methods, optimistic updating
map.putIfAbsent("somekey", "somevalue");
map.replace("key", "value", "newvalue");
// Shutdown this Hazelcast client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.cache.ICache;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.AccessedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.expiry.ExpiryPolicy;
public class JCacheSample {
public static void main(String[] args) {
// Run as a Hazelcast Client
System.setProperty("hazelcast.jcache.provider.type", "client");
// Create the JCache CacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
MutableConfiguration configuration = new MutableConfiguration();
// Expire entries after 1 minute
configuration.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
// Get a Cache called "myCache" and configure with 1 minute expiry
Cache myCache = manager.createCache("myCache", configuration);
// Put and Get a value from "myCache"
myCache.put("key", "value");
String value = myCache.get("key");
System.out.println(value);
//ICache is a Hazelcast interface that extends JCache, provides more functionality
ICache icache = myCache.unwrap(ICache.class);
//Async Get and Put using ICache interface
icache.getAsync("key");
icache.putAsync("key", "value");
//ICache allows custom expiry per cache entry
final ExpiryPolicy customExpiryPolicy = AccessedExpiryPolicy.factoryOf(Duration.TEN_MINUTES).create();
icache.put("key", "newValue", customExpiryPolicy);
//Size of the Cache should reflect the ICache and JCache operations
icache.size();
//Shutdown this Hazelcast Client
manager.getCachingProvider().close();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ReplicatedMap;
public class ReplicatedMapSample {
public static void main(String[] args) {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get a Replicated Map called "my-replicated-map"
ReplicatedMap map = hz.getReplicatedMap("my-replicated-map");
// Put and Get a value from the Replicated Map
String replacedValue = map.put("key", "value");
// key/value replicated to all members
System.out.println("replacedValue = " + replacedValue);
// Will be null as its first update
String value = map.get("key");
// the value is retrieved from a random member in the cluster
System.out.println("value for key = " + value);
// Shutdown this Hazelcast Client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.MultiMap;
import java.util.Collection;
public class MultiMapSample {
public static void main(String[] args) {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get the Distributed MultiMap from Cluster.
MultiMap multiMap = hz.getMultiMap("my-distributed-multimap");
// Put values in the map against the same key
multiMap.put("my-key", "value1");
multiMap.put("my-key", "value2");
multiMap.put("my-key", "value3");
// Print out all the values for associated with key called "my-key"
Collection values = multiMap.get("my-key");
System.out.println(values);
// remove specific key/value pair
multiMap.remove("my-key", "value2");
// Shutdown this Hazelcast Client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import java.util.Set;
public class SetSample {
public static void main(String[] args) {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get the Distributed Set from Cluster.
Set set = hz.getSet("my-distributed-set");
// Add items to the set with duplicates
set.add("item1");
set.add("item1");
set.add("item2");
set.add("item2");
set.add("item2");
set.add("item3");
// Get the items. Note that there are no duplicates.
for (String item: set) {
System.out.println(item);
}
// Shutdown this Hazelcast client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import java.util.List;
public class ListSample {
public static void main(String[] args) {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get the Distributed List from Cluster.
List list = hz.getList("my-distributed-list");
// Add elements to the list
list.add("item1");
list.add("item2");
// Remove the first element
System.out.println("Removed: " + list.remove(0));
// There is only one element left
System.out.println("Current size is " + list.size());
// Clear the list
list.clear();
// Shutdown this Hazelcast client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class QueueSample {
public static void main(String[] args) throws InterruptedException {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get a Blocking Queue called "my-distributed-queue"
BlockingQueue queue = hz.getQueue("my-distributed-queue");
// Offer a String into the Distributed Queue
queue.offer("item");
// Poll the Distributed Queue and return the String
queue.poll();
//Timed blocking Operations
queue.offer("anotheritem", 500, TimeUnit.MILLISECONDS);
queue.poll(5, TimeUnit.SECONDS);
//Indefinitely blocking Operations
queue.put("yetanotheritem");
System.out.println(queue.take());
// Shutdown this Hazelcast Client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;
public class TopicSample implements MessageListener {
@Override
public void onMessage(Message message) {
System.out.println("Got message " + message.getMessageObject());
}
public static void main(String[] args) {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get a Topic called "my-distributed-topic"
ITopic topic = hz.getTopic("my-distributed-topic");
// Add a Listener to the Topic
topic.addMessageListener(new TopicSample());
// Publish a message to the Topic
topic.publish("Hello to distributed world");
// Shutdown this Hazelcast Client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.nio.serialization.Portable;
import com.hazelcast.nio.serialization.PortableFactory;
import com.hazelcast.nio.serialization.PortableReader;
import com.hazelcast.nio.serialization.PortableWriter;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.Predicates;
import com.hazelcast.query.SqlPredicate;
import java.io.IOException;
import java.util.Collection;
public class QuerySample {
public static class User implements Portable {
public static final int CLASS_ID = 1;
public String username;
public int age;
public boolean active;
public User(String username, int age, boolean active) {
this.username = username;
this.age = age;
this.active = active;
}
public User() {
}
@Override
public String toString() {
return "User{"
+ "username='" + username + '\''
+ ", age=" + age
+ ", active=" + active
+ '}';
}
@Override
public int getFactoryId() {
return ThePortableFactory.FACTORY_ID;
}
@Override
public int getClassId() {
return CLASS_ID;
}
@Override
public void writePortable(PortableWriter writer) throws IOException {
writer.writeUTF("username", username);
writer.writeInt("age", age);
writer.writeBoolean("active", active);
}
@Override
public void readPortable(PortableReader reader) throws IOException {
username = reader.readUTF("username");
age = reader.readInt("age");
active = reader.readBoolean("active");
}
}
public static class ThePortableFactory implements PortableFactory {
public static final int FACTORY_ID = 1;
@Override
public Portable create(int classId) {
if (classId == User.CLASS_ID) {
return new User();
}
return null;
}
}
private static void generateUsers(IMap users) {
users.put("Rod", new User("Rod", 19, true));
users.put("Jane", new User("Jane", 20, true));
users.put("Freddy", new User("Freddy", 23, true));
}
public static void main(String[] args) {
ClientConfig clientConfig = new ClientConfig();
clientConfig.getSerializationConfig()
.addPortableFactory(ThePortableFactory.FACTORY_ID, new ThePortableFactory());
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient(clientConfig);
// Get a Distributed Map called "users"
IMap users = hz.getMap("users");
// Add some users to the Distributed Map
generateUsers(users);
// Create a Predicate from a String (a SQL like Where clause)
Predicate sqlQuery = new SqlPredicate("active AND age BETWEEN (18 AND 21)");
// Creating the same Predicate as above but with a builder
Predicate criteriaQuery = Predicates.and(
Predicates.equal("active", true),
Predicates.between("age", 18, 21)
);
// Get result collections using the two different Predicates
Collection result1 = users.values(sqlQuery);
Collection result2 = users.values(criteriaQuery);
// Print out the results
System.out.println(result1);
System.out.println(result2);
// Shutdown this Hazelcast Client
hz.shutdown();
}
}
Get this code sample on Github
package client;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import java.util.concurrent.locks.Lock;
public class LockSample {
public static void main(String[] args) {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastInstance hz = HazelcastClient.newHazelcastClient();
// Get a distributed lock called "my-distributed-lock"
Lock lock = hz.getLock("my-distributed-lock");
// Now create a lock and execute some guarded code.
lock.lock();
try {
//do something here
} finally {
lock.unlock();
}
// Shutdown this Hazelcast Client
hz.shutdown();
}
}
Get this code sample on Github
using Hazelcast.Client;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class MapSample
{
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get the Distributed Map from Cluster.
var map = hz.GetMap("my-distributed-map");
//Standard Put and Get.
map.Put("key", "value");
map.Get("key");
//Concurrent Map methods, optimistic updating
map.PutIfAbsent("somekey", "somevalue");
map.Replace("key", "value", "newvalue");
// Shutdown this Hazelcast Client
hz.Shutdown();
}
}
}
Get this code sample on Github
using System;
using Hazelcast.Client;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class ReplicatedMapSample
{
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get a Replicated Map called "my-replicated-map"
var map = hz.GetReplicatedMap("my-replicated-map");
// Put and Get a value from the Replicated Map
var replacedValue = map.Put("key", "value"); // key/value replicated to all members
Console.WriteLine("replacedValue = " + replacedValue); // Will be null as its first update
var value = map.Get("key"); // the value is retrieved from a random member in the cluster
Console.WriteLine("value for key = " + value);
// Shutdown this Hazelcast Client
hz.Shutdown();
}
}
}
Get this code sample on Github
using System;
using Hazelcast.Client;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class DistributedMultiMapSample
{
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get the Distributed MultiMap from Cluster.
var multiMap = hz.GetMultiMap("my-distributed-multimap");
// Put values in the map against the same key
multiMap.Put("my-key", "value1");
multiMap.Put("my-key", "value2");
multiMap.Put("my-key", "value3");
// Print out all the values for associated with key called "my-key"
var values = multiMap.Get("my-key");
foreach (var item in values)
{
Console.WriteLine(item);
}
// remove specific key/value pair
multiMap.Remove("my-key", "value2");
// Shutdown this Hazelcast Client
hz.Shutdown();
}
}
}
Get this code sample on Github
using System;
using Hazelcast.Client;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class SetSample
{
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get the Distributed Set from Cluster.
var set = hz.GetSet("my-distributed-set");
// Add items to the set with duplicates
set.Add("item1");
set.Add("item1");
set.Add("item2");
set.Add("item2");
set.Add("item2");
set.Add("item3");
// Get the items. Note that there are no duplicates.
foreach (var item in set)
{
Console.WriteLine(item);
}
// Shutdown this Hazelcast client
hz.Shutdown();
}
}
}
Get this code sample on Github
using System;
using Hazelcast.Client;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class ListSample
{
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get the Distributed List from Cluster.
var list = hz.GetList("my-distributed-list");
// Add elements to the list
list.Add("item1");
list.Add("item2");
// Remove the first element
Console.WriteLine("Removed: " + list.Remove(0));
// There is only one element left
Console.WriteLine("Current size is " + list.Size());
// Clear the list
list.Clear();
// Shutdown this Hazelcast client
hz.Shutdown();
}
}
}
Get this code sample on Github
using System;
using Hazelcast.Client;
using Hazelcast.Core;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class QueueSample
{
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get a Blocking Queue called "my-distributed-queue"
var queue = hz.GetQueue("my-distributed-queue");
// Offer a String into the Distributed Queue
queue.Offer("item");
// Poll the Distributed Queue and return the String
queue.Poll();
//Timed blocking Operations
queue.Offer("anotheritem", 500, TimeUnit.Milliseconds);
queue.Poll(5, TimeUnit.Seconds);
//Indefinitely blocking Operations
queue.Put("yetanotheritem");
Console.WriteLine(queue.Take());
// Shutdown this Hazelcast Client
hz.Shutdown();
}
}
}
Get this code sample on Github
using System;
using Hazelcast.Client;
using Hazelcast.Core;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class TopicSample : IMessageListener
{
public void OnMessage(Message message)
{
Console.WriteLine("Got message " + message.GetMessageObject());
}
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get a Topic called "my-distributed-topic"
var topic = hz.GetTopic("my-distributed-topic");
// Add a Listener to the Topic
topic.AddMessageListener(new TopicSample());
// Publish a message to the Topic
topic.Publish("Hello to distributed world");
// Shutdown this Hazelcast Client
hz.Shutdown();
}
}
}
Get this code sample on Github
using System;
using Hazelcast.Client;
using Hazelcast.Config;
using Hazelcast.Core;
using Hazelcast.IO.Serialization;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class QuerySample
{
public class User : IPortable
{
public const int ClassId = 1;
private string _username;
private int _age;
private bool _active;
public User()
{
}
public User(string username, int age, bool active)
{
_username = username;
_age = age;
_active = active;
}
public int GetFactoryId()
{
return PortableFactory.FactoryId;
}
public int GetClassId()
{
return ClassId;
}
public void ReadPortable(IPortableReader reader)
{
_username = reader.ReadUTF("username");
_age = reader.ReadInt("age");
_active = reader.ReadBoolean("active");
}
public void WritePortable(IPortableWriter writer)
{
writer.WriteUTF("username", _username);
writer.WriteInt("age", _age);
writer.WriteBoolean("active", _active);
}
}
public class PortableFactory : IPortableFactory
{
public const int FactoryId = 1;
public IPortable Create(int classId)
{
if (classId == User.ClassId) return new User();
return null;
}
}
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var clientConfig = new ClientConfig();
clientConfig.GetSerializationConfig()
.AddPortableFactory(PortableFactory.FactoryId, new PortableFactory());
var hz = HazelcastClient.NewHazelcastClient(clientConfig);
// Get a Distributed Map called "users"
var users = hz.GetMap("users");
// Add some users to the Distributed Map
GenerateUsers(users);
// Create a Predicate from a String (a SQL like Where clause)
var sqlQuery = Predicates.Sql("active AND age BETWEEN 18 AND 21)");
// Creating the same Predicate as above but with a builder
var criteriaQuery = Predicates.And(
Predicates.IsEqual("active", true),
Predicates.IsBetween("age", 18, 21)
);
// Get result collections using the two different Predicates
var result1 = users.Values(sqlQuery);
var result2 = users.Values(criteriaQuery);
// Print out the results
Console.WriteLine(result1);
Console.WriteLine(result2);
// Shutdown this Hazelcast Client
hz.Shutdown();
}
private static void GenerateUsers(IMap users)
{
users.Put("Rod", new User("Rod", 19, true));
users.Put("Jane", new User("Jane", 20, true));
users.Put("Freddy", new User("Freddy", 23, true));
}
}
}
Get this code sample on Github
using Hazelcast.Client;
namespace Hazelcast.Examples.Org.Website.Samples
{
public class LockSample
{
public static void Run(string[] args)
{
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
var hz = HazelcastClient.NewHazelcastClient();
// Get a distributed lock called "my-distributed-lock"
var lck = hz.GetLock("my-distributed-lock");
// Now create a lock and execute some guarded code.
lck.Lock();
try
{
//do something here
}
finally
{
lck.Unlock();
}
// Shutdown this Hazelcast Client
hz.Shutdown();
}
}
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
using namespace hazelcast::client;
int main() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastClient hz;
// Get the Distributed Map from Cluster.
IMap map = hz.getMap("my-distributed-map");
//Standard Put and Get.
map.put("key", "value");
map.get("key");
//Concurrent Map methods, optimistic updating
map.putIfAbsent("somekey", "somevalue");
map.replace("key", "value", "newvalue");
// Shutdown this Hazelcast Client
hz.shutdown();
return 0;
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
using namespace hazelcast::client;
int main() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastClient hz;
// Get the Distributed MultiMap from Cluster.
MultiMap multiMap = hz.getMultiMap("my-distributed-multimap");
// Put values in the map against the same key
multiMap.put("my-key", "value1");
multiMap.put("my-key", "value2");
multiMap.put("my-key", "value3");
// Print out all the values for associated with key called "my-key"
std::vector values = multiMap.get("my-key");
for (std::vector::const_iterator it = values.begin();it != values.end(); ++it) {
std::cout << *it << std::endl;
}
// remove specific key/value pair
multiMap.remove("my-key", "value2"); // Shutdown this Hazelcast Client
hz.shutdown();
return 0;
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
using namespace hazelcast::client;
int main() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastClient hz;
// Get the Distributed Set from Cluster.
ISet set = hz.getSet("my-distributed-set");
// Add items to the set with duplicates
set.add("item1");
set.add("item1");
set.add("item2");
set.add("item2");
set.add("item2");
set.add("item3");
// Get the items. Note that there are no duplicates.
std::vector values = set.toArray();
for (std::vector::const_iterator it=values.begin();it != values.end();++it) {
std::cout << (*it) << std::endl;
}
// Shutdown this Hazelcast Client
hz.shutdown();
return 0;
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
using namespace hazelcast::client;
int main() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastClient hz;
// Get the Distributed List from Cluster.
IList list = hz.getList("my-distributed-list");
// Add elements to the list
list.add("item1");
list.add("item2");
// Remove the first element
std::cout << "Removed: " << *list.remove(0);
// There is only one element left
std::cout << "Current size is " << list.size() << std::endl;
// Clear the list
list.clear();
// Shutdown this Hazelcast Client
hz.shutdown();
return 0;
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
using namespace hazelcast::client;
int main() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastClient hz;
// Get a Blocking Queue called "my-distributed-queue"
IQueue queue = hz.getQueue("my-distributed-queue");
// Offer a String into the Distributed Queue
queue.offer("item");
// Poll the Distributed Queue and return the String
boost::shared_ptr item = queue.poll();
//Timed blocking Operations
queue.offer("anotheritem", 500);
boost::shared_ptr anotherItem = queue.poll(5 * 1000);
//Indefinitely blocking Operations
queue.put("yetanotheritem");
std::cout << *queue.take() << std::endl;
// Shutdown this Hazelcast Client
hz.shutdown();
return 0;
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
using namespace hazelcast::client;
class TopicSample : public topic::MessageListener {
public:
virtual void onMessage(std::auto_ptr > message) {
std::cout << "Got message " <<message-> getMessageObject() << std::endl;
}
};
int main() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastClient hz;
// Get a Topic called "my-distributed-topic"
ITopic topic = hz.getTopic("my-distributed-topic");
// Add a Listener to the Topic
TopicSample listener;
topic.addMessageListener(listener);
// Publish a message to the Topic
topic.publish("Hello to distributed world");
// Shutdown this Hazelcast Client
hz.shutdown();
return 0;
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
#include <hazelcast/client/query/SqlPredicate.h>
#include <hazelcast/client/query/AndPredicate.h>
#include <hazelcast/client/query/EqualPredicate.h>
#include <hazelcast/client/query/BetweenPredicate.h>
#include <hazelcast/client/serialization/PortableWriter.h>
#include <hazelcast/client/serialization/PortableReader.h>
#include <ostream>
using namespace hazelcast::client;
class User : public serialization::Portable {
public:
static const int CLASS_ID = 1;
User(const std::string &username, int age, bool active) : username(username), age(age), active(active) {
}
User() : age(0), active(false) {
}
virtual int getFactoryId() const {
return 1;
}
virtual int getClassId() const {
return CLASS_ID;
}
virtual void writePortable(serialization::PortableWriter &writer) const {
writer.writeUTF("username", &username);
writer.writeInt("age", age);
writer.writeBoolean("active", active);
}
virtual void readPortable(serialization::PortableReader &reader) {
username = *reader.readUTF("username");
age = reader.readInt("age");
active = reader.readBoolean("active");
}
friend std::ostream &operator<<(std::ostream &os, const User &user) {
os << "User{" << " username: " << user.username << " age: " << user.age << " active: " << user.active << '}';
return os;
}
private:
std::string username;
int age;
bool active;
};
class ThePortableFactory : public serialization::PortableFactory {
public:
static const int FACTORY_ID = 1;
virtual std::auto_ptr create(int32_t classId) const {
if (classId == User::CLASS_ID) {
return std::auto_ptr(new User());
}
return std::auto_ptr();
}
};
void generateUsers(IMap &users) {
users.put("Rod", User("Rod", 19, true));
users.put("Jane", User("Jane", 20, true));
users.put("Freddy", User("Freddy", 23, true));
}
int main() {
ClientConfig clientConfig;
clientConfig.getSerializationConfig().addPortableFactory(ThePortableFactory::FACTORY_ID,
boost::shared_ptr(
new ThePortableFactory()));
HazelcastClient hz(clientConfig);
// Get a Distributed Map called "users"
IMap users = hz.getMap("users");
// Add some users to the Distributed Map
generateUsers(users);
// Create a Predicate from a String (a SQL like Where clause)
query::SqlPredicate sqlQuery = query::SqlPredicate("active AND age BETWEEN 18 AND 21)");
// Creating the same Predicate as above but with AndPredicate builder
query::AndPredicate criteriaQuery;
criteriaQuery.add(std::auto_ptr(new query::EqualPredicate("active", true)))
.add(std::auto_ptr(new query::BetweenPredicate("age", 18, 21)));
// Get result collections using the two different Predicates
std::vector result1 = users.values(sqlQuery);
std::vector result2 = users.values(criteriaQuery);
// Print out the results
std::cout << "Result 1:" << std::endl;
for (std::vector::const_iterator it = result1.begin(); it != result1.end(); ++it) {
std::cout << (*it) << std::endl;
}
std::cout << "Result 2:" << std::endl;
for (std::vector::const_iterator it = result2.begin(); it != result2.end(); ++it) {
std::cout << (*it) << std::endl;
}
hz.shutdown();
return 0;
}
Get this code sample on Github
#include <hazelcast/client/HazelcastAll.h>
using namespace hazelcast::client;
int main() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
HazelcastClient hz;
// Get a distributed lock called "my-distributed-lock"
ILock lock = hz.getILock("my-distributed-lock");
// Now create a lock and execute some guarded code.
lock.lock();
try {
//do something here
} catch (...) {
lock.unlock();
}
// Shutdown this Hazelcast Client
hz.shutdown();
return 0;
}
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var map;
// Get the Distributed Map from Cluster.
hz.getMap('my-distributed-map').then(function (mp) {
map = mp;
// Standard Put and Get.
return map.put('key', 'value');
}).then(function () {
return map.get('key');
}).then(function (val) {
// Concurrent Map methods, optimistic updating
return map.putIfAbsent('somekey', 'somevalue');
}).then(function () {
return map.replace('key', 'value', 'newvalue');
}).then(function (value) {
// Shutdown this Hazelcast client
hz.shutdown();
});
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var map;
// Get a Replicated Map called "my-replicated-map"
hz.getReplicatedMap('my-replicated-map').then(function (rmp) {
map = rmp;
// Put and Get a value from the Replicated Map
// key/value replicated to all members
return map.put('key', 'value');
}).then(function (replacedValue) {
console.log('replaced value = ' + replacedValue); // Will be null as its first update
return map.get('key');
}).then(function (value) {
// The value is retrieved from a random member in the cluster
console.log('value for key = ' + value);
// Shutdown this Hazelcast Client
hz.shutdown();
});
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var multiMap;
// Get the Distributed MultiMap from Cluster.
hz.getMultiMap('my-distributed-multimap').then(function (mmp) {
multiMap = mmp;
// Put values in the map against the same key
return multiMap.put('my-key', 'value1');
}).then(function () {
return multiMap.put('my-key', 'value2');
}).then(function () {
return multiMap.put('my-key', 'value3');
}).then(function () {
// Print out all the values for associated with key called "my-key"
return multiMap.get('my-key')
}).then(function (values) {
for (value of values) {
console.log(value);
}
// remove specific key/value pair
return multiMap.remove('my-key', 'value2');
}).then(function () {
// Shutdown this Hazelcast client
hz.shutdown();
});
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var set;
// Get the Distributed Set from Cluster.
hz.getSet('my-distributed-set').then(function (s) {
set = s;
// Add items to the set with duplicates
return set.add('item1');
}).then(function () {
return set.add('item1');
}).then(function () {
return set.add('item2');
}).then(function () {
return set.add('item2');
}).then(function () {
return set.add('item2');
}).then(function () {
return set.add('item3');
}).then(function () {
// Get the items. Note that there are no duplicates
return set.toArray();
}).then(function (values) {
console.log(values);
}).then(function () {
// Shutdown this Hazelcast client
hz.shutdown();
});
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var list;
// Get the Distributed List from Cluster.
hz.getList('my-distributed-list').then(function (l) {
list = l;
// Add elements to the list
return list.add('item1');
}).then(function () {
return list.add('item2');
}).then(function () {
//Remove the first element
return list.removeAt(0);
}).then(function (value) {
console.log(value);
// There is only one element left
return list.size();
}).then(function (len) {
console.log(len);
// Clear the list
return list.clear();
}).then(function () {
// Shutdown this Hazelcast client
hz.shutdown();
});
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var queue;
// Get a Blocking Queue called "my-distributed-queue"
hz.getQueue('my-distributed-queue').then(function (q) {
queue = q;
// Offer a String into the Distributed Queue
return queue.offer('item');
}).then(function () {
// Poll the Distributed Queue and return the String
return queue.poll();
}).then(function () {
// Timed blocking Operations
return queue.offer('anotheritem', 500);
}).then(function () {
return queue.poll(5000);
}).then(function () {
// Indefinitely blocking Operations
return queue.put('yetanotheritem');
}).then(function () {
return queue.take();
}).then(function (value) {
console.log(value);
// Shutdown this Hazelcast Client
hz.shutdown();
})
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var topic;
// Get a Topic called "my-distributed-topic"
hz.getReliableTopic("my-distributed-topic").then(function (t) {
topic = t;
// Add a Listener to the Topic
topic.addMessageListener(function (message) {
console.log(message);
});
// Publish a message to the Topic
return topic.publish('Hello to distributed world');
}).then(function () {
// Shutdown this Hazelcast Client
hz.shutdown();
});
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
var Predicates = require('hazelcast-client').Predicates;
var Config = require('hazelcast-client').Config;
function User(username, age, active) {
this.username = username;
this.age = age;
this.active = active;
}
User.prototype.readPortable = function (reader) {
this.username = reader.readUTF('username');
this.age = reader.readInt('age');
this.active = reader.readBoolean('active');
};
User.prototype.writePortable = function (writer) {
writer.writeUTF('username', this.username);
writer.writeInt('age', this.age);
writer.writeBoolean('active', this.active);
};
User.prototype.getFactoryId = function () {
return 1;
};
User.prototype.getClassId = function () {
return 1;
};
function PortableFactory() {
// Constructor sample
}
PortableFactory.prototype.create = function (classId) {
if (classId === 1) {
return new User();
}
return null;
};
function generateUsers(users) {
return users.put('Rod', new User('Rod', 19, true)).then(function () {
return users.put('Jane', new User('Jane', 20, true));
}).then(function () {
return users.put('Freddy', new User('Freddy', 23, true));
});
}
var cfg = new Config.ClientConfig();
cfg.serializationConfig.portableFactories[1] = new PortableFactory();
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient(cfg).then(function (hz) {
var users;
// Get a Distributed Map called "users"
hz.getMap('users').then(function (mp) {
users = mp;
// Add some users to the Distributed Map
return generateUsers(users)
}).then(function () {
// Create a Predicate
var criteriaQuery = Predicates.and(
Predicates.equal('active', true),
Predicates.between('age', 18, 21)
);
// Get result collections using the the Predicate
return users.valuesWithPredicate(criteriaQuery);
}).then(function (values) {
// Print out the results
console.log(values.toArray());
// Shutdown this Hazelcast Client
hz.shutdown();
})
});
Get this code sample on Github
var Client = require('hazelcast-client').Client;
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
Client.newHazelcastClient().then(function (hz) {
var lock;
// Get a distributed lock called "my-distributed-lock"
hz.getLock("my-distributed-lock").then(function (l) {
lock = l;
// Now create a lock and execute some guarded code.
return lock.lock();
}).then(function () {
// do something here
}).finally(function () {
return lock.unlock();
}).then(function () {
// Shutdown this Hazelcast Client
hz.shutdown();
});
});
Get this code sample on Github
import hazelcast
if __name__ == "__main__":
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz = hazelcast.HazelcastClient()
# Get the Distributed Map from Cluster.
map = hz.get_map("my-distributed-map").blocking()
# Standard Put and Get
map.put("key", "value")
map.get("key")
# Concurrent Map methods, optimistic updating
map.put_if_absent("somekey", "somevalue")
map.replace_if_same("key", "value", "newvalue")
# Shutdown this Hazelcast Client
hz.shutdown()
Get this code sample on Github
import hazelcast
if __name__ == "__main__":
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz = hazelcast.HazelcastClient()
# Get a Replicated Map called "my-replicated-map"
map = hz.get_replicated_map("my-replicated-map").blocking()
# Put and Get a value from the Replicated Map
replaced_value = map.put("key", "value")
# key/value replicated to all members
print("replaced value = {}".format(replaced_value))
# Will be None as its first update
value = map.get("key")
# the value is retrieved from a random member in the cluster
print("value for key = {}".format(value))
# Shutdown this Hazelcast Client
hz.shutdown()
Get this code sample on Github
import hazelcast
if __name__ == "__main__":
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz = hazelcast.HazelcastClient()
# Get the Distributed MultiMap from Cluster.
multi_map = hz.get_multi_map("my-distributed-multimap").blocking()
# Put values in the map against the same key
multi_map.put("my-key", "value1")
multi_map.put("my-key", "value2")
multi_map.put("my-key", "value3")
# Print out all the values for associated with key called "my-key"
values = multi_map.get("my-key")
print(values)
# remove specific key/value pair
multi_map.remove("my-key", "value2")
# Shutdown this Hazelcast Client
hz.shutdown()
Get this code sample on Github
import hazelcast
if __name__ == "__main__":
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz = hazelcast.HazelcastClient()
# Get the Distributed Set from Cluster.
set = hz.get_set("my-distributed-set").blocking()
# Add items to the set with duplicates
set.add("item1")
set.add("item1")
set.add("item2")
set.add("item2")
set.add("item2")
set.add("item3")
# Get the items. Note that there are no duplicates.
for item in set.get_all():
print(item)
# Shutdown this Hazelcast Client
hz.shutdown()
Get this code sample on Github
import hazelcast
if __name__ == "__main__":
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz = hazelcast.HazelcastClient()
# Get the Distributed List from Cluster.
list = hz.get_list("my-distributed-list").blocking()
# Add element to the list
list.add("item1")
list.add("item2")
# Remove the first element
print("Removed: {}".format(list.remove_at(0)))
# There is only one element left
print("Current size is {}".format(list.size()))
# Clear the list
list.clear()
# Shutdown this Hazelcast Client
hz.shutdown()
Get this code sample on Github
import hazelcast
if __name__ == "__main__":
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz = hazelcast.HazelcastClient()
# Get a Blocking Queue called "my-distributed-queue"
queue = hz.get_queue("my-distributed-queue").blocking()
# Offer a String into the Distributed Queue
queue.offer("item")
# Poll the Distributed Queue and return the String
item = queue.poll()
# Timed blocking Operations
queue.offer("anotheritem", 0.5)
another_item = queue.poll(5)
# Indefinitely blocking Operations
queue.put("yetanotheritem")
print(queue.take())
# Shutdown this Hazelcast Client
hz.shutdown()
Get this code sample on Github
import hazelcast
from hazelcast import ClientConfig
from hazelcast.serialization.api import Portable
from hazelcast.serialization.predicate import SqlPredicate, and_, is_between, is_equal_to
class User(Portable):
FACTORY_ID = 1
CLASS_ID = 1
def __init__(self, username=None, age=None, active=None):
self.username = username
self.age = age
self.active = active
def write_portable(self, writer):
writer.write_utf("username", self.username)
writer.write_int("age", self.age)
writer.write_boolean("active", self.active)
def read_portable(self, reader):
self.username = reader.read_utf("username")
self.age = reader.read_int("age")
self.active = reader.read_boolean("active")
def get_factory_id(self):
return self.FACTORY_ID
def get_class_id(self):
return self.CLASS_ID
def __repr__(self):
return "User[username='{}', age={}, active={}]".format(self.username, self.age, self.active)
def generate_users(users):
users.put("Rod", User("Rod", 19, True))
users.put("Jane", User("Jane", 20, True))
users.put("Freddy", User("Freddy", 23, True))
if __name__ == "__main__":
config = ClientConfig()
portable_factory = {User.CLASS_ID: User}
config.serialization_config.add_portable_factory(User.FACTORY_ID, portable_factory)
# Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz = hazelcast.HazelcastClient(config)
# Get a Distributed Map called "users"
users = hz.get_map("users").blocking()
# Add some users to the Distributed Map
generate_users(users)
# Create a Predicate from a String (a SQL like Where clause)
sql_query = SqlPredicate("active AND age BETWEEN 18 AND 21)")
# Creating the same Predicate as above but with a builder
criteria_query = and_(is_equal_to("active", True), is_between("age", 18, 21))
# Get result collections using the two different Predicates
result1 = users.values(sql_query)
result2 = users.values(criteria_query)
# Print out the results
print(result1)
print(result2)
# Shutdown this Hazelcast Client
hz.shutdown()
Get this code sample on Github
package orgwebsite
import "github.com/hazelcast/hazelcast-go-client"
func mapSampleRun() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClient()
// Get the Distributed Map from Cluster.
mp, _ := hz.GetMap("myDistributedMap")
//Standard Put and Get.
mp.Put("key", "value")
mp.Get("key")
//Concurrent Map methods, optimistic updating
mp.PutIfAbsent("somekey", "somevalue")
mp.ReplaceIfSame("key", "value", "newvalue")
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github
package orgwebsite
import (
"fmt"
"github.com/hazelcast/hazelcast-go-client"
)
func replicatedMapSampleRun() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClient()
// Get a Replicated Map called "my-replicated-map"
mp, _ := hz.GetReplicatedMap("my-replicated-map")
// Put and Get a value from the Replicated Map
replacedValue, _ := mp.Put("key", "value") // key/value replicated to all members
fmt.Println("replacedValue = ", replacedValue) // Will be null as its first update
value, _ := mp.Get("key") // the value is retrieved from a random member in the cluster
fmt.Println("value for key = ", value)
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github
package orgwebsite
import (
"fmt"
"github.com/hazelcast/hazelcast-go-client"
)
func multimapSampleRun() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClient()
// Get the Distributed MultiMap from Cluster.
multiMap, _ := hz.GetMultiMap("myDistributedMultimap")
// Put values in the map against the same key
multiMap.Put("my-key", "value1")
multiMap.Put("my-key", "value2")
multiMap.Put("my-key", "value3")
// Print out all the values for associated with key called "my-key"
values, _ := multiMap.Get("my-key")
fmt.Println(values)
// remove specific key/value pair
multiMap.Remove("my-key", "value2")
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github
package orgwebsite
import (
"fmt"
"github.com/hazelcast/hazelcast-go-client"
)
func setSampleRun() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClient()
// Get the distributed set from cluster
set, _ := hz.GetSet("my-distributed-set")
// Add items to the set with duplicates
set.Add("item1")
set.Add("item1")
set.Add("item2")
set.Add("item2")
set.Add("item3")
set.Add("item3")
// Get the items. Note that no duplicates
items, _ := set.ToSlice()
fmt.Println(items)
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github
package orgwebsite
import (
"fmt"
"github.com/hazelcast/hazelcast-go-client"
)
func listSampleRun() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClient()
// Get the distributed list from cluster
list, _ := hz.GetList("my-distributed-list")
// Add elements to the list
list.Add("item1")
list.Add("item2")
// Remove the first element
removed, _ := list.RemoveAt(0)
fmt.Println("removed: ", removed)
// There is only one element left
size, _ := list.Size()
fmt.Println("current size is: ", size)
// Clear the list
list.Clear()
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github
package orgwebsite
import (
"fmt"
"time"
"github.com/hazelcast/hazelcast-go-client"
)
func queueSampleRun() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClient()
// Get a Blocking Queue called "my-distributed-queue"
queue, _ := hz.GetQueue("my-distributed-queue")
// Offer a String into the Distributed Queue
queue.Offer("item")
// Poll the Distributed Queue and return the String
queue.Poll()
//Timed blocking Operations
queue.OfferWithTimeout("anotheritem", 500*time.Millisecond)
queue.PollWithTimeout(5 * time.Second)
//Indefinitely blocking Operations
queue.Put("yetanotheritem")
fmt.Println(queue.Take())
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github
package orgwebsite
import (
"fmt"
"github.com/hazelcast/hazelcast-go-client"
"github.com/hazelcast/hazelcast-go-client/core"
)
type topicMessageListener struct {
}
func (*topicMessageListener) OnMessage(message core.Message) {
fmt.Println("Got message: ", message.MessageObject())
}
func topicSampleRun() {
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClient()
// Get a Topic called "my-distributed-topic"
topic, _ := hz.GetTopic("my-distributed-topic")
// Add a Listener to the Topic
topic.AddMessageListener(&topicMessageListener{})
// Publish a message to the Topic
topic.Publish("Hello to distributed world")
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github
package orgwebsite
import (
"fmt"
"github.com/hazelcast/hazelcast-go-client"
"github.com/hazelcast/hazelcast-go-client/core"
"github.com/hazelcast/hazelcast-go-client/core/predicate"
"github.com/hazelcast/hazelcast-go-client/serialization"
)
const (
userClassID = 1
userFactoryID = 1
)
type User struct {
username string
age int32
active bool
}
func newUser(username string, age int32, active bool) *User {
return &User{
username: username,
age: age,
active: active,
}
}
func (u *User) FactoryID() int32 {
return userFactoryID
}
func (u *User) ClassID() int32 {
return userClassID
}
func (u *User) WritePortable(writer serialization.PortableWriter) error {
writer.WriteUTF("username", u.username)
writer.WriteInt32("age", u.age)
writer.WriteBool("active", u.active)
return nil
}
func (u *User) ReadPortable(reader serialization.PortableReader) error {
var err error
u.username, err = reader.ReadUTF("username")
if err != nil {
return err
}
u.age, err = reader.ReadInt32("age")
if err != nil {
return err
}
u.active, err = reader.ReadBool("active")
return err
}
type ThePortableFactory struct {
}
func (pf *ThePortableFactory) Create(classID int32) serialization.Portable {
if classID == userClassID {
return &User{}
}
return nil
}
func generateUsers(users core.Map) {
users.Put("Rod", newUser("Rod", 19, true))
users.Put("Jane", newUser("Jane", 20, true))
users.Put("Freddy", newUser("Freddy", 23, true))
}
func querySampleRun() {
clientConfig := hazelcast.NewConfig()
clientConfig.SerializationConfig().
AddPortableFactory(userFactoryID, &ThePortableFactory{})
// Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1
hz, _ := hazelcast.NewClientWithConfig(clientConfig)
// Get a Distributed Map called "users"
users, _ := hz.GetMap("users")
// Add some users to the Distributed Map
generateUsers(users)
// Create a Predicate from a String (a SQL like Where clause)
var sqlQuery = predicate.SQL("active AND age BETWEEN 18 AND 21)")
// Creating the same Predicate as above but with a builder
var criteriaQuery = predicate.And(
predicate.Equal("active", true),
predicate.Between("age", 18, 21))
// Get result collections using the two different Predicates
result1, _ := users.ValuesWithPredicate(sqlQuery)
result2, _ := users.ValuesWithPredicate(criteriaQuery)
// Print out the results
fmt.Println(result1)
fmt.Println(result2)
// Shutdown this hazelcast client
hz.Shutdown()
}
Get this code sample on Github