Java Code Examples for com.hazelcast.client.HazelcastClient#newHazelcastClient()

The following examples show how to use com.hazelcast.client.HazelcastClient#newHazelcastClient() . 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 vote down vote up
@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 2
Source File: ConnectDisconnectTest.java    From hazelcast-simulator with Apache License 2.0 6 votes vote down vote up
@TimeStep
public void timestep() throws Exception {
    Thread thread = new Thread(() -> {
        try {
            HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
            client.shutdown();
        } catch (Exception e) {
            ExceptionReporter.report(testContext.getTestId(), e);
        }
    });
    thread.start();
    thread.join(timeoutMillis);
    if (thread.isAlive()) {
        throw new RuntimeException("Connect/Disconnect cycle failed to complete in " + timeoutMillis + " millis");
    }
}
 
Example 3
Source File: HazelcastMemoryService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * 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 vote down vote up
@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 5
Source File: ConnectDisconnectTest.java    From hazelcast-simulator with Apache License 2.0 6 votes vote down vote up
@TimeStep
public void timestep() throws Exception {
    Thread thread = new Thread(() -> {
        try {
            HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
            client.shutdown();
        } catch (Exception e) {
            ExceptionReporter.report(testContext.getTestId(), e);
        }
    });
    thread.start();
    thread.join(timeoutMillis);
    if (thread.isAlive()) {
        throw new RuntimeException("Connect/Disconnect cycle failed to complete in " + timeoutMillis + " millis");
    }
}
 
Example 6
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_detached_state()
        throws Exception {

    Hazelcast.newHazelcastInstance();
    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();

        sequencer.next();
    } finally {
        HazelcastClient.shutdownAll();
        Hazelcast.shutdownAll();
    }
}
 
Example 7
Source File: ClientBasicTestCase.java    From snowcast with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: ClientBasicTestCase.java    From snowcast with Apache License 2.0 6 votes vote down vote up
@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 9
Source File: HazelcastSetup.java    From mercury with Apache License 2.0 5 votes vote down vote up
public static void connectToHazelcast() {
    String topic = getRealTopic();
    if (client != null) {
        client.getLifecycleService().removeLifecycleListener(listenerId);
        client.shutdown();
    }
    String[] address = new String[cluster.size()];
    for (int i=0; i < cluster.size(); i++) {
        address[i] = cluster.get(i);
    }
    ClientConnectionStrategyConfig connectionStrategy = new ClientConnectionStrategyConfig();
    connectionStrategy.setReconnectMode(ClientConnectionStrategyConfig.ReconnectMode.ASYNC);
    ConnectionRetryConfig retry = new ConnectionRetryConfig();
    retry.setClusterConnectTimeoutMillis(MAX_CLUSTER_WAIT);
    connectionStrategy.setConnectionRetryConfig(retry);
    ClientConfig config = new ClientConfig();
    config.getNetworkConfig().addAddress(address);
    config.setConnectionStrategyConfig(connectionStrategy);
    client = HazelcastClient.newHazelcastClient(config);
    client.getCluster().addMembershipListener(new ClusterListener());
    listenerId = client.getLifecycleService().addLifecycleListener(new TopicLifecycleListener(topic));
    if (!isServiceMonitor) {
        try {
            // recover the topic
            PostOffice.getInstance().request(MANAGER, 10000, new Kv(TYPE, TopicManager.CREATE_TOPIC));
        } catch (IOException | TimeoutException | AppException e) {
            log.error("Unable to create topic {} - {}", topic, e.getMessage());
        }
    }
    log.info("Connected to hazelcast cluster and listening to {} ", topic);
}
 
Example 10
Source File: ProducerConsumerHzClient.java    From hazelcastmq with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {

  // Create a Hazelcast instance.
  ClientConfig config = new ClientConfig();
  config.getNetworkConfig().addAddress("localhost:6071");
  HazelcastInstance hz = HazelcastClient.newHazelcastClient(config);

  try {
    // Setup the connection factory.
    HazelcastMQConfig mqConfig = new HazelcastMQConfig();
    mqConfig.setHazelcastInstance(hz);

    HazelcastMQInstance mqInstance = HazelcastMQ
        .newHazelcastMQInstance(mqConfig);

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

      try (HazelcastMQConsumer mqConsumer =
          mqContext.createConsumer("/queue/example.dest")) {

        HazelcastMQMessage msg = mqConsumer.receive(10, TimeUnit.SECONDS);
        if (msg != null) {
          System.out.println("Got message: " + msg.getBodyAsString());
        }
        else {
          System.out.println("Failed to get message.");
        }
      }

      mqContext.stop();
    }
    mqInstance.shutdown();
  }
  finally {
    hz.shutdown();
  }
}
 
Example 11
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 12
Source File: HazelcastCacheConfig.java    From spring4-sandbox with Apache License 2.0 5 votes vote down vote up
@Bean
public HazelcastInstance hazelcastInstance() {
	ClientNetworkConfig networkConfig = new ClientNetworkConfig()
			.addAddress("localhost");
	ClientConfig clientConfig = new ClientConfig();
	clientConfig.setNetworkConfig(networkConfig);
	return HazelcastClient.newHazelcastClient(clientConfig);
}
 
