com.hazelcast.core.Hazelcast Java Examples
The following examples show how to use
com.hazelcast.core.Hazelcast.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClientBasicTestCase.java From snowcast with Apache License 2.0 | 6 votes |
@Test public void test_simple_sequencer_initialization() throws Exception { Hazelcast.newHazelcastInstance(config); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); try { Snowcast snowcast = SnowcastSystem.snowcast(client); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); assertNotNull(sequencer); } finally { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } }
Example #2
Source File: HazelcastMemoryService.java From sakai with Educational Community License v2.0 | 6 votes |
/** * Service INIT */ public void init() { String clientServers = serverConfigurationService.getString("memory.hc.server", null); boolean clientConfigured = StringUtils.isNotBlank(clientServers); if (clientConfigured) { ClientConfig clientConfig = new ClientConfig(); ClientNetworkConfig clientNetworkConfig = new ClientNetworkConfig(); clientNetworkConfig.addAddress(StringUtils.split(clientServers, ',')); clientConfig.setNetworkConfig(clientNetworkConfig); hcInstance = HazelcastClient.newHazelcastClient(clientConfig); } else { // start up a local server instead Config localConfig = new Config(); localConfig.setInstanceName(serverConfigurationService.getServerIdInstance()); hcInstance = Hazelcast.newHazelcastInstance(localConfig); } if (hcInstance == null) { throw new IllegalStateException("init(): HazelcastInstance is null!"); } log.info("INIT: " + hcInstance.getName() + " ("+(clientConfigured?"client:"+hcInstance.getClientService():"localServer")+"), cache maps: " + hcInstance.getDistributedObjects()); }
Example #3
Source File: HazelcastMemoryService.java From sakai with Educational Community License v2.0 | 6 votes |
/** * Service INIT */ public void init() { String clientServers = serverConfigurationService.getString("memory.hc.server", null); boolean clientConfigured = StringUtils.isNotBlank(clientServers); if (clientConfigured) { ClientConfig clientConfig = new ClientConfig(); ClientNetworkConfig clientNetworkConfig = new ClientNetworkConfig(); clientNetworkConfig.addAddress(StringUtils.split(clientServers, ',')); clientConfig.setNetworkConfig(clientNetworkConfig); hcInstance = HazelcastClient.newHazelcastClient(clientConfig); } else { // start up a local server instead Config localConfig = new Config(); localConfig.setInstanceName(serverConfigurationService.getServerIdInstance()); hcInstance = Hazelcast.newHazelcastInstance(localConfig); } if (hcInstance == null) { throw new IllegalStateException("init(): HazelcastInstance is null!"); } log.info("INIT: " + hcInstance.getName() + " ("+(clientConfigured?"client:"+hcInstance.getClientService():"localServer")+"), cache maps: " + hcInstance.getDistributedObjects()); }
Example #4
Source File: ClientBasicTestCase.java From snowcast with Apache License 2.0 | 6 votes |
@Test public void test_sequencer_timestamp() throws Exception { Hazelcast.newHazelcastInstance(config); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); try { Snowcast snowcast = SnowcastSystem.snowcast(client); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); int boundedNodeCount = calculateBoundedMaxLogicalNodeCount(128); int shifting = calculateLogicalNodeShifting(boundedNodeCount); long sequence = generateSequenceId(10000, 10, 100, shifting); assertEquals(10000, sequencer.timestampValue(sequence)); } finally { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } }
Example #5
Source File: ServerFoo.java From camelinaction2 with Apache License 2.0 | 6 votes |
public void boot() throws Exception { // create and embed the hazelcast server // (you can use the hazelcast client if you want to connect to external hazelcast server) HazelcastInstance hz = Hazelcast.newHazelcastInstance(); // setup the hazelcast route policy HazelcastRoutePolicy routePolicy = new HazelcastRoutePolicy(hz); // the lock names must be same in the foo and bar server routePolicy.setLockMapName("myLock"); routePolicy.setLockKey("myLockKey"); routePolicy.setLockValue("myLockValue"); // attempt to grab lock every 5th second routePolicy.setTryLockTimeout(5, TimeUnit.SECONDS); main = new Main(); // bind the hazelcast route policy to the name myPolicy which we refer to from the route main.bind("myPolicy", routePolicy); // add the route and and let the route be named Bar and use a little delay when processing the files main.addRouteBuilder(new FileConsumerRoute("Foo", 100)); main.run(); }
Example #6
Source File: ListenerDemo.java From hazelcast-demo with Apache License 2.0 | 6 votes |
public static void main(String[] args) { HazelcastInstance ins = Hazelcast.newHazelcastInstance(); IMap<Integer, String> map = ins.getMap(""); map.addEntryListener(new ListenerExample(), true);//添加自定义监听器 map.put(1, "Grand Theft Auto"); map.put(1, "Final Fantasy"); map.put(2, "World Of Warcraft"); HazelcastInstance insex = Hazelcast.newHazelcastInstance(); IMap<Integer, String> mapex = insex.getMap(""); System.out.println(mapex.get(1)); System.out.println(mapex.get(2)); mapex.remove(1); mapex.remove(2); System.exit(0); }
Example #7
Source File: HazelcastSessionDataStorageTest.java From pippo with Apache License 2.0 | 6 votes |
/** * Test of save method, of class HazelcastSessionDataStorage. */ @Test public void testSave() { HazelcastInstance hazelcastInstance1 = Hazelcast.newHazelcastInstance(); HazelcastInstance hazelcastInstance2 = Hazelcast.newHazelcastInstance(); System.out.println("save"); HazelcastSessionDataStorage instance = new HazelcastSessionDataStorage(hazelcastInstance1); SessionData sessionData = instance.create(); String sessionId = sessionData.getId(); sessionData.put(KEY, VALUE); instance.save(sessionData); SessionData saved = hazelcastInstance2 .<String, SessionData>getMap(SESSION_NAME) .get(sessionId); assertEquals(sessionData, saved); }
Example #8
Source File: AtomicExample.java From chuidiang-ejemplos with GNU Lesser General Public License v3.0 | 6 votes |
public static void main( String[] args ) throws FileNotFoundException, InterruptedException { Config config = new Config(); HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config); IAtomicLong atomicLong = hazelcastInstance.getAtomicLong("soy productor"); boolean cambiado = atomicLong.compareAndSet(0, 1); if (cambiado){ produce(hazelcastInstance); } else { consume(hazelcastInstance); } }
Example #9
Source File: ClientBasicTestCase.java From snowcast with Apache License 2.0 | 6 votes |
@Test public void test_sequencer_counter_value() throws Exception { Hazelcast.newHazelcastInstance(config); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); try { Snowcast snowcast = SnowcastSystem.snowcast(client); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); int boundedNodeCount = calculateBoundedMaxLogicalNodeCount(128); int shifting = calculateLogicalNodeShifting(boundedNodeCount); long sequence = generateSequenceId(10000, 10, 100, shifting); assertEquals(100, sequencer.counterValue(sequence)); } finally { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } }
Example #10
Source File: ClientBasicTestCase.java From snowcast with Apache License 2.0 | 6 votes |
@Test public void test_sequencer_logical_node_id() throws Exception { Hazelcast.newHazelcastInstance(config); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); try { Snowcast snowcast = SnowcastSystem.snowcast(client); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); int boundedNodeCount = calculateBoundedMaxLogicalNodeCount(128); int shifting = calculateLogicalNodeShifting(boundedNodeCount); long sequence = generateSequenceId(10000, 10, 100, shifting); assertEquals(10, sequencer.logicalNodeId(sequence)); } finally { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } }
Example #11
Source File: ClientBasicTestCase.java From snowcast with Apache License 2.0 | 6 votes |
@Test(expected = SnowcastStateException.class) public void test_id_generation_in_attach_wrong_state() throws Exception { Hazelcast.newHazelcastInstance(config); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); try { Snowcast snowcast = SnowcastSystem.snowcast(client); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); assertNotNull(sequencer); sequencer.attachLogicalNode(); } finally { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } }
Example #12
Source File: ClientBasicTestCase.java From snowcast with Apache License 2.0 | 6 votes |
@Test public void test_single_id_generation() throws Exception { Hazelcast.newHazelcastInstance(config); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); try { Snowcast snowcast = SnowcastSystem.snowcast(client); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); assertNotNull(sequencer); assertNotNull(sequencer.next()); } finally { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } }
Example #13
Source File: ServerFoo.java From camelinaction2 with Apache License 2.0 | 6 votes |
public void boot(String[] args) throws Exception { // create and embed the hazelcast server // (you can use the hazelcast client if you want to connect to external hazelcast server) HazelcastInstance hz = Hazelcast.newHazelcastInstance(); main = new Main(); main.bind("hz", hz); if (args.length == 0) { // route which uses get/put operations main.addRouteBuilder(new CounterRoute("Foo", 8080)); } else { // route which uses atomic counter main.addRouteBuilder(new AtomicCounterRoute("Foo", 8080)); } main.run(); }
Example #14
Source File: HazelcastReentrantReadWriteLockTest.java From hazelcast-locks with Apache License 2.0 | 6 votes |
@BeforeClass public static void createGrids() { /* Suppress Hazelcast log output to standard error which does not appear to be suppressible via Agent Server's * log4j.xml. */ // ConsoleOutputSuppressor.suppressStandardError(); final Config standardConfig1 = new ClasspathXmlConfig("hazelcast1.xml"), standardConfig2 = new ClasspathXmlConfig("hazelcast2.xml"); standardConfig1.setProperty("hazelcast.operation.call.timeout.millis", "3000"); standardConfig2.setProperty("hazelcast.operation.call.timeout.millis", "3000"); grid1 = Hazelcast.newHazelcastInstance(standardConfig1); grid2 = Hazelcast.newHazelcastInstance(standardConfig2); dataStructureFactory1 = HazelcastDataStructureFactory.getInstance(grid1); dataStructureFactory2 = HazelcastDataStructureFactory.getInstance(grid2); lockService1 = new DistributedLockUtils().new PublicDistributedLockService(dataStructureFactory1); lockService2 = new DistributedLockUtils().new PublicDistributedLockService(dataStructureFactory2); }
Example #15
Source File: HazelcastCacheMetricsCompatibilityTest.java From micrometer with Apache License 2.0 | 6 votes |
@Disabled("This only demonstrates why we can't support miss count in Hazelcast.") @Issue("#586") @Test void multiInstanceMissCount() { IMap<String, String> cache2 = Hazelcast.newHazelcastInstance(config).getMap("mycache"); // Since each member owns 1/N (N being the number of members in the cluster) entries of a distributed map, // we add two entries so we can deterministically say that each cache will "own" one entry. cache.put("k1", "v"); cache.put("k2", "v"); cache.get("k1"); cache.get("k2"); // cache stats: hits = 1, gets = 2, puts = 2 // cache2 stats: hits = 1, gets = 0, puts = 0 assertThat(cache.getLocalMapStats().getHits()).isEqualTo(1); assertThat(cache.getLocalMapStats().getGetOperationCount()).isEqualTo(2); assertThat(cache2.getLocalMapStats().getHits()).isEqualTo(1); // ... and this is why we can't calculate miss count in Hazelcast. sorry! }
Example #16
Source File: NodeSelector.java From JPPF with Apache License 2.0 | 6 votes |
/** * Initialize this node selector and distribute the trades among the nodes. * @param trades the list of trades to distribute among the nodes. * @param nodeIdList the list of node ids. */ public NodeSelector(final List<Trade> trades, final List<String> nodeIdList) { System.out.println("populating the trades"); this.nodeIdList = nodeIdList; final int nbNodes = nodeIdList.size(); final Trade[] tradeArray = trades.toArray(new Trade[0]); //for (int i=0; i<tradeArray.length; i++) tradeToNodeMap.put(tradeArray[i].getId(), nodeIdList.get(i % nbNodes)); final ExecutorService executor = Executors.newFixedThreadPool(nbNodes); final List<Future<?>> futures = new ArrayList<>(); for (int i=0; i<nbNodes; i++) { final String nodeId = nodeIdList.get(i); final Map<String, Trade> hazelcastMap = Hazelcast.getMap(ModelConstants.TRADE_MAP_PREFIX + nodeId); nodeToHazelcastMap.put(nodeId, hazelcastMap); futures.add(executor.submit(new PopulateTradesTask(tradeArray, i, nbNodes, hazelcastMap))); } for (final Future<?> f: futures) { try { f.get(); } catch(final Exception e) { e.printStackTrace(); } } executor.shutdownNow(); System.out.println("end of populating the trades"); }
Example #17
Source File: HazelcastScheduler.java From greycat with Apache License 2.0 | 6 votes |
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()); }
Example #18
Source File: ClientBasicTestCase.java From snowcast with Apache License 2.0 | 5 votes |
@Test(expected = SnowcastStateException.class) public void test_destroyed_state() throws Exception { Hazelcast.newHazelcastInstance(config); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); try { Snowcast snowcast = SnowcastSystem.snowcast(client); SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast); assertNotNull(sequencer); assertNotNull(sequencer.next()); snowcast.destroySequencer(sequencer); long deadline = System.currentTimeMillis() + 60000; while (true) { // Will eventually fail sequencer.next(); if (System.currentTimeMillis() >= deadline) { // Safe exit after another minute of waiting for the event return; } } } finally { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } }
Example #19
Source File: HazelcastLocal.java From j2cache with Apache License 2.0 | 5 votes |
public synchronized HazelcastInstance getHazelcast() { if (hazelcast == null) { Config config = new ClasspathXmlConfig("org/j2server/j2cache/cache/hazelcast/hazelcast-cache-config.xml"); config.setInstanceName("j2cache"); hazelcast = Hazelcast.newHazelcastInstance(config); } return hazelcast; }
Example #20
Source File: ServerNode.java From tutorials with MIT License | 5 votes |
public static void main(String[] args) { HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); Map<Long, String> map = hazelcastInstance.getMap("data"); IdGenerator idGenerator = hazelcastInstance.getIdGenerator("newid"); for (int i = 0; i < 10; i++) { map.put(idGenerator.newId(), "message" + 1); } }
Example #21
Source File: HazelcastGetStartServerMaster.java From hazelcast-demo with Apache License 2.0 | 5 votes |
public static void main(String[] args) { // 创建一个 hazelcastInstance实例 HazelcastInstance instance = Hazelcast.newHazelcastInstance(); // 创建集群Map Map<Integer, String> clusterMap = instance.getMap("MyMap"); clusterMap.put(1, "Hello hazelcast map!"); // 创建集群Queue Queue<String> clusterQueue = instance.getQueue("MyQueue"); clusterQueue.offer("Hello hazelcast!"); clusterQueue.offer("Hello hazelcast queue!"); }
Example #22
Source File: HazelcastManaged.java From cqrs-eventsourcing-kafka with Apache License 2.0 | 5 votes |
public static HazelcastInstance getInstance() { if (hazelcastInstance == null) { Config config = new XmlConfigBuilder().build(); config.setInstanceName(Thread.currentThread().getName()); hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(config); } return hazelcastInstance; }
Example #23
Source File: ClusterConfig.java From batchers with Apache License 2.0 | 5 votes |
@Bean public HazelcastInstance hazelcastInstance() { Config cfg = new Config(); //if batchersmaster in /etc/hosts points to a IP, try to add it to the cluster //if it does not, the cluster will just broadcast on UDP buildBatchersmasterTCPConfigIfNeeded(cfg); HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg); return hz; }
Example #24
Source File: HazelcastSessionDataStorageTest.java From pippo with Apache License 2.0 | 5 votes |
/** * Test of create method, of class HazelcastSessionDataStorage. */ @Test public void testCreate() { System.out.println("create"); HazelcastSessionDataStorage instance = new HazelcastSessionDataStorage(Hazelcast.newHazelcastInstance()); SessionData sessionData = instance.create(); sessionData.put(KEY, VALUE); assertNotNull(sessionData); assertNotNull(sessionData.getId()); assertNotNull(sessionData.getCreationTime()); assertEquals(sessionData.get(KEY), VALUE); }
Example #25
Source File: HazelcastSessionDao.java From dpCms with Apache License 2.0 | 5 votes |
public HazelcastSessionDao() { log.info("Initializing Hazelcast Shiro session persistence.."); // configure Hazelcast instance final Config cfg = new Config(); cfg.setInstanceName(hcInstanceName); // group configuration cfg.setGroupConfig(new GroupConfig(HC_GROUP_NAME, HC_GROUP_PASSWORD)); // network configuration initialization final NetworkConfig netCfg = new NetworkConfig(); netCfg.setPortAutoIncrement(true); netCfg.setPort(HC_PORT); // multicast final MulticastConfig mcCfg = new MulticastConfig(); mcCfg.setEnabled(false); mcCfg.setMulticastGroup(HC_MULTICAST_GROUP); mcCfg.setMulticastPort(HC_MULTICAST_PORT); // tcp final TcpIpConfig tcpCfg = new TcpIpConfig(); tcpCfg.addMember("127.0.0.1"); tcpCfg.setEnabled(false); // network join configuration final JoinConfig joinCfg = new JoinConfig(); joinCfg.setMulticastConfig(mcCfg); joinCfg.setTcpIpConfig(tcpCfg); netCfg.setJoin(joinCfg); // ssl netCfg.setSSLConfig(new SSLConfig().setEnabled(false)); // get map map = Hazelcast.newHazelcastInstance(cfg).getMap(HC_MAP); log.info("Hazelcast Shiro session persistence initialized."); }
Example #26
Source File: HazelcastClusteredAsynchronousLockTest.java From vertx-hazelcast with Apache License 2.0 | 5 votes |
@Override public void setUp() throws Exception { Random random = new Random(); System.setProperty("vertx.hazelcast.test.group.name", new BigInteger(128, random).toString(32)); for (int i = 0; i < DATA_NODES; i++) { dataNodes.add(Hazelcast.newHazelcastInstance(ConfigUtil.loadConfig())); } super.setUp(); }
Example #27
Source File: Initializer.java From spring-session with Apache License 2.0 | 5 votes |
private HazelcastInstance createHazelcastInstance() { Config config = new Config(); NetworkConfig networkConfig = config.getNetworkConfig(); networkConfig.setPort(0); networkConfig.getJoin().getMulticastConfig().setEnabled(false); config.getMapConfig(SESSION_MAP_NAME).setTimeToLiveSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); return Hazelcast.newHazelcastInstance(config); }
Example #28
Source File: SessionConfig.java From spring-session with Apache License 2.0 | 5 votes |
@Bean(destroyMethod = "shutdown") public HazelcastInstance hazelcastInstance() { Config config = new Config(); NetworkConfig networkConfig = config.getNetworkConfig(); networkConfig.setPort(0); networkConfig.getJoin().getMulticastConfig().setEnabled(false); MapAttributeConfig attributeConfig = new MapAttributeConfig() .setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE) .setExtractor(PrincipalNameExtractor.class.getName()); config.getMapConfig(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME) .addMapAttributeConfig(attributeConfig).addMapIndexConfig( new MapIndexConfig(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); return Hazelcast.newHazelcastInstance(config); }
Example #29
Source File: HazelcastSessionDao.java From dpCms with Apache License 2.0 | 5 votes |
/** * Destroys currently allocated instance. */ public void destroy() { log.info("Shutting down Hazelcast instance [{}]..", hcInstanceName); final HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName( hcInstanceName); if (instance != null) { instance.shutdown(); } }
Example #30
Source File: HazelcastClusteredAsyncMapTest.java From vertx-hazelcast with Apache License 2.0 | 5 votes |
@Override public void setUp() throws Exception { Random random = new Random(); System.setProperty("vertx.hazelcast.test.group.name", new BigInteger(128, random).toString(32)); for (int i = 0; i < DATA_NODES; i++) { dataNodes.add(Hazelcast.newHazelcastInstance(ConfigUtil.loadConfig())); } super.setUp(); }