本文共 2753 字,大约阅读时间需要 9 分钟。
使用Hazelcast
1.在pom.xml中配置对Hazelcast的依赖
com.hazelcast hazelcast 3.5.2
2.创建hazelcast server端和client端并运行
hazelcast server端程序代码
import com.hazelcast.core.Hazelcast;import com.hazelcast.core.HazelcastInstance;import java.util.Map;import java.util.Queue;public class GettingStarted { public static void main( String[] args ) { HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); Mapcustomers = hazelcastInstance.getMap( "customers" ); customers.put( 1, "Joe" ); customers.put( 2, "Ali" ); customers.put( 3, "Avi" ); System.out.println( "Customer with key 1: " + customers.get(1) ); System.out.println( "Map Size:" + customers.size() ); Queue queueCustomers = hazelcastInstance.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() ); }}
运行两次可以得到输出:
Members [2] { Member [127.0.0.1:5701] Member [127.0.0.1:5702] this}
在pom.xml里面添加对hazelcast client的依赖:
com.hazelcast hazelcast-client 3.5.2
创建客户端程序:
package com.hazelcast.test;import com.hazelcast.client.config.ClientConfig;import com.hazelcast.client.HazelcastClient;import com.hazelcast.core.HazelcastInstance;import com.hazelcast.core.IMap;public class GettingStartedClient { public static void main( String[] args ) { ClientConfig clientConfig = new ClientConfig(); HazelcastInstance client = HazelcastClient.newHazelcastClient( clientConfig ); IMap map = client.getMap( "customers" ); System.out.println( "Map Size:" + map.size() ); }}
运行客户端程序:
运行客户端后,客户端会连到先前创建的hazelcast集群,且输出map size为3.
在我们的这个示例中,没有配置任何Hazelcast配置文件。实际上,hazelcast会用默认的配置文件。
下面是hazelcast找寻配置文件的规则:
1.当一个hazelcast 节点启动的时候,它会先找寻hazelcast.config 系统属性。如果这个属性有被设置的话,那么hazelcast将会按照该属性的设置去找寻配置文件。
- Dhazelcast.config=
2.如果找不到属性,那么hazelcast会在当前工作目录中找寻hazelcast.xml
3.如果在工作目录中找不到,会在class path寻找hazelcast.xml
4.如果还是找不到,hazelcast会加载默认的配置文件。hazlelcast.jar包中的hazelcast-default.xml
========广告时间========
鄙人的新书《Tomcat内核设计剖析》已经在京东销售了,有需要的朋友可以到 进行预定。感谢各位朋友。
=========================
欢迎关注: