### Get Help for `hz start` Command Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/management/pages/cluster-utilities.adoc Display all available options and usage information for the `hz start` command. This is useful for exploring customization possibilities. ```bash ./hz start -h ``` -------------------------------- ### Start Kafka Broker with Binary Installation Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/sql/pages/learn-sql.adoc Steps to download, extract, and start Kafka and Zookeeper using binary installations. This requires manual management of Kafka and Zookeeper processes. ```shell wget "https://www.apache.org/dyn/closer.lua/kafka/2.7.0/kafka-2.7.0-src.tgz?action=download" tar xvf kafka-2.7.0-src.tgz cd kafka-2.7.0-src ``` ```shell bin/zookeeper-server-start.sh config/zookeeper.properties ``` ```shell bin/kafka-server-start.sh config/server.properties ``` -------------------------------- ### Run Go Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/go-client-getting-started.adoc Execute the Go script to start the Hazelcast client and connect to the cluster. ```bash go run example.go ``` -------------------------------- ### Hazelcast C++ Client Setup and Operations Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cpp-client-getting-started.adoc This example demonstrates the complete setup for the Hazelcast C++ client, including cloud configuration, SSL setup, and basic operations like creating mappings, inserting city data, and fetching it. ```cpp #include #include void create_mapping(hazelcast::client::hazelcast_client client); void insert_cities(hazelcast::client::hazelcast_client client); void fetch_cities(hazelcast::client::hazelcast_client client); struct CityDTO { std::string cityName; std::string country; int population; }; // CityDTO serializer namespace hazelcast { namespace client { namespace serialization { template<> struct hz_serializer : compact::compact_serializer { static void write(const CityDTO& object, compact::compact_writer& out) { out.write_int32("population", object.population); out.write_string("city", object.cityName); out.write_string("country", object.country); } static CityDTO read(compact::compact_reader& in) { CityDTO c; c.population = in.read_int32("population"); boost::optional city = in.read_string("city"); if (city) { c.cityName = *city; } boost::optional country = in.read_string("country"); if (country) { c.country = *country; } return c; } static std::string type_name() { return "CityDTO"; } }; } // namespace serialization } // namespace client } // namespace hazelcast int main(int argc, char** argv) { hazelcast::client::client_config config; // Cluster Name and Token config.set_cluster_name(""); auto& cloud_configuration = config.get_network_config().get_cloud_config(); cloud_configuration.enabled = true; cloud_configuration.discovery_token = ""; // configure SSL boost::asio::ssl::context ctx(boost::asio::ssl::context::tlsv12); try { ctx.load_verify_file("ca.pem"); ctx.use_certificate_file("cert.pem", boost::asio::ssl::context::pem); ctx.set_password_callback( [&](std::size_t max_length, boost::asio::ssl::context::password_purpose purpose) { return ""; }); ctx.use_private_key_file("key.pem", boost::asio::ssl::context::pem); } catch (std::exception& e) { std::cerr << "You should copy ca.pem, cert.pem and key.pem files to " "the working directory, exception cause " << e.what() << std::endl; exit(EXIT_FAILURE); } config.get_network_config().get_ssl_config().set_context(std::move(ctx)); // Connect to your Hazelcast Cluster auto client = hazelcast::new_client(std::move(config)).get(); // take actions create_mapping(client); insert_cities(client); fetch_cities(client); // Shutdown the client connection client.shutdown().get(); } void create_mapping(hazelcast::client::hazelcast_client client) { // Mapping is required for your distributed map to be queried over SQL. // See: https://docs.hazelcast.com/hazelcast/latest/sql/mapping-to-maps std::cout << "Creating the mapping..."; auto sql = client.get_sql(); auto result = sql .execute(R"(CREATE OR REPLACE MAPPING cities ( __key INT, country VARCHAR, city VARCHAR, population INT) TYPE IMAP OPTIONS ( 'keyFormat' = 'int', 'valueFormat' = 'compact', 'valueCompactTypeName' = 'CityDTO'))") .get(); std::cout << "OK." << std::endl; } void insert_cities(hazelcast::client::hazelcast_client client) { auto sql = client.get_sql(); try { sql.execute("DELETE FROM cities").get(); std::cout << "Inserting data..."; // Create mapping for the integers. This needs to be done only once per // map. auto result = sql .execute(R"(INSERT INTO cities (__key, city, country, population) VALUES (1, 'London', 'United Kingdom', 9540576), (2, 'Manchester', 'United Kingdom', 2770434), (3, 'New York', 'United States', 19223191), (4, 'Los Angeles', 'United States', 3985520), (5, 'Istanbul', 'Türkiye', 15636243), (6, 'Ankara', 'Türkiye', 5309690), (7, 'Sao Paulo ', 'Brazil', 22429800))") .get(); std::cout << "OK." << std::endl; } catch (hazelcast::client::exception::iexception& e) { // don't panic for duplicated keys. ``` -------------------------------- ### Sample Go Client Usage Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/go.adoc Example demonstrating how to create a client, connect to a cluster, get and populate a map, and retrieve data. ```go package main import ( "context" "fmt" "log" "github.com/hazelcast/hazelcast-go-client" ) func main() { ctx := context.TODO() // create the client and connect to the cluster on localhost client, err := hazelcast.StartNewClient(ctx) if err != nil { log.Fatal(err) } // get a map people, err := client.GetMap(ctx, "people") if err != nil { log.Fatal(err) } personName := "Jane Doe" // set a value in the map if err = people.Set(ctx, personName, 30); err != nil { log.Fatal(err) } // get a value from the map age, err := people.Get(ctx, personName) if err != nil { log.Fatal(err) } fmt.Printf("%s is %d years old.\n", personName, age) // stop the client to release resources client.Shutdown(ctx) } ``` -------------------------------- ### Install Hazelcast Go Client Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/list.adoc Installs the Hazelcast Go client library using go get. This command fetches and installs the necessary package for Go development. ```shell go get github.com/hazelcast/hazelcast-go-client ``` -------------------------------- ### Configure and Start Go Client with Credentials Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/authenticate-client-tutorial.adoc Use this code to start a Go client and authenticate with a Hazelcast cluster using username and password credentials. Ensure the Hazelcast Go client library is installed. ```go package main import ( "context" "github.com/hazelcast/hazelcast-go-client" ) func main() { ctx := context.TODO() config := hazelcast.Config{} cc := &config.Cluster cc.Network.SetAddresses("127.0.0.1:5701") cc.Name = "hello-world" creds := &cc.Security.Credentials creds.Username = "member1" creds.Password = "s3crEtPassword*" client, err := hazelcast.StartNewClientWithConfig(ctx, config) if err != nil { panic(err) } client.Shutdown(ctx) } ``` -------------------------------- ### Basic Hazelcast Client Initialization (C++) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cplusplus.adoc Initialize and connect a Hazelcast C++ client to a cluster. This example demonstrates the minimal setup required to start a client instance. ```c++ #include int main() { auto hz = hazelcast::new_client().get(); // Connects to the cluster std::cout << "Started the Hazelcast C++ client instance " << hz.get_name() << std::endl; // Prints client instance name hz.shutdown().get(); return 0; } ``` -------------------------------- ### Configure and Start C# Client with Credentials Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/authenticate-client-tutorial.adoc Use this C# code to set up and start an authenticated Hazelcast client with username and password. Ensure the Hazelcast C# client library is installed. ```cs var username = "member1"; var password = "s3crEtPassword*"; var options = new HazelcastOptionsBuilder(); .With(o => { o.Authentication.ConfigureUsernamePasswordCredentials(username, password); }) .Build(); var client = await HazelcastClientFactory.StartNewClientAsync(options); ``` -------------------------------- ### Start Hazelcast Member Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-binary.adoc Navigate to your Hazelcast installation directory and run this script to start a new Hazelcast member. This command is cross-platform. ```shell cd hazelcast-{full-version} bin/hz-start ``` -------------------------------- ### Install godoc Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/go.adoc Install godoc using the go get command. This is not included by default. ```bash go get -u golang.org/x/tools/... ``` -------------------------------- ### Complete SQL API Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-java.adoc This is a complete Java program demonstrating the setup of Hazelcast instances and interaction with data using the SQL API. It includes necessary imports, configuration, and SQL execution logic. ```java package org.example; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.sql.SqlResult; import com.hazelcast.sql.SqlRow; import com.hazelcast.sql.SqlService; import java.util.Arrays; import java.util.List; public class HelloWorld { public static void main(String[] args) { Config helloWorldConfig = new Config(); ``` -------------------------------- ### Configure and Start C++ Client with Credentials Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/authenticate-client-tutorial.adoc This C++ code snippet demonstrates how to configure and start an authenticated Hazelcast client using username and password. Ensure the Hazelcast C++ client library is installed. ```cpp hazelcast::client::client_config clientConfig; clientConfig.set_credentials( std::make_shared("member1", "s3crEtPassword*")); clientConfig.set_cluster_name("hello-world"); auto hz = hazelcast::new_client(std::move(clientConfig)).get(); ``` -------------------------------- ### Start Hazelcast Enterprise Node Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/wan/pages/wan-replication-tutorial.adoc Starts a Hazelcast Enterprise node with a specific configuration file mounted. Ensure the configuration path is correct for your setup. ```shell docker run -e JAVA_OPTS="-Dhazelcast.config=/opt/hazelcast/config_ext/hazelcast.yaml" -v ~/config-tokyo:/opt/hazelcast/config_ext hazelcast/hazelcast-enterprise:{ee-version} ``` -------------------------------- ### Install Hazelcast Go Client Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-docker.adoc Install the Go client library for Hazelcast. ```shell go get github.com/hazelcast/hazelcast-go-client ``` ```go package main import ( "context" "fmt" "log" "github.com/hazelcast/hazelcast-go-client" ) func main() { ctx := context.TODO() cfg := hazelcast.Config{} cfg.Cluster.Name = "hello-world" <1> hz, err := hazelcast.StartNewClientWithConfig(ctx, cfg) <2> if err != nil { panic(fmt.Errorf("starting the client with config: %w", err)) } mp, err := hz.GetMap(ctx, "my-distributed-map") <3> if err != nil { panic(fmt.Errorf("trying to get a map: %w", err)) } <4> _, err = mp.Put(ctx, 1, "John") if err != nil { panic(fmt.Errorf("trying to put to map: %w", err)) } _, err = mp.Put(ctx, 2, "Mary") if err != nil { panic(fmt.Errorf("trying to put to map: %w", err)) } _, err = mp.Put(ctx, 3, "Jane") if err != nil { panic(fmt.Errorf("trying to put to map: %w", err)) } } ``` -------------------------------- ### Basic JCache Application Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/jcache/pages/setup.adoc Demonstrates a basic JCache application using Hazelcast. It shows how to retrieve the CachingProvider, get a CacheManager, configure a cache with typesafe key-value pairs, create the cache, and perform basic put and get operations. ```java CachingProvider cachingProvider = Caching.getCachingManager(); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); config.setTypes(String.class, String.class); Cache cache = cacheManager.createCache("myCache", config); cache.put("key1", "value1"); String value = cache.get("key1"); String oldValue = cache.getAndPut("key2", "value2"); ``` -------------------------------- ### Configure and Start Java Client with Credentials Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/authenticate-client-tutorial.adoc This Java code snippet shows how to create and start an authenticated Hazelcast client using username and password. Make sure the Hazelcast Java client library is installed. ```java import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; public class SecuredClient { public static void main(String[] args) { ClientConfig clientConfig = new ClientConfig(); clientConfig.setClusterName("hello-world"); clientConfig.getSecurityConfig().setUsernamePasswordIdentityConfig("member1","s3crEtPassword*"); HazelcastClient.newHazelcastClient(clientConfig); } } ``` -------------------------------- ### Build and Run Vert.x Project Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/integrate/pages/get-started-with-vertx.adoc Builds a Vert.x project using Maven and starts the application. Ensure Java and Maven are installed. ```bash $ mvn clean package ``` ```bash java -jar target/messages-1.0.0-SNAPSHOT-fat.jar ``` -------------------------------- ### Complete Map API Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-java.adoc This is a complete Java program demonstrating the setup of Hazelcast instances and interaction with a distributed map using the Map API. It includes necessary imports and configuration. ```java package org.example; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import java.util.Map; public class HelloWorld { public static void main(String[] args) { Config helloWorldConfig = new Config(); helloWorldConfig.setClusterName("hello-world"); HazelcastInstance hz = Hazelcast.newHazelcastInstance(helloWorldConfig); HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(helloWorldConfig); HazelcastInstance hz3 = Hazelcast.newHazelcastInstance(helloWorldConfig); Map map = hz.getMap("my-distributed-map"); map.put("1", "John"); map.put("2", "Mary"); map.put("3", "Jane"); System.out.println(map.get("1")); System.out.println(map.get("2")); System.out.println(map.get("3")); } } ``` -------------------------------- ### Start Hazelcast Server Distribution Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cplusplus.adoc Start a Hazelcast member from a downloaded distribution. Navigate to the bin directory and use the appropriate start script. ```bash hz start ``` -------------------------------- ### Basic List Operations (Python) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/list.adoc Shows how to create a list, add items, retrieve size and elements, check for containment, get a sublist, and remove items. Requires the Hazelcast client to be installed and running. ```python import hazelcast client = hazelcast.HazelcastClient() my_list = client.get_list("list") my_list.add("Tokyo") my_list.add("Paris") my_list.add("London") my_list.add("New York") my_list.add("Istanbul") print("List size: {}".format(my_list.size().result())) print("First element: {}".format(my_list.get(0).result())) print("Contains London: {}".format(my_list.contains("London").result())) print("Sublist: {}".format(my_list.sub_list(3, 4).result())) my_list.remove("Tokyo") print("Final size: {}".format(my_list.size().result())) client.shutdown() ``` -------------------------------- ### Client YAML Configuration Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/java.adoc Example of a basic Hazelcast client configuration in YAML format. ```yaml hazelcast-client: cluster-name: cluster-a network: cluster-members: - production1.myproject - production2.myproject ``` -------------------------------- ### Build and Install Hazelcast C++ Client (Windows) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cplusplus.adoc Build and install the client library using CMake, specifying the 'Release' configuration. Ensure the same configuration is used for both build and install commands. ```bat cmake --build . --config Release cmake --build . --target install --config Release ``` -------------------------------- ### Create and Populate MultiMap in Java Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/multimap.adoc Demonstrates how to get a MultiMap instance by name, add multiple values for the same key, and then iterate through the keys to print their associated values. Ensure the Hazelcast Java client library is installed. ```java import com.hazelcast.client.HazelcastClient; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.multimap.MultiMap; import java.util.Collection; public class Client { public static void main(String[] args) throws Exception { HazelcastInstance client = HazelcastClient.newHazelcastClient(); MultiMap multimap = client.getMultiMap("multimap"); multimap.put("a", "1"); multimap.put("a", "2"); multimap.put("b", "3"); System.out.printf("Put items:Done"); for (String key: multimap.keySet()){ Collection values = multimap.get(key); System.out.printf("%s -> %s\n", key, values); } } } ``` -------------------------------- ### Start Tutorial Environment Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/vector-search-tutorial.adoc Launches Hazelcast Platform, Management Center, and the Web server using Docker Compose. Access Management Center at http://localhost:8080. ```sh docker compose up -d ``` -------------------------------- ### Create and Add Items to a Set (Node.js) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/set.adoc Illustrates how to get a Hazelcast Set and add string elements using the Node.js client. The example also shows how to retrieve the size of the set. Make sure to install the Node.js client library. ```javascript 'use strict'; const { Client } = require('hazelcast-client'); (async () => { try { const client = await Client.newHazelcastClient(); const set = await client.getSet('my-distributed-set'); await set.add('Tokyo'); await set.add('Paris'); await set.add('London'); await set.add('New York'); const size = await set.size(); console.log('Set size:', size); await client.shutdown(); } catch (err) { console.error('Error occurred:', err); process.exit(1); } })(); ``` -------------------------------- ### Create and Add Items to a Set (C#) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/set.adoc Demonstrates creating a Hazelcast Set and adding string elements using the C# client. Includes examples of checking for containment and retrieving the set size. Ensure the C# client library is installed. ```cs using System; using System.Threading.Tasks; namespace Hazelcast.Examples.DistributedObjects { public class SetExample { public static async Task Main(string[] args) { var options = new HazelcastOptionsBuilder() .With(args) .WithConsoleLogger() .Build(); await using var client = await HazelcastClientFactory.StartNewClientAsync(options); await using var set = await client.GetSetAsync("set"); await set.AddAsync("Tokyo"); await set.AddAsync("Paris"); await set.AddAsync("London"); await set.AddAsync("New York"); Console.WriteLine("All: " + string.Join(", ", await set.GetAllAsync())); Console.WriteLine("Contains: " + await set.ContainsAsync("Paris")); Console.WriteLine("Count: " + await set.GetSizeAsync()); await client.DestroyAsync(set); } } } ``` -------------------------------- ### Create Project Directory and Navigate Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/python-client-getting-started.adoc Create a new directory for your Hazelcast Python example and navigate into it. ```bash mkdir hazelcast-python-example cd hazelcast-python-example ``` -------------------------------- ### Build and Run Sample Project (Windows) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cplusplus.adoc Instructions for building and running the C++ client sample project on Windows using CMake and vcpkg. ```bat cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=[path to vcpkg]\scripts\buildsystems\vcpkg.cmake && \ cmake --build build && \ .\build\Debug\client ``` -------------------------------- ### Publisher Example for Reliable Topic Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/reliable-topic.adoc Example of a publisher using the Reliable Topic API. Ensure necessary imports and Hazelcast instance setup. ```java import com.hazelcast.topic.ITopic; import com.hazelcast.core.HazelcastInstance; public class PublisherMember { public void publish(HazelcastInstance hz) { ITopic topic = hz.getTopic("my-reliable-topic"); topic.publish("Hello Reliable World!"); } } ``` -------------------------------- ### Basic List Operations (Go) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/list.adoc Demonstrates initializing the Hazelcast client, getting a list, adding items, and retrieving the list size. Ensure the Hazelcast server is running. ```go package main import ( "context" "fmt" "log" "math/rand" "time" "github.com/hazelcast/hazelcast-go-client" ) func main() { ctx := context.TODO() client, err := hazelcast.StartNewClient(ctx) if err != nil { log.Fatal(err) } rand.Seed(time.Now().Unix()) listName := fmt.Sprintf("sample-%d", rand.Int()) list, err := client.GetList(ctx, listName) if err != nil { log.Fatal(err) } size, err := list.Size(ctx) if err != nil { log.Fatal(err) } fmt.Println(size) list.Add(ctx, "Tokyo") list.Add(ctx, "Paris") list.Add(ctx, "London") list.Add(ctx, "New York") size, err = list.Size(ctx) if err != nil { log.Fatal(err) } fmt.Println(size) // Shutdown client client.Shutdown(ctx) } ``` -------------------------------- ### Build and Run Sample Project (Linux/Mac) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cplusplus.adoc Instructions for building and running the C++ client sample project on Linux or macOS using CMake and vcpkg. ```sh cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=[path to vcpkg]/scripts/buildsystems/vcpkg.cmake cmake --build build ./build/client ``` -------------------------------- ### Start Client with Custom Configuration Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/go.adoc Start the client with custom configuration, optionally setting member addresses manually. ```go config := hazelcast.Config{} config.Cluster.Network.SetAddresses("member1.example.com:5701", "member2.example.com:5701") client, err := hazelcast.StartNewClientWithConfig(ctx, config) ``` -------------------------------- ### Example cURL Request to Cluster Endpoint Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-rest-api-with-java.adoc This example demonstrates how to make a GET request to the cluster endpoint using cURL, including the necessary Authorization header for authentication. ```shell curl -X 'GET' \ 'http://localhost:8443/hazelcast/rest/api/v1/cluster' \ -H 'Authorization: Bearer ' ``` -------------------------------- ### Install and Connect to Hazelcast in Go Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-binary.adoc Install the Go client library and use it to connect to a Hazelcast cluster, then write data to a distributed map. Error handling is omitted for brevity. ```shell go get github.com/hazelcast/hazelcast-go-client ``` ```go import ( "context" "github.com/hazelcast/hazelcast-go-client" ) func mapSampleRun() { // error handling is omitted for brevity config := hazelcast.Config{} config.Cluster.Name = "hello-world" <1> ctx := context.TODO() client, _ := hazelcast.StartNewClientWithConfig(ctx, config) <2> mp, _ := client.GetMap(ctx, "my-distributed-map") <3> <4> mp.Put(ctx, "1", "John") mp.Put(ctx, "2", "Mary") mp.Put(ctx, "3", "Jane") } ``` -------------------------------- ### OpenSSL TLS Configuration Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/security/pages/integrating-openssl.adoc Configure TLS settings for OpenSSL integration, specifying protocol and trust certificate file. This example demonstrates basic TLS setup. ```yaml protocol: TLSv1.2 trustCertCollectionFile: trusted-certs.pem ``` -------------------------------- ### Configure and Start Node.js Client with Credentials Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/authenticate-client-tutorial.adoc This Node.js script shows how to configure and start an authenticated Hazelcast client using username and password. Install the 'hazelcast-client' npm package before running. ```javascript const config = { security: { usernamePassword: { username: 'member1', password: 's3crEtPassword*' } } }; const client = await Client.newHazelcastClient(cfg); ``` -------------------------------- ### Start Hazelcast Go Client and Connect Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/go-client-getting-started.adoc This code snippet initializes and starts a Hazelcast client, connecting to a Hazelcast Cloud cluster using provided credentials and keystore files. It prints a welcome message and ensures the client is shut down gracefully. ```go package main import ( "context" "fmt" "github.com/hazelcast/hazelcast-go-client" ) func main() { // Connection details for cluster config := hazelcast.Config{} config.Cluster.Name = "" config.Cluster.Cloud.Enabled = true config.Cluster.Cloud.Token = "" config.Cluster.Network.SSL.SetCAPath("ca.pem") config.Cluster.Network.SSL.AddClientCertAndEncryptedKeyPath("cert.pem", "key.pem", "") // create the client and connect to the cluster client, err := hazelcast.StartNewClientWithConfig(context.TODO(), config) // error checking is omitted for brevity fmt.Println("Welcome to your Hazelcast Cluster!") defer client.Shutdown(context.TODO()) if err != nil { panic(err) } } ``` -------------------------------- ### Basic .NET Client Usage Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/dotnet.adoc A minimal example demonstrating how to create a .NET client instance, connect to a Hazelcast server, and perform basic map operations. ```csharp using System.Threading.Tasks; using Hazelcast; class Program { public static async Task Main() { // Create default options and connect to a Hazelcast server running on localhost var options = new HazelcastOptionsBuilder().Build(); await using var client = await HazelcastClientFactory.StartNewClientAsync(options); // Use the client (e.g., get a distributed map) var map = await client.GetMapAsync("my-distributed-map"); await map.SetAsync("key", "value"); var value = await map.GetAsync("key"); System.Console.WriteLine($"Value for 'key': {value}"); // Dispose the client when done await client.DisposeAsync(); } } ``` -------------------------------- ### Start Management Center (Binary) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/pipelines/pages/stream-processing-client.adoc Instructions for starting the Management Center from its binary distribution on Mac/Linux and Windows. ```shell management-center/bin/start.sh ``` ```shell management-center/bin/start.bat ``` -------------------------------- ### Build Hazelcast C++ Client with Tests and Examples Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cplusplus.adoc Build the project with tests and examples enabled, including OpenSSL support and verbose Makefiles. Specify the vcpkg toolchain and manifest features. ```bash cmake -b build \ -DBUILD_TESTS=ON \ -DBUILD_EXAMPLES=ON \ -DWITH_OPENSSL=ON \ -DCMAKE_VERBOSE_MAKEFILE=ON \ -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake \ -DVCPKG_MANIFEST_FEATURES='build-tests' \ cmake --build build ``` -------------------------------- ### Passive Cluster Confirmation Log Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/wan/pages/wan-replication-tutorial.adoc This is an example of the confirmation log output when the passive cluster starts successfully. ```shell 2024-11-23 11:08:15,055 [ INFO] [main] [c.h.i.c.ClusterService]: [host.docker.internal]:5701 [London] [{ee-version}] Members {size:1, ver:1} [ Member [host.docker.internal]:5701 - bed20746-1505-449b-9f4a-548bcdbe12b8 this ] ``` -------------------------------- ### Create a Job Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/sql/pages/create-job.adoc This example demonstrates how to create a job named 'myJob' with specific processing guarantees and snapshot intervals, inserting data into 'myMap' from 'my_source'. ```sql CREATE JOB myJob OPTIONS ( 'processingGuarantee' = 'exactlyOnce', 'snapshotIntervalMillis' = '5000', ) AS INSERT INTO myMap SELECT * FROM my_source ``` -------------------------------- ### Start third Hazelcast Enterprise member Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-enterprise.adoc Start a third Hazelcast Enterprise member, similar to the second, by incrementing the public port and mapping a distinct local persistence directory. This completes the three-member cluster setup. ```shell docker run \ --name third-member --network hazelcast-network \ --rm \ -e HZ_NETWORK_PUBLICADDRESS=host.docker.internal:5703 \ -e HZ_CLUSTERNAME=hello-world \ -e HZ_LICENSEKEY= \ -e HZ_PERSISTENCE_ENABLED=true \ -e HZ_MAP_MYDISTRIBUTEDMAP_DATAPERSISTENCE_ENABLED=true \ -v ~/persist3:/opt/hazelcast/persistence \ -p 5703:5701 hazelcast/hazelcast-enterprise:{ee-version} ``` -------------------------------- ### Hazelcast Cluster Setup and SQL Operations in Java Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-java.adoc Demonstrates setting up a Hazelcast cluster, enabling Jet, creating an SQL mapping, inserting data, and querying it. Ensure Hazelcast is properly configured and dependencies are included. ```java helloWorldConfig.setClusterName("hello-world"); JetConfig jetConfig = helloWorldConfig.getJetConfig(); jetConfig.setEnabled(true); HazelcastInstance hz = Hazelcast.newHazelcastInstance(helloWorldConfig); HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(helloWorldConfig); HazelcastInstance hz3 = Hazelcast.newHazelcastInstance(helloWorldConfig); SqlService sql = hz.getSql(); String createMappingQuery = "CREATE MAPPING myDistributedMap\n" + "TYPE IMap\n" + "OPTIONS ('keyFormat'='varchar','valueFormat'='varchar')"; sql.execute(createMappingQuery); List insertionQueries = Arrays.asList( "SINK INTO myDistributedMap VALUES('1', 'John')", "SINK INTO myDistributedMap VALUES('2', 'Mary')", "SINK INTO myDistributedMap VALUES('3', 'Jane')" ); for (String insertionQuery : insertionQueries) { sql.execute(insertionQuery); } String scanQuery = "SELECT * FROM myDistributedMap"; try (SqlResult result = sql.execute(scanQuery)) { int columnCount = result.getRowMetadata().getColumnCount(); for (SqlRow row : result) { for (int colIdx = 0; colIdx < columnCount; colIdx++) { System.out.print(row.getObject(colIdx) + " "); } System.out.println(); } } } ``` -------------------------------- ### Create Project Directory Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/cpp-client-getting-started.adoc Create a new directory for your Hazelcast C++ example project and navigate into it. Avoid directory names with spaces or special characters. ```bash mkdir hazelcast-cpp-example cd hazelcast-cpp-example ``` -------------------------------- ### Vert.x MainVerticle Start Method Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/integrate/pages/get-started-with-vertx.adoc Configures a Vert.x router, sets up local session storage, and defines routes for handling HTTP requests. Uses 2-space indentation. ```java public void start() { // Create a Router Router router = router(vertx); // Create local SessionStore SessionStore store = LocalSessionStore.create(vertx); // Use the SessionStore to handle all requests router.route() .handler(SessionHandler.create(store)); router.route(HttpMethod.PUT, "/").handler(context -> { context.request().bodyHandler(body -> { List messages = getMessagesFromSession(context); JsonObject json = body.toJsonObject(); String message = json.getString("message"); messages.add(message); putMessagesToSession(context, messages); context.json( new JsonObject() .put("messages", messages) ); }); }); // Create the HTTP server vertx.createHttpServer() // Handle every request using the router .requestHandler(router) // Start listening .listen(8888) // Print the port .onSuccess(server -> System.out.println( "HTTP server started on port " + server.actualPort() ) ); } private static List getMessagesFromSession(RoutingContext context) { String messages = context.session().get("messages"); if (messages == null) { return new ArrayList<>(); } else { return new ArrayList<>(Arrays.asList(messages.split(","))); } } private void putMessagesToSession(RoutingContext context, List messages) { context.session().put("messages", String.join(",", messages)); } ``` -------------------------------- ### PHP Memcache Client Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/memcache.adoc Connect to a Hazelcast member using the PHP Memcache client and perform basic set and get operations. ```php connect( '10.20.17.1', 5701 ) or die ( "Could not connect" ); $memcache->set( 'key1', 'value1', 0, 3600 ); $get_result = $memcache->get( 'key1' ); // retrieve your data var_dump( $get_result ); // show it ?> ``` -------------------------------- ### Start Hazelcast SQL Shell Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/getting-started/pages/get-started-enterprise.adoc Launches the Hazelcast SQL shell to interact with the cluster. Ensure the network and cluster name match your setup. ```shell docker run --network hazelcast-network -it --rm hazelcast/hazelcast-enterprise:{ee-version} hz-cli --targets hello-world@host.docker.internal sql ``` -------------------------------- ### Start Default Client Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/go.adoc Start the client with default Hazelcast host and port when Hazelcast is running locally. ```go ctx := context.TODO() client, err := hazelcast.StartNewClient(ctx) ``` -------------------------------- ### Example Trial License Key Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/deploy/pages/enterprise-licenses.adoc A sample trial license key format obtained from the Hazelcast website. Replace placeholders with your actual license key in code examples. ```shell TrialLicense#10Nodes#eyJhbGxvd2VkTmF0aXZlTWVtb3J5U2l6ZSI6MTAwLCJhbGxvd2VkTnVtYmVyT2ZOb2RlcyI6MTAsImFsbG93ZWRUaWVyZWRTdG9yZVNpemUiOjAsImFsbG93ZWRUcGNDb3JlcyI6MCwiY3JlYXRpb25EYXRlIjoxNzUyMTU0ODYzLjMxODUyNzg2MSwiZXhwaXJ5RGF0ZSI6MTc1NDY5NzU5OS45OTk5OTk5OTksImZlYXR1cmVzIjpbMCwyLDMsNCw1LDYsNyw4LDEwLDExLDE1LDE3LDIxLDIyXSwiZ3JhY2VQZXJpb2QiOjAsImhhemVsY2FzdFZlcnNpb24iOjk5LCJvZW0iOmZhbHNlLCJ0cmlhbCI6dHJ1ZSwidmVyc2lvbiI6IlY3In0=.enSTWffnYK_rBdTC7LOVISPYYaEfwdM7giv8ZBH4iq2b5vHuA5U-OswteJUmF8jHXyyo9j0oKBWkvgxe6PBKAQ== ``` -------------------------------- ### Example Warning for Non-Enforced Policy Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/security/pages/validating-secrets.adoc Illustrates the warning message displayed when a weak secret is detected and the policy is not enforced. Cluster members will still start. ```log @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ SECURITY WARNING @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ SSLConfig property[keyStorePassword] does not meet the current policy and complexity requirements. *Must contain 8 or more characters. *Must have at least 1 lower and 1 upper case characters. *Must have at least 1 alphabetic character. *Must contain at least 1 special character. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ``` -------------------------------- ### Configure REST API TLS/HTTPS (Java) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/maintain-cluster/pages/enterprise-rest-api.adoc Configure TLS/HTTPS settings for the REST API programmatically using Java. This example shows the start of the configuration. ```java Config config = new Config() .setRestConfig( new RestConfig() ``` -------------------------------- ### Install Hazelcast with Helm Chart Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/kubernetes/pages/deploying-in-kubernetes.adoc Deploys Hazelcast using the official Helm chart. This is a quick way to get a Hazelcast cluster running on Kubernetes. ```bash helm repo add hazelcast https://hazelcast-charts.s3.amazonaws.com/ helm repo update helm install hazelcast hazelcast/hazelcast ``` -------------------------------- ### Create Hazelcast Go Project Directory Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/clients/pages/go-client-getting-started.adoc Create a new directory for your Go project and navigate into it. ```bash mkdir hazelcast-go-example cd hazelcast-go-example ``` -------------------------------- ### Create Hazelcast Instances for Testing Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/test/pages/testing-setup.adoc Example of creating Hazelcast instances using `HazelcastTestSupport` for testing purposes. This setup uses mock networking by default. ```java Config config = HazelcastTestSupport.regularInstanceConfig(); // setup config int clusterSize = 2; TestHazelcastFactory factory = new TestHazelcastFactory(clusterSize); HazelcastInstance[] members = factory.newInstances(config, clusterSize); // ... factory.shutdownAll(); // or for each member: members[i].shutdown(); ``` -------------------------------- ### Start Hazelcast Member with Default Settings Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/management/pages/cluster-utilities.adoc Use this command to start a Hazelcast member using default configuration. Navigate to the `bin` directory first. ```bash ./hz start ``` -------------------------------- ### Java: Set Configuration Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/set.adoc Shows a Java code snippet for configuring a Hazelcast Set, including settings for backups, size, and listeners. ```java include::ROOT:example$/dds/set/SetConfiguration.java[tag=sc] ``` -------------------------------- ### Consume Items from Queue (Python) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/queue.adoc Accesses a distributed queue and starts consuming messages. This example uses a thread for consumption and has a limit on the number of items to consume. ```python import hazelcast import threading client = hazelcast.HazelcastClient() queue = client.get_queue("queue") <1> def consume(): consumed_count = 0 while consumed_count < 100: <2> head = queue.take().result() print("Consuming {}".format(head)) consumed_count += 1 consumer_thread = threading.Thread(target=consume) consumer_thread.start() consumer_thread.join() client.shutdown() ``` -------------------------------- ### YAML: Set Configuration Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/set.adoc Demonstrates configuring a Hazelcast Set using YAML, specifying parameters like statistics, backups, and maximum size. ```yaml hazelcast: set: default: statistics-enabled: false backup-count: 1 async-backup-count: 0 max-size: 10 item-listeners: - class-name: com.hazelcast.examples.ItemListener split-brain-protection-ref: splitbrainprotection-name ``` -------------------------------- ### Consume Items from Queue (C#) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/queue.adoc Accesses a distributed queue and starts consuming messages. This example demonstrates polling for messages and has a limit on the number of consumed items. ```cs using System; using System.Threading.Tasks; namespace Hazelcast.Examples.DistributedObjects { public class QueueExample { public static async Task Main(string[] args) { var options = new HazelcastOptionsBuilder() .With(args) .WithConsoleLogger() .Build(); await using var client = await HazelcastClientFactory.StartNewClientAsync(options); await using var queue = await client.GetQueueAsync("queue"); <1> var consumer = Task.Run(async () => { var nConsumed = 0; string e; while (nConsumed++ < 100 && (e = await queue.PollAsync()) != null) <2> { Console.WriteLine("Consuming " + e); } Console.WriteLine("consumed"); }); await Task.WhenAll(producer, consumer); await client.DestroyAsync(queue); } } } ``` -------------------------------- ### Starting Hazelcast Member Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/configuration/pages/configuring-declaratively.adoc This command starts a Hazelcast member using the default configuration file 'hazelcast.xml' from the working directory. ```bash java -jar hazelcast-*.jar ``` -------------------------------- ### Read Batched Items from Ringbuffer (No Filter) Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/data-structures/pages/ringbuffer.adoc Read a batch of items from the Ringbuffer starting from the head sequence. This example demonstrates reading without applying a filter. ```java long sequence = rb.headSequence(); for(;;) { CompletionStage> f = rb.readManyAsync(sequence, 1, 10, null); CompletionStage readCountStage = f.thenApplyAsync(rs -> { for (String s : rs) { System.out.println(s); } return rs.readCount(); }); sequence += readCountStage.toCompletableFuture().join(); } ``` -------------------------------- ### Full Persistence Configuration Example Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/storage/pages/configuring-persistence.adoc A comprehensive example demonstrating persistence configuration for the entire Hazelcast instance, including base directory, backup directory, timeouts, recovery policies, and specific configurations for maps, caches, SQL, and Jet. ```xml ... /mnt/persistence /mnt/hot-backup 120 900 FULL_RECOVERY_ONLY 0 ... 12 false ... 12 false ... true ... true ... ``` ```yaml hazelcast: persistence: enabled: true base-dir: /mnt/persistence backup-dir: /mnt/hot-backup validation-timeout-seconds: 120 data-load-timeout-seconds: 900 cluster-data-recovery-policy: FULL_RECOVERY_ONLY rebalance-delay-seconds: 0 map: test-map: merkle-tree: enabled: true depth: 12 data-persistence: enabled: true fsync: false cache: test-cache: merkle-tree: enabled: true depth: 12 data-persistence: enabled: true fsync: false sql: catalog-persistence-enabled: true jet: instance: lossless-restart-enabled: true ``` ```java include::ROOT:example$/storage/SamplePersistenceConfiguration.java[tag=hrconf] ``` -------------------------------- ### Example Warning and Error for Enforced Policy Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/security/pages/validating-secrets.adoc Shows the warning and severe error messages when a weak secret is detected and the policy is enforced. Cluster members will fail to start. ```log WARNING: [10.8.0.10]:5701 [dev] [{full-version}] @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ SECURITY WARNING @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ SSLConfig property[keyStorePassword] does not meet the current policy and complexity requirements. *Must contain 8 or more characters. *Must have at least 1 lower and 1 upper case characters. *Must have at least 1 alphabetic character. *Must contain at least 1 special character. SSLConfig property[trustStorePassword] does not meet the current policy and complexity requirements. *Must contain 8 or more characters. *Must have at least 1 lower and 1 upper case characters. *Must have at least 1 alphabetic character. *Must contain at least 1 special character. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Oct 10, 2022 11:00:52 AM com.hazelcast.instance.impl.Node SEVERE: [10.8.0.10]:5701 [dev] [{full-version}] Node creation failed com.hazelcast.security.WeakSecretException: Weak secrets found in configuration, check output above for more details. at com.hazelcast.security.impl.WeakSecretsConfigChecker.evaluateAndReport(WeakSecretsConfigChecker.java) at com.hazelcast.instance.impl.EnterpriseNodeExtension.printBannersBeforeNodeInfo(EnterpriseNodeExtension.java) at com.hazelcast.instance.impl.DefaultNodeExtension.printNodeInfo(DefaultNodeExtension.java) at com.hazelcast.instance.impl.Node.(Node.java) at com.hazelcast.instance.impl.HazelcastInstanceImpl.createNode(HazelcastInstanceImpl.java) at com.hazelcast.instance.impl.HazelcastInstanceImpl.(HazelcastInstanceImpl.java) ``` -------------------------------- ### Set Heap Size via JAVA_OPTS Source: https://github.com/hazelcast/hz-docs/blob/main/docs/modules/configuration/pages/jvm-parameters.adoc Use the `JAVA_OPTS` environment variable for ad-hoc JVM configuration. This example sets the heap size to 8GB when starting Hazelcast. ```bash JAVA_OPTS=-Xmx8G bin/jet-start ```