Example 13
Source File: ClientBasicTestCase.java    From snowcast with Apache License 2.0 5 votes vote down vote up
@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 14
Source File: DefaultHazelcastProvider.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
public synchronized HazelcastInstance getHazelcastInstance(final HazelcastConfig configuration) {
    if (hazelcastInstance == null) {
        final String serverName = configuration.getServerName();
        final String serverPort = configuration.getServerPort();
        final String groupName = configuration.getGroupName();

        LOG.debug("Hazelcast server name: {}", serverName);
        LOG.debug("Hazelcast server port: {}", serverPort);
        LOG.debug("Hazelcast group name: {}", groupName);

        final ClientConfig clientConfig = new ClientConfig();
        clientConfig.getNetworkConfig().setConnectionAttemptLimit(configuration.getConnectionAttemptLimit());
        clientConfig.getNetworkConfig().setConnectionAttemptPeriod(configuration.getConnectionAttemptPeriod());
        clientConfig.getNetworkConfig().setConnectionTimeout(configuration.getConnectionTimeout());
        clientConfig.getNetworkConfig().addAddress(serverName + ":" + serverPort);
        clientConfig.getGroupConfig().setName(groupName);
        clientConfig.setProperty(LOGGER_PROPERTY_NAME, LOGGER_PROPERTY_SLF4J_TYPE);

        final SerializerConfig dolphinEventSerializerConfig = new SerializerConfig().
                setImplementation(new EventStreamSerializer()).setTypeClass(DolphinEvent.class);

        clientConfig.getSerializationConfig().getSerializerConfigs().add(dolphinEventSerializerConfig);


        hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig);
    }
    return hazelcastInstance;
}
 
Example 15
Source File: Cluster.java    From OSPREY3 with GNU General Public License v2.0 4 votes vote down vote up
public Client(Parallelism parallelism) {

			this.parallelism = parallelism;

			this.name = String.format("%s-client-%d", Cluster.this.name, nodeId);

			// make a member first, if needed
			if (clientIsMember) {
				member = new Member(parallelism);
			} else {
				member = null;
			}

			// configure the cluster
			ClientConfig cfg = new ClientConfig();
			cfg.setClusterName(id);
			cfg.setInstanceName(name);

			// disable Hazelcast's automatic phone home "feature", which is on by default
			cfg.setProperty("hazelcast.phone.home.enabled", "false");

			log("node looking for cluster named %s ...", id);

			inst = HazelcastClient.newHazelcastClient(cfg);

			log("node started on cluster %s", id);

			activeId = new Value<>(inst, TasksActiveIdName);
			scatter = inst.getQueue(TasksScatterName);
			gather = inst.getQueue(TasksGatherName);

			listener = new Thread(() -> {
				try {
					while (listenerActive.get()) {

						// get the next task result, if any
						TaskResult<?> taskResult = gather.poll(400, TimeUnit.MILLISECONDS);
						if (taskResult != null) {

							// find the task for this result
							TaskAndListener<?,?> tal = tasks.get(taskResult.taskId);
							if (tal == null) {
								log("WARNING: received result for unknown task: %d", taskResult.taskId);
								continue;
							}

							try {

								// handle the task result
								if (taskResult.t != null) {
									taskFailure(tal.task, tal.listener, taskResult.t);
								} else {
									taskSuccessCoerceTypes(tal.task, tal.listener, taskResult.result);
								}

							} finally {
								// clean up the handled task
								tasks.remove(taskResult.taskId);
							}
						}
					}
				} catch (InterruptedException ex) {
					// exit the thread
				} catch (Throwable t) {
					t.printStackTrace(System.err);
				}
			});
			listener.setName("ClusterClientListener");
			listener.setDaemon(true);
			listener.start();
		}
 
Example 16
Source File: HazelcastTestHelper.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
public HazelcastInstance getClient() {
    HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
    LOG.info("Hazelcast client {}", client.getName());

    return client;
}
 
Example 17
Source File: HazelcastLockProviderClusterTest.java    From ShedLock with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void startHazelcast() {
    lockProvider1 = new HazelcastLockProvider(Hazelcast.newHazelcastInstance());
    lockProvider2 = new HazelcastLockProvider(HazelcastClient.newHazelcastClient());
}
 
Example 18
Source File: HazelcastLockProviderClusterTest.java    From ShedLock with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void startHazelcast() {
    lockProvider1 = new HazelcastLockProvider(Hazelcast.newHazelcastInstance());
    lockProvider2 = new HazelcastLockProvider(HazelcastClient.newHazelcastClient());
}
 
Example 19
Source File: HazelcastTest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewHazelcastClientInstance(final MockTracer tracer) {
  final HazelcastInstance instance = HazelcastClient.newHazelcastClient();
  test(instance, tracer);
}
 
Example 20
Source File: InstanceHelper.java    From spring-data-hazelcast with Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * Create a client that can connect to the cluster via the master server {@code 127.0.0.1:5701}. The server will be in
 * the same JVM, but connect via the network.
 * </P>
 *
 * @param name The client's instance name
 * @return A client in a client-server topology.
 */
public static HazelcastInstance makeClient(final String name) {
    ClientConfig clientConfig = new ClientConfig();

    clientConfig.setInstanceName(name);
    clientConfig.getNetworkConfig().setAddresses(Arrays.asList(MASTER_SERVER));

    HazelcastInstance hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig);

    LOG.debug("Created {}", hazelcastInstance);

    return hazelcastInstance;
}