所有Hazelcast 数据结构的共同特征:
以下是你如何获取现有的数据结构的实例(map, queue, set, lock, topic, 等),以及当一个实例被创建或销毁时, 你如何可以监听到实例的事件通知。
import java.util.Collection;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.Instance;
import com.hazelcast.core.InstanceEvent;
import com.hazelcast.core.InstanceListener;
public class Sample implements InstanceListener {
public static void main(String[] args) {
Sample sample = new Sample();
Hazelcast.addInstanceListener(sample);
Collection<Instance> instances = Hazelcast.getInstances();
for (Instance instance : instances) {
System.out.println(instance.getInstanceType() + "," + instance.getId());
}
}
public void instanceCreated(InstanceEvent event) {
Instance instance = event.getInstance();
System.out.println("Created " + instance.getInstanceType() + "," + instance.getId());
}
public void instanceDestroyed(InstanceEvent event) {
Instance instance = event.getInstance();
System.out.println("Destroyed " + instance.getInstanceType() + "," + instance.getId());
}
}
Hazelcast 分布式队列是一个 java.util.concurrent.BlockingQueue 的实现 .
import com.hazelcast.core.Hazelcast;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
BlockingQueue<MyTask> q = Hazelcast.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
}
如果你有1 亿个 “任务”任务排队,你正在超过10 个JVM (或服务器)上运行相应代码,然后每个服务器进行1 千万任务对象(加上备份)。在集群范围内应用先进先出( FIFO )顺序处理所有队列操作。队列中的用户对象(如上面的例子的MyTask )必须是可序列化的( Serializable )。每JVM 为队列提供的最大容量和TTL (生存时间)是可配置的,如显示在下面的例子。
<hazelcast>
...
<queue name="default">
<!--
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>
<!--
Maximum number of seconds for each item to stay in the queue. Items that are
not consumed in <time-to-live-seconds> will get automatically evicted from the queue.
Any integer between 0 and Integer.MAX_VALUE. 0 means infinite. Default is 0.
-->
<time-to-live-seconds>0</time-to-live-seconds>
</queue>
</hazelcast>