Java Code Examples for com.hazelcast.core.Hazelcast#newHazelcastInstance()

The following examples show how to use com.hazelcast.core.Hazelcast#newHazelcastInstance() . 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: ServerBar.java    From camelinaction2 with 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("Bar", 9090));
    } else {
        // route which uses atomic counter
        main.addRouteBuilder(new AtomicCounterRoute("Bar", 9090));
    }
    main.run();
}
 
Example 2
Source File: ClientBasicTestCase.java    From snowcast with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: OperationTest.java    From eventapis with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadWriteExternal() throws Exception {
    HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
    IMap<Object, Object> test = hazelcastInstance.getMap("test");
    test.executeOnKey("123", new EntryProcessor() {
        @Override
        public Object process(Map.Entry entry) {
            entry.setValue("Blabla");
            return entry;
        }

        @Override
        public EntryBackupProcessor getBackupProcessor() {
            return null;
        }
    });

    System.out.println(test.get("123"));


}
 
Example 4
Source File: ServiceNode.java    From hazelcast-demo with 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 5
Source File: DistributedLockFactory.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public static synchronized HazelcastInstance getHazelcastInstance(String instanceName) {
	logger.debug("Getting Hazelcast instance with name [" + instanceName + "]");
	HazelcastInstance hz = Hazelcast.getHazelcastInstanceByName(instanceName);
	if (hz == null) {
		logger.debug("No Hazelcast instance with name [" + instanceName + "] found");
		logger.debug("Creating Hazelcast instance with name [" + instanceName + "]");
		Config config = getDefaultConfig();
		config.setInstanceName(instanceName);
		hz = Hazelcast.newHazelcastInstance(config);
	}
	return hz;
}
 
Example 6
Source File: SubscriptionMain.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 7
Source File: Initializer.java    From spring-session with Apache License 2.0 5 votes vote down vote up
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 8
Source File: HazelcastMQConfig.java    From hazelcastmq with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Hazelcast instance that this MQ will use for all queue and
 * topic operations.
 * 
 * @return the Hazelcast instance
 */
public HazelcastInstance getHazelcastInstance() {
  if (hazelcastInstance == null) {
    hazelcastInstance = Hazelcast.newHazelcastInstance();
  }
  return hazelcastInstance;
}
 
Example 9
Source File: ServerBar.java    From camelinaction2 with 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 10
Source File: CacheConfiguration.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("umm");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("umm");
    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());

    // Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
    config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties));
    config.getMapConfigs().put("com.wyy.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 11
Source File: CacheConfiguration.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("uaa");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("uaa");
    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());

    // Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
    config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties));
    config.getMapConfigs().put("com.wyy.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
 
Example 12
Source File: HazelcastConfigSimple.java    From hazelcast-demo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	// 从classpath加载配置文件
	Config config = new ClasspathXmlConfig("xmlconfig/simple-config.xml");
	// 获取网络配置
	NetworkConfig netConfig = config.getNetworkConfig();
	// 获取用户定义的map配置
	MapConfig mapConfigXml = config.getMapConfig("demo.config");
	// 获取系统默认的map配置
	MapConfig mapConfigDefault = config.getMapConfig("default");
	// 输出集群监听的起始端口号
	System.out.println("Current port:" + netConfig.getPort());
	// 输出监听端口的累加号
	System.out.println("Current port count:" + netConfig.getPortCount());
	// 输出自定义map的备份副本个数
	System.out.println("Config map backup count:" + mapConfigXml.getBackupCount());
	// 输出默认map的备份副本个数
	System.out.println("Default map backup count:" + mapConfigDefault.getBackupCount());

	// 测试创建Hazelcast实例并读写测试数据
	HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
	HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config);

	Map<Integer, String> defaultMap1 = instance1.getMap("defaultMap");
	defaultMap1.put(1, "testMap");
	Map<Integer, String> configMap1 = instance1.getMap("configMap");
	configMap1.put(1, "configMap");

	Map<Integer, String> testMap2 = instance2.getMap("defaultMap");
	System.out.println("Default map value:" + testMap2.get(1));
	Map<Integer, String> configMap2 = instance2.getMap("configMap");
	System.out.println("Config map value:" + configMap2.get(1));
}
 
Example 13
Source File: ClientBasicTestCase.java    From snowcast with 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();
    }
}
 
Example 14
Source File: HazelcastGetStartServerMaster.java    From hazelcast-demo with Apache License 2.0 5 votes vote down vote up
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 15
Source File: ProgrammaticHazelcastClusterManagerTest.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
@Test
public void testThatExternalHZInstanceCanBeShutdown() {
  // This instance won't be used by vert.x
  HazelcastInstance instance = Hazelcast.newHazelcastInstance(createConfig());
  String nodeID = instance.getCluster().getLocalMember().getUuid().toString();

  HazelcastClusterManager mgr = new HazelcastClusterManager(createConfig());
  VertxOptions options = new VertxOptions().setClusterManager(mgr);
  options.getEventBusOptions().setHost("127.0.0.1");

  AtomicReference<Vertx> vertx1 = new AtomicReference<>();

  Vertx.clusteredVertx(options, res -> {
    assertTrue(res.succeeded());
    assertNotNull(mgr.getHazelcastInstance());
    res.result().sharedData().getClusterWideMap("mymap1", ar -> {
      ar.result().put("news", "hello", v -> {
        vertx1.set(res.result());
      });
    });
  });

  assertWaitUntil(() -> vertx1.get() != null);
  int size = mgr.getNodes().size();
  assertTrue(mgr.getNodes().contains(nodeID));

  // Retrieve the value inserted by vert.x
  Map<Object, Object> map = instance.getMap("mymap1");
  Map<Object, Object> anotherMap = instance.getMap("mymap2");
  assertEquals(map.get("news"), "hello");
  map.put("another-key", "stuff");
  anotherMap.put("another-key", "stuff");
  map.remove("news");
  map.remove("another-key");
  anotherMap.remove("another-key");

  instance.shutdown();

  assertWaitUntil(() -> mgr.getNodes().size() == size - 1);
  vertx1.get().close(ar -> vertx1.set(null));

  assertWaitUntil(() -> vertx1.get() == null);
}
 
Example 16
Source File: TestDoNothingRegistrator.java    From hazelcast-consul-discovery-spi with Apache License 2.0 4 votes vote down vote up
public void start() {
	hazelcastInstance = Hazelcast.newHazelcastInstance(conf);
}
 
Example 17
Source File: DistributedObjectProviderTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUpClass() {
    hazelcastInstance = Hazelcast.newHazelcastInstance();
}
 
Example 18
Source File: ProducerConsumerTextOneWay.java    From hazelcastmq with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs the example.
 * 
 * @throws JMSException
 */
public ProducerConsumerTextOneWay() throws JMSException, InterruptedException {

  // Hazelcast Instance.
  Config config = new Config();
  HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(config);

  try {
    // HazelcastMQ Instance
    HazelcastMQConfig mqConfig = new HazelcastMQConfig();
    mqConfig.setHazelcastInstance(hazelcast);

    HazelcastMQInstance mqInstance = HazelcastMQ
        .newHazelcastMQInstance(mqConfig);

    // HazelcastMQJms Instance
    HazelcastMQJmsConfig mqJmsConfig = new HazelcastMQJmsConfig();
    mqJmsConfig.setHazelcastMQInstance(mqInstance);

    HazelcastMQJmsConnectionFactory connectionFactory = new HazelcastMQJmsConnectionFactory(
        mqJmsConfig);

    // Create a connection, session, and destinations.
    Connection connection = connectionFactory.createConnection();
    connection.start();
    Session session = connection.createSession(false,
        Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue("foo.bar");

    // Create a producer and send a message.
    log.info("Sending message.");
    MessageProducer producer = session.createProducer(destination);
    TextMessage msg = session.createTextMessage("Hello World!");
    producer.send(msg);
    producer.close();

    // Create a consumer and receive a message.
    log.info("Receiving message.");
    MessageConsumer consumer = session.createConsumer(destination);
    msg = (TextMessage) consumer.receive(2000);

    Assert.notNull(msg, "Did not get required message.");
    log.info("Got message body: " + msg.getText());

    consumer.close();

    // Cleanup.
    session.close();
    connection.close();

    mqInstance.shutdown();
  }
  finally {
    hazelcast.getLifecycleService().shutdown();
  }
}
 
Example 19
Source File: ProducerRequestReplyReactor.java    From hazelcastmq with Apache License 2.0 4 votes vote down vote up
@Override
protected void start() throws Exception {

  // Create a Hazelcast instance.
  Config config = new Config();
  HazelcastInstance hz = Hazelcast.newHazelcastInstance(config);

  try {
    // Setup the connection factory.
    HazelcastMQConfig mqConfig = new HazelcastMQConfig();
    mqConfig.setHazelcastInstance(hz);
    mqConfig.setExecutor(Executors.newSingleThreadExecutor());
    mqConfig.setContextDispatchStrategy(
        HazelcastMQConfig.ContextDispatchStrategy.REACTOR);

    String requestDest = "/queue/example.dest";

    HazelcastMQInstance mqInstance = HazelcastMQ
        .newHazelcastMQInstance(mqConfig);

    try (HazelcastMQContext mqContext = mqInstance.createContext()) {

      // Create a temporary reply-to queue.
      String replyDest = mqContext.createTemporaryQueue();

      HazelcastMQMessage msg = new HazelcastMQMessage();
      msg.setBody("Do some work and get back to me.");
      msg.setReplyTo(replyDest);
      msg.setCorrelationId(UUID.randomUUID().toString());
      msg.setContentType("text/plain");

      // Send a message with a reply-to header.
      HazelcastMQProducer mqProducer = mqContext.createProducer(requestDest);
      mqProducer.send(msg);

      // Create a consumer on the request destination. Normally this would
      // be done in a different node.
      try (HazelcastMQConsumer mqConsumer =
          mqContext.createConsumer(requestDest)) {

        msg = mqConsumer.receive(2, TimeUnit.SECONDS);
        String rd = msg.getReplyTo();
        String corrId = msg.getCorrelationId();

        log.info("Got message [{}]. Sending reply to [{}].", msg.
            getBodyAsString(), rd);

        // Build the reply message.
        msg = new HazelcastMQMessage();
        msg.setBody("Work is done. You're welcome.");
        msg.setContentType("text/plain");
        msg.setCorrelationId(corrId);

        // Create a producer on the reply destination.
        mqProducer = mqContext.createProducer(rd);
        mqProducer.send(msg);
      }

      // Create a consumer on the reply destination.
      try (HazelcastMQConsumer mqConsumer =
          mqContext.createConsumer(replyDest)) {

        msg = mqConsumer.receive(2, TimeUnit.SECONDS);

        log.info("Got reply message [{}].", msg.getBodyAsString());
      }

      mqContext.stop();
    }
    mqInstance.shutdown();
    mqConfig.getExecutor().shutdown();
  }
  finally {
    hz.getLifecycleService().shutdown();
  }
}
 
Example 20
Source File: ManualRunner.java    From hazelcast-consul-discovery-spi with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	Config conf =new ClasspathXmlConfig("hazelcast-consul-discovery-spi-example.xml");

	HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(conf);
	
	Thread.currentThread().sleep(300000);
	
	System.exit(0);
}