Java Code Examples for com.hazelcast.core.HazelcastInstance

The following examples show how to use com.hazelcast.core.HazelcastInstance. These examples are extracted from open source projects. 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 Project: snowcast   Source File: BasicTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = SnowcastStateException.class)
public void test_id_generation_in_detached_state()
        throws Exception {

    TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
    HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();

    try {
        Snowcast snowcast = SnowcastSystem.snowcast(hazelcastInstance);
        SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast);

        assertNotNull(sequencer);
        assertNotNull(sequencer.next());

        // Detach the node and free the currently used logical node ID
        sequencer.detachLogicalNode();

        sequencer.next();
    } finally {
        factory.shutdownAll();
    }
}
 
Example 2
public static void main( String[] args ) throws FileNotFoundException, InterruptedException
{
   Config config = new Config();
   HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config);
   
   IMap<String,String> map = hazelcastInstance.getMap("TimeToLiveMap");
   
   map.put("hola", "tu", 10, TimeUnit.SECONDS);
   
   while (true){
      Thread.sleep(1000);
      String dato =map.get("hola");
      if (null!=dato){
         System.out.println(dato);
      } else {
         break;
      }
   }
   System.out.println("Data expired");
}
 
Example 3
Source Project: flair-engine   Source File: CacheConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("fbiengine");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("fbiengine");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.fbi.engine.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 4
Source Project: snowcast   Source File: BasicTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_sequencer_timestamp()
        throws Exception {

    TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
    HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();

    try {
        Snowcast snowcast = SnowcastSystem.snowcast(hazelcastInstance);
        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 {
        factory.shutdownAll();
    }
}
 
Example 5
Source Project: hazelcast-simulator   Source File: Hazelcast4Driver.java    License: Apache License 2.0 6 votes vote down vote up
public static void warmupPartitions(HazelcastInstance hazelcastInstance) {
    LOGGER.info("Waiting for partition warmup");

    PartitionService partitionService = hazelcastInstance.getPartitionService();
    long started = System.nanoTime();
    for (Partition partition : partitionService.getPartitions()) {
        if (System.nanoTime() - started > PARTITION_WARMUP_TIMEOUT_NANOS) {
            throw new IllegalStateException("Partition warmup timeout. Partitions didn't get an owner in time");
        }

        while (partition.getOwner() == null) {
            LOGGER.debug("Partition owner is not yet set for partitionId: " + partition.getPartitionId());
            sleepMillisThrowException(PARTITION_WARMUP_SLEEP_INTERVAL_MILLIS);
        }
    }

    LOGGER.info("Partitions are warmed up successfully");
}
 
Example 6
Source Project: greycat   Source File: HazelcastScheduler.java    License: Apache License 2.0 6 votes vote down vote up
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 7
Source Project: subzero   Source File: TestCustomerSerializers.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGlobalCustomSerializationConfiguredProgrammaticallyForClientConfig() {
    Config memberConfig = new Config();
    SubZero.useAsGlobalSerializer(memberConfig);
    hazelcastFactory.newHazelcastInstance(memberConfig);

    String mapName = randomMapName();
    ClientConfig config = new ClientConfig();

    SubZero.useAsGlobalSerializer(config, MyGlobalUserSerlizationConfig.class);

    HazelcastInstance member = hazelcastFactory.newHazelcastClient(config);
    IMap<Integer, AnotherNonSerializableObject> myMap = member.getMap(mapName);
    myMap.put(0, new AnotherNonSerializableObject());
    AnotherNonSerializableObject fromCache = myMap.get(0);

    assertEquals("deserialized", fromCache.name);
}
 
Example 8
Source Project: snowcast   Source File: BasicTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_simple_sequencer_initialization_declarative()
        throws Exception {

    ClassLoader classLoader = BasicTestCase.class.getClassLoader();
    InputStream stream = classLoader.getResourceAsStream("hazelcast-node-configuration.xml");
    Config config = new XmlConfigBuilder(stream).build();

    TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
    HazelcastInstance hazelcastInstance = factory.newHazelcastInstance(config);

    try {
        Snowcast snowcast = SnowcastSystem.snowcast(hazelcastInstance);
        SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast);

        assertNotNull(sequencer);
    } finally {
        factory.shutdownAll();
    }
}
 
Example 9
Source Project: hazelcast-demo   Source File: ServiceNode.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	// 获取Hazelcast实例
	HazelcastInstance ins = Hazelcast.newHazelcastInstance();

	// 从集群中读取Map实例
	Map<Integer, String> map = ins.getMap("default map");

	// 向集群中添加数据
	System.out.println("Begin insert data");
	map.put(1, "Cait Cassiopeia");
	map.put(2, "Annie");
	map.put(3, "Evelynn");
	map.put(4, "Ashe");
	System.out.println("End");
	
}
 
Example 10
Source Project: mercury   Source File: TopicManager.java    License: Apache License 2.0 6 votes vote down vote up
private void createTopic(String topic) {
    if (!topicExists(topic)) {
        String now = Utility.getInstance().date2str(new Date(), true);
        String nodes = HazelcastSetup.NAMESPACE+NODES;
        String realTopic = HazelcastSetup.NAMESPACE+topic;
        HazelcastInstance client = HazelcastSetup.getHazelcastClient();
        IMap<String, byte[]> map = client.getMap(nodes);
        Map<String, String> metadata = new HashMap<>();
        metadata.put("node", topic);
        metadata.put("name", Platform.getInstance().getName());
        metadata.put("created", now);
        metadata.put("updated", now);
        try {
            map.put(topic, msgPack.pack(metadata));
            // create topic if not exists
            client.getReliableTopic(realTopic);
            log.info("Topic {} created", realTopic);
        } catch (IOException e) {
            // this does not happen
            log.error("Unable to create topic {} - {}", topic, e.getMessage());
        }
    }
}
 
Example 11
Source Project: minicubes   Source File: TimeSeriesMiniCubeManagerHzImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void handleNewMember(HazelcastInstance instance, Member member) {
    
    // Relationship between Member and MiniCube ID
    IMap<String, String> miniCubeManager = instance.getMap(MINICUBE_MANAGER);
    LOGGER.info("Minicube manager status {}", ObjectUtils.getDisplayString(miniCubeManager));
    
    String key = member.getSocketAddress().toString();
    // FIXME: load-pending status need refactor
    instance.getCluster().getLocalMember().setBooleanAttribute("load-pending", false);
    
    if (miniCubeManager.containsKey(key) && !miniCubeManager.get(key).startsWith("?")) {
        // Maybe node-restart
        LOGGER.info("A node{} restarted, so we need rebuild cube{}", key, miniCubeManager.get(key));
        // Reassign task.
        reassignRole(miniCubeManager.get(key), miniCubeManager.get(key).split("::")[0]);
    } else {
        // First time join into cluster
        String id = "?" + "::" + hzGroupName + "@" + key;
        miniCubeManager.put(key, id);
        
        member.setStringAttribute("cubeId", id);
        LOGGER.info("Add {} into cluster {}", id, hzGroupName);
    }
    LOGGER.info("Set load-pending status to false, enable reassign feature on {}", member);
}
 
Example 12
Source Project: camelinaction2   Source File: ServerFoo.java    License: Apache License 2.0 6 votes vote down vote up
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 13
Source Project: iotplatform   Source File: ServiceCacheConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance() {
    Config config = new Config();

    if (zkEnabled) {
        addZkConfig(config);
    }

    config.addMapConfig(createDeviceCredentialsCacheConfig());

    return Hazelcast.newHazelcastInstance(config);
}
 
Example 14
Source Project: hazelcastmq   Source File: TransactionAwareConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public HazelcastInstance transactionAwareHazelcast() {
  TransactionAwareHazelcastInstanceProxyFactory factory =
      new TransactionAwareHazelcastInstanceProxyFactory(hazelcast(), true);

  return factory.create();
}
 
Example 15
private static void produce(HazelcastInstance hazelcastInstance) {
   IQueue<String> cola = hazelcastInstance.getQueue("cola");
   
   int count=0;
   while (true){
      try {
         cola.offer(Integer.toString(count++));
         Thread.sleep(1000);
         System.out.println("Added to queue. It has now "+cola.size());
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }
}
 
Example 16
Source Project: hazelcast-demo   Source File: InterceptorDemo.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	HazelcastInstance ins = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> imap = ins.getMap("");
	imap.addInterceptor(new InterceptorExample());// 添加拦截器
	imap.put(1, "Mei");
	imap.put(1, "Tracer");
	imap.put(1, "D.va");
	imap.put(1, "Mercy");
	
	imap.get(1);
	imap.remove(1);
	System.out.println(imap.get(1));
}
 
Example 17
Source Project: hazelcast-simulator   Source File: KeyUtils.java    License: Apache License 2.0 5 votes vote down vote up
private Member getLocalMember(HazelcastInstance hz) {
    try {
        return hz.getCluster().getLocalMember();
    } catch (UnsupportedOperationException ignore) {
        // clients throw UnsupportedOperationExceptions
        return null;
    }
}
 
Example 18
Source Project: snowcast   Source File: SnowcastSequenceUtilsTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_comparator_first_higher_by_counter()
        throws Exception {

    TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
    HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();

    try {
        Snowcast snowcast = SnowcastSystem.snowcast(hazelcastInstance);
        SnowcastSequencer sequencer = buildSnowcastSequencer(snowcast);

        int boundedNodeCount = calculateBoundedMaxLogicalNodeCount(SnowcastConstants.DEFAULT_MAX_LOGICAL_NODES_13_BITS);
        int shifting = calculateLogicalNodeShifting(boundedNodeCount);
        long sequence1 = generateSequenceId(10000, 1, 2, shifting);
        long sequence2 = generateSequenceId(10000, 1, 1, shifting);

        Comparator<Long> comparator = SnowcastSequenceUtils.snowcastSequenceComparator(sequencer);

        assertEquals(1, comparator.compare(sequence1, sequence2));
    } finally {
        factory.shutdownAll();
    }
}
 
Example 19
public static void main(String[] args) {
	//创建一个 hazelcastInstance实例
	HazelcastInstance instance = Hazelcast.newHazelcastInstance();
	Map<Integer, String> clusterMap = instance.getMap("MyMap");
	Queue<String> clusterQueue = instance.getQueue("MyQueue");
	
	System.out.println("Map Value:" + clusterMap.get(1));
	System.out.println("Queue Size :" + clusterQueue.size());
	System.out.println("Queue Value 1:" + clusterQueue.poll());
	System.out.println("Queue Value 2:" + clusterQueue.poll());
	System.out.println("Queue Size :" + clusterQueue.size());
}
 
Example 20
Source Project: subzero   Source File: TestCustomerSerializers.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalCustomSerializer_SpecialRegistrationRegisteredInDefaultConfigFile() {
    String mapName = randomMapName();
    Config config = new Config();

    SubZero.useAsGlobalSerializer(config);
    HazelcastInstance member = hazelcastFactory.newHazelcastInstance(config);
    IMap<Integer, ClassWithUnmodifieableList> myMap = member.getMap(mapName);
    myMap.put(0, new ClassWithUnmodifieableList("foo"));

    //does not throw an exception
    myMap.get(0);
}
 
Example 21
Source Project: snowcast   Source File: ClientBasicTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = SnowcastStateException.class)
public void test_destroyed_state_from_node()
        throws Exception {

    HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config);
    HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);

    try {
        SnowcastEpoch epoch = buildEpoch();

        Snowcast snowcastClient = SnowcastSystem.snowcast(client);
        SnowcastSequencer sequencerClient = buildSnowcastSequencer(snowcastClient, epoch);

        assertNotNull(sequencerClient);
        assertNotNull(sequencerClient.next());

        Snowcast snowcastNode = SnowcastSystem.snowcast(hazelcastInstance);
        SnowcastSequencer sequencerNode = buildSnowcastSequencer(snowcastNode, epoch);

        assertNotNull(sequencerNode);
        assertNotNull(sequencerNode.next());

        snowcastNode.destroySequencer(sequencerNode);

        long deadline = System.currentTimeMillis() + 60000;
        while (true) {
            // Will eventually fail
            sequencerClient.next();

            if (System.currentTimeMillis() >= deadline) {
                // Safe exit after another minute of waiting for the event
                return;
            }
        }

    } finally {
        HazelcastClient.shutdownAll();
        Hazelcast.shutdownAll();
    }
}
 
Example 22
Source Project: hazelcast-simulator   Source File: HazelcastUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isMaster(final HazelcastInstance hazelcastInstance, ScheduledExecutorService executor,
                               int delaySeconds) {
    if (hazelcastInstance == null || !isOldestMember(hazelcastInstance)) {
        return false;
    }
    try {
        Callable<Boolean> callable = () -> isOldestMember(hazelcastInstance);
        ScheduledFuture<Boolean> future = executor.schedule(callable, delaySeconds, TimeUnit.SECONDS);
        return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 23
Source Project: youkefu   Source File: UKTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 选出新的 Master服务器
 * @param hazelcastInstance
 */
public static void voteMaster(HazelcastInstance hazelcastInstance) {
	Set<Member> members = hazelcastInstance.getCluster().getMembers() ;
   	Member master = null ;
   	for(Member member : members) {
   		if(master == null || (member!=null && member.getLongAttribute("start")!=null && member.getLongAttribute("start") < master.getLongAttribute("start"))) {
   			master = member ;
   		}
   	}
   	if(master!=null) {
   		hazelcastInstance.getTopic(UKDataContext.UCKeFuTopic.TOPIC_VOTE.toString()).publish(new RPCDataBean(master.getStringAttribute("id"), master.getAddress().getHost(), master.getAddress().getPort() , master.getLongAttribute("start")));
   	}
}
 
Example 24
Source Project: camelinaction2   Source File: ServerBar.java    License: Apache License 2.0 5 votes vote down vote up
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 idempotent repository which we will use in the route
    HazelcastIdempotentRepository repo = new HazelcastIdempotentRepository(hz, "camel");

    main = new Main();
    // bind the hazelcast repository to the name myRepo which we refer to from the route
    main.bind("myRepo", repo);
    // add the route and and let the route be named BAR and use a little delay when processing the files
    main.addRouteBuilder(new FileConsumerRoute("BAR", 100));
    main.run();
}
 
Example 25
@Test
void qualifiedAndPrimaryHazelcastInstanceConfiguration() {
	registerAndRefresh(QualifiedAndPrimaryHazelcastInstanceConfiguration.class);

	HazelcastIndexedSessionRepository repository = this.context.getBean(HazelcastIndexedSessionRepository.class);
	HazelcastInstance hazelcastInstance = this.context.getBean("qualifiedHazelcastInstance",
			HazelcastInstance.class);
	assertThat(repository).isNotNull();
	assertThat(hazelcastInstance).isNotNull();
	assertThat(ReflectionTestUtils.getField(repository, "sessions"))
			.isEqualTo(QualifiedAndPrimaryHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions);
}
 
Example 26
public static void main(String[] args){
    Config config = new Config();
    GlobalSerializerConfig globalConfig = new GlobalSerializerConfig();
    globalConfig.setOverrideJavaSerialization(true).setImplementation(new DataSerializer());

    config.getSerializationConfig().setGlobalSerializerConfig(globalConfig);

   HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);

   IMap<String, String> aMap = instance.getMap("aMap");

   aMap.addEntryListener(new MyListener(), true);

   
   aMap.put("key", "value");
   aMap.put("key", "Another value");
   aMap.remove("key");
   aMap.put("other key", "other value");
   aMap.clear();


   IMap<String, Data> otherMap = instance.getMap("otherMap");

   otherMap.addEntryListener(new MyListener(), true);
   otherMap.put("key", new Data());
   Data data = otherMap.get("key");
   data.date=new Date();
   data.value=1000;
   otherMap.put("key",data);

   instance.shutdown();
}
 
Example 27
Source Project: hazelcast-simulator   Source File: HazelcastTestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void waitClusterSize(org.apache.log4j.Logger logger, HazelcastInstance hz, int clusterSize) {
    for (; ; ) {
        if (hz.getCluster().getMembers().size() >= clusterSize) {
            return;
        }

        logger.info("waiting cluster == " + clusterSize);
        sleepSeconds(1);
    }
}
 
Example 28
@Bean
@SpringSessionHazelcastInstance
HazelcastInstance qualifiedHazelcastInstance() {
	HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class);
	given(hazelcastInstance.getMap(anyString())).willReturn(qualifiedHazelcastInstanceSessions);
	return hazelcastInstance;
}
 
Example 29
@Bean
@Primary
HazelcastInstance primaryHazelcastInstance() {
	HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class);
	given(hazelcastInstance.getMap(anyString())).willReturn(primaryHazelcastInstanceSessions);
	return hazelcastInstance;
}
 
Example 30
Source Project: snowcast   Source File: ClientBasicTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_id_generation_in_reattached_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());

        // Detach the node and free the currently used logical node ID
        sequencer.detachLogicalNode();

        try {
            // Must fail since we're in detached state!
            sequencer.next();
            fail();
        } catch (SnowcastStateException e) {
            // Expected, so ignore
        }

        // Re-attach the node and assign a free logical node ID
        sequencer.attachLogicalNode();

        assertNotNull(sequencer.next());
    } finally {
        HazelcastClient.shutdownAll();
        Hazelcast.shutdownAll();
    }
}