forked from hazelcast/hazelcast-cpp-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReference_Manual.md.in
More file actions
3268 lines (2462 loc) · 175 KB
/
Reference_Manual.md.in
File metadata and controls
3268 lines (2462 loc) · 175 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!-- THIS FILE IS AUTO GENERATED FILE.
MODIFY Reference_Manual.md.in TO MAKE CHANGES.
If you make any changes in Reference_Manual.md.in file,
you need to build the project which will re-generate the Reference_Manual.md file
and commit this generated reference manual in the github repository.
-->
# Hazelcast C++ Client Library
<!--ts-->
* [Hazelcast C++ Client Library](#hazelcast-c-client-library)
* [Introduction](#introduction)
* [Resources](#resources)
* [Release Notes](#release-notes)
* [1. Getting Started](#1-getting-started)
* [2. Features](#2-features)
* [3. Configuration Overview](#3-configuration-overview)
* [3.1. Configuration Options](#31-configuration-options)
* [3.1.1. Programmatic Configuration](#311-programmatic-configuration)
* [4. Serialization](#4-serialization)
* [4.1. identified_data_serializer Serialization](#41-identified_data_serializer-serialization)
* [4.2. portable_serializer Serialization](#42-portable_serializer-serialization)
* [4.3. compact_serializer Serialization](#43-compact_serializer-serialization)
* [4.3.1. Compact Serializer](#431-compact-serializer)
* [4.3.2. Schema Evolution](#432-schema-evolution)
* [4.3.3. Generic Record](#433-generic-record)
* [4.4. Custom Serialization](#44-custom-serialization)
* [4.5. JSON Serialization](#45-json-serialization)
* [4.6. Global Serialization](#46-global-serialization)
* [5. Setting Up Client Network](#5-setting-up-client-network)
* [5.1. Providing Member Addresses](#51-providing-member-addresses)
* [5.2. Setting Smart Routing](#52-setting-smart-routing)
* [5.3. Enabling Redo Operation](#53-enabling-redo-operation)
* [5.4. Setting Cluster Connection Timeout](#54-setting-cluster-connection-timeout)
* [5.5. Advanced Cluster Connection Retry Configuration](#55-advanced-cluster-connection-retry-configuration)
* [5.6. Enabling Client TLS/SSL](#56-enabling-client-tlsssl)
* [5.7. Enabling Hazelcast AWS Discovery](#57-enabling-hazelcast-aws-discovery)
* [5.8. Enabling Hazelcast Cloud Discovery](#58-enabling-hazelcast-cloud-discovery)
* [5.8.1. Cloud Discovery With SSL Enabled](#581-cloud-discovery-with-ssl-enabled)
* [5.9. External Smart Client Discovery](#59-external-smart-client-discovery)
* [5.10. Authentication](#510-authentication)
* [5.10.1. Username Password Authentication](#5101-username-password-authentication)
* [5.10.2. Token Authentication](#5102-token-authentication)
* [5.11. Configuring Backup Acknowledgment](#511-configuring-backup-acknowledgment)
* [6. Securing Client Connection](#6-securing-client-connection)
* [6.1. TLS/SSL](#61-tlsssl)
* [6.1.1. TLS/SSL for Hazelcast Members](#611-tlsssl-for-hazelcast-members)
* [6.1.2. TLS/SSL for Hazelcast C++ Client](#612-tlsssl-for-hazelcast-c-client)
* [6.1.2.1. Enabling Validation Of Server Certificate](#6121-enabling-validation-of-server-certificate)
* [6.1.2.2. Mutual Authentication (Two Way Authentication)](#6122-mutual-authentication-two-way-authentication)
* [6.1.2.3. Constraining The Used Cipher List](#6123-constraining-the-used-cipher-list)
* [7. Using the Hazelcast C++ Client](#7-using-the-hazelcast-c-client)
* [7.1. C++ Client API Overview](#71-c-client-api-overview)
* [7.2. C++ Client Operation Modes](#72-c-client-operation-modes)
* [7.2.1. Smart Client](#721-smart-client)
* [7.2.2. Unisocket Client](#722-unisocket-client)
* [7.3. Handling Failures](#73-handling-failures)
* [7.3.1. Handling Client Connection Failure](#731-handling-client-connection-failure)
* [7.3.2. Handling Retry-able Operation Failure](#732-handling-retry-able-operation-failure)
* [7.3.3. Client Backpressure](#733-client-backpressure)
* [7.3.4 Client Connection Strategy](#734-client-connection-strategy)
* [7.3.4.1 Configuring Client Reconnect Strategy](#7341-configuring-client-reconnect-strategy)
* [7.4. Using Distributed Data Structures](#74-using-distributed-data-structures)
* [7.4.1. Using imap](#741-using-imap)
* [7.4.2. Using multi_map](#742-using-multi_map)
* [7.4.3. Using replicated_map](#743-using-replicated_map)
* [7.4.4. Using iqueue](#744-using-iqueue)
* [7.4.5. Using iset](#745-using-iset)
* [7.4.6. Using ilist](#746-using-ilist)
* [7.4.7. Using ringbuffer](#747-using-ringbuffer)
* [7.4.8. Using reliable_topic](#748-using-reliable_topic)
* [7.4.9 Using pn_counter](#749-using-pn_counter)
* [7.4.10 Using flake_id_generator](#7410-using-flake_id_generator)
* [7.4.11. CP Subsystem](#7411-cp-subsystem)
* [7.4.11.1. Using atomic_long](#74111-using-atomic_long)
* [7.4.11.2. Using fenced_lock](#74112-using-fenced_lock)
* [7.4.11.3. Using counting_semaphore](#74113-using-counting_semaphore)
* [7.4.11.4. Using latch](#74114-using-latch)
* [7.4.11.5. Using atomic_reference](#74115-using-atomic_reference)
* [7.4.12. Using Transactions](#7412-using-transactions)
* [7.5. Distributed Events](#75-distributed-events)
* [7.5.1. Cluster Events](#751-cluster-events)
* [7.5.1.1. Listening for Member Events](#7511-listening-for-member-events)
* [7.5.1.3. Listening for Lifecycle Events](#7513-listening-for-lifecycle-events)
* [7.5.2. Distributed Data Structure Events](#752-distributed-data-structure-events)
* [7.5.2.1. Listening for Map Events](#7521-listening-for-map-events)
* [7.6. Distributed Computing](#76-distributed-computing)
* [7.6.1. Distributed Executor Service](#761-distributed-executor-service)
* [7.6.1.1 Implementing a Callable Task](#7611-implementing-a-callable-task)
* [7.6.1.2 Executing a Callable Task](#7612-executing-a-callable-task)
* [7.6.1.3 Scaling The Executor Service](#7613-scaling-the-executor-service)
* [7.6.1.4 Executing Code in the Cluster](#7614-executing-code-in-the-cluster)
* [7.6.1.5 Canceling an Executing Task](#7615-canceling-an-executing-task)
* [7.6.1.5.1 Example Task to Cancel](#76151-example-task-to-cancel)
* [7.6.1.6 Selecting Members for Task Execution](#7616-selecting-members-for-task-execution)
* [7.6.2. Using entry_processor](#762-using-entry_processor)
* [7.6.2.1. Processing Entries](#7621-processing-entries)
* [7.7. Distributed Query](#77-distributed-query)
* [7.7.1. How Distributed Query Works](#771-how-distributed-query-works)
* [7.7.1.1. person Map Query Example](#7711-person-map-query-example)
* [7.7.1.2. Querying by Combining Predicates with AND, OR, NOT](#7712-querying-by-combining-predicates-with-and-or-not)
* [7.7.1.3. Querying with SQL](#7713-querying-with-sql)
* [7.7.1.3.1. Supported SQL Syntax](#77131-supported-sql-syntax)
* [7.7.1.4. Querying Examples with Predicates](#7714-querying-examples-with-predicates)
* [7.7.1.5. Querying with JSON Strings](#7715-querying-with-json-strings)
* [7.7.1.6. Filtering with Paging Predicates](#7716-filtering-with-paging-predicates)
* [7.8. Performance](#78-performance)
* [7.8.1. Partition Aware](#781-partition-aware)
* [7.8.2. Near Cache](#782-near-cache)
* [7.8.2.1 Configuring Near Cache](#7821-configuring-near-cache)
* [7.8.2.2. Near Cache Example for Map](#7822-near-cache-example-for-map)
* [7.8.2.3. Near Cache Eviction](#7823-near-cache-eviction)
* [7.8.2.4. Near Cache Expiration](#7824-near-cache-expiration)
* [7.8.2.5. Near Cache Invalidation](#7825-near-cache-invalidation)
* [7.8.3. Pipelining](#783-pipelining)
* [7.9. Monitoring and Logging](#79-monitoring-and-logging)
* [7.9.1. Enabling Client Statistics](#791-enabling-client-statistics)
* [7.9.2. Logging Configuration](#792-logging-configuration)
* [7.10. Mixed Object Types Supporting Hazelcast Client](#710-mixed-object-types-supporting-hazelcast-client)
* [7.10.1. typed_data API](#7101-typed_data-api)
* [7.11. SQL API](#711-sql-api)
* [7.11.1 Overview](#7111-overview)
* [7.11.2 Create Mapping](#7112-create-mapping)
* [7.11.3 Read SELECT Results](#7113-read-select-results)
* [7.11.4 Sql Statement With Options](#7114-sql-statement-with-options)
* [7.11.5 Read Row Metadata](#7115-read-row-metadata)
* [7.11.6 Read Table Column Value](#7116-read-table-column-value)
* [7.11.7 Error Handling](#7117-error-handling)
* [7.11.8 Iterators](#7118-iterators)
* [7.11.8.1 page_iterator](#71181-page_iterator)
* [7.11.8.2 page_iterator_sync](#71182-page_iterator_sync)
* [7.11.8.3 row_iterator_sync](#71183-row_iterator_sync)
* [8. Development and Testing](#8-development-and-testing)
* [8.1. Testing](#81-testing)
* [9. Getting Help](#9-getting-help)
* [10. Contributing](#10-contributing)
* [11. License](#11-license)
* [12. Copyright](#12-copyright)
<!-- Added by: ihsan, at: Mon Aug 23 15:55:05 +03 2021 -->
<!--te-->
# Introduction
This document provides information about how to configure and use the C++ client for [Hazelcast](https://hazelcast.com/).
Serialization, network-related configuration, and securing the client connection are also described.
For an introduction to the C++ client for Hazelcast, and information on how to install and get started with the client, see the [Hazelcast documentation](https://docs.hazelcast.com/hazelcast/latest/clients/cplusplus).
# Resources
For more information about Hazelcast, see the:
* Hazelcast [website](https://hazelcast.com)
* Hazelcast [documentation](https://docs.hazelcast.com/hazelcast/latest)
# Release Notes
See the [Releases](https://github.com/hazelcast/hazelcast-cpp-client/releases) page of this repository.
# 1. Getting Started
For information about how to install and get started with the C++ client for Hazelcast, see the [Hazelcast documentation](https://docs.hazelcast.com/hazelcast/latest/clients/cplusplus).
For examples, see the Hazelcast C++ [code samples](examples).
See the Hazelcast C++ [code samples](examples) for more examples.
# 2. Features
Hazelcast C++ client supports the following data structures and features:
* imap
* iqueue
* iset
* ilist
* multi_map
* replicated_map
* Ringbuffer
* reliable_topic
* CRDT pn_counter
* flake_id_generator
* fenced_lock (CP Subsystem)
* counting_semaphore (CP Subsystem)
* atomic_long (CP Subsystem)
* atomic_reference (CP Subsystem)
* latch (CP Subsystem)
* Event Listeners
* Distributed Executor Service
* Entry Processor
* transactional_map
* transactional_multi_map
* transactional_queue
* transactional_list
* transactional_set
* Query (Predicates)
* paging_predicate
* Built-in Predicates
* Listener with predicate
* Near Cache Support
* Programmatic Configuration
* Fail Fast on Invalid Configuration
* SSL Support (requires Enterprise server)
* Authorization
* Smart Client
* Unisocket Client
* Lifecycle Service
* identified_data_serializer Serialization
* portable_serializer Serialization
* custom_serializer Serialization
* JSON Serialization
* Global Serialization
* Hazelcast AWS Discovery
* Hazelcast Cloud Discovery
* External Smart Client Discovery
# 3. Configuration Overview
This chapter describes the options to configure your C++ client.
## 3.1. Configuration Options
You can configure Hazelcast C++ client programmatically (API).
### 3.1.1. Programmatic Configuration
For programmatic configuration of the Hazelcast C++ client, just instantiate a `client_config` object and configure the desired aspects. An example is shown below.
```c++
hazelcast::client::client_config config;
config.get_network_config().add_address({ "your server ip", 5701 /* your server port*/});
auto hz = hazelcast::new_client(std::move(config)).get(); // Connects to the cluster
```
See the `client_config` class reference at the Hazelcast C++ client API Documentation for details.
# 4. Serialization
Serialization is the process of converting an object into a stream of bytes to store the object in the memory, a file or database, or transmit it through the network. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization. Hazelcast offers you its own native serialization methods. You will see these methods throughout this chapter.
Hazelcast serializes all your objects before sending them to the server. The `unsigned char` (`byte`), `bool`, `char`, `short`, `int32_t`, `int64_t`, `float`, `double`, `std::string` types are serialized natively and you cannot override this behavior. The following table is the conversion of types for Java server side.
| C++ | Java |
|--------------|-------------------------------------|
| byte | Byte |
| bool | Boolean |
| char | Character |
| short | Short |
| int32_t | Integer |
| int64_t | Long |
| float | Float |
| double | Double |
| std::string | String |
Vector of the above types can be serialized as `boolean[]`, `byte[]`, `short[]`, `int[]`, `float[]`, `double[]`, `long[]` and `string[]` for the Java server side, respectively.
If you want the serialization to work faster or you use the clients in different languages, Hazelcast offers its own native serialization types, such as [`identified_data_serializer` serialization](#41-identified_data_serializer-serialization) and [`portable_serializer` serialization](#42-portable_serializer-serialization).
On top of all, if you want to use your own serialization type, you can use a [Custom Serialization](#44-custom-serialization).
Hazelcast serialization is mostly performed at compile time by implementing the specialization of template struct `hz_serializer<>`. The specialized struct should be defined at the `hazelcast::client::serialization` namespace. The serializer should be derived from one of the following marker classes:
1. identified_data_serializer
2. portable_serializer
3. custom_serializer
4. json serialization
5. global_serializer
This way of specialization allows us two advantages:
1. No need to modify your classes (no extra API interfaces for existing classes).
2. The determination of the serializer is at compile time.
In addition to deriving from these marker classes, certain methods should be implemented in order your code to compile with this serializations.
You can also configure a global serializer in case non-of the above serializations are implemented for the user object. If no serializer can be found, then `exception::hazelcast_serialization` is thrown at runtime.
## 4.1. identified_data_serializer Serialization
For a faster serialization of objects, Hazelcast recommends to implement the `identified_data_serializer` interface. The following is an example of a `hz_serializer` implementing this interface:
```c++
struct Person {
std::string name;
bool male;
int32_t age;
};
namespace hazelcast {
namespace client {
namespace serialization {
template<>
struct hz_serializer<Person> : identified_data_serializer {
static int32_t get_factory_id() noexcept {
return 1;
}
static int32_t get_class_id() noexcept {
return 3;
}
static void write_data(const Person &object, object_data_output &out) {
out.write(object.name);
out.write(object.male);
out.write(object.age);
}
static Person read_data(object_data_input &in) {
return Person{in.read<std::string>(), in.read<bool>(), in.read<int32_t>()};
}
};
}
}
}
```
`hz_serializer<Person>` specialization of `hz_serializer` should implement the above four methods, namely `get_factory_id`, `get_class_id`, `write_data`, `read_data`. In case that the object fields are non-public, you can always define struct `hz_serializer<Person>` as a friend to your object class. You use the `object_data_output` class methods when serializing the object into binary bytes and the `object_data_input` class methods when de-serializing the bytes into the concrete object instance. The factory and class ID returned from the associated methods should match the IDs defined at the server side (you need to have the corresponding Java classes at the server side).
## 4.2. portable_serializer Serialization
If you want to support versioning of the objects, then you can use the portable serialization type. It has the following benefits:
- Support multiversion of the same object type.
- Fetch individual fields without having to rely on the reflection.
- Querying and indexing support without deserialization and/or reflection.
In order to support these features, a serialized `Portable` object contains meta information like the version and concrete location of each of the fields in the binary data. This way Hazelcast is able to navigate in the binary data and deserialize only the required field without actually deserializing the whole object which improves the query performance.
With multiversion support, you can have two members where each of them having different versions of the same object, and Hazelcast will store both meta information and use the correct one to serialize and deserialize portable objects depending on the member. This is very helpful when you are doing a rolling upgrade without shutting down the cluster.
Also note that portable serialization is totally language independent and is used as the binary protocol between Hazelcast server and clients.
A sample portable_serializer implementation of a `Person` class looks like the following:
```c++
struct Person {
std::string name;
bool male;
int32_t age;
};
namespace hazelcast {
namespace client {
namespace serialization {
template<>
struct hz_serializer<Person> : portable_serializer {
static int32_t get_factory_id() noexcept {
return 1;
}
static int32_t get_class_id() noexcept {
return 3;
}
static void write_portable(const Person &object, portable_writer &out) {
out.write("name", object.name);
out.write("gender", object.male);
out.write("age", object.age);
}
static Person read_portable(portable_reader &in) {
return Person{in.read<std::string>("name"), in.read<bool>("gender"), in.read<int32_t>("age")};
}
};
}
}
}
```
Note that, this is very similar to `identified_data_serializer` implementation except the method signatures and the derived marker class of `portable_serializer` for the specialized serializer.
`hz_serializer<Person>` specialization of `hz_serializer` should implement the above four methods, namely `get_factory_id`, `get_class_id`, `write_portable`, `read_portable`. In case that the object fields are non-public, you can always define struct `hz_serializer<Person>` as friend to your object class. You use the `portable_writer` class methods when serializing the object into binary bytes and you use the `portable_reader` class methods when de-serializing the bytes into the concrete object instance.
## 4.3. compact_serializer Serialization
As an enhancement to the existing serialization methods, Hazelcast offers compact serialization, with the following main features:
- Separates the schema from the data and stores it for each type, instead of each object which results in less memory and bandwidth usage compared to other formats
- Does not require a class to implement an interface or change the source code of the class in any way
- Supports schema evolution which permits adding or removing fields, or changing the types of fields
- Can work with any kind of types
- Platform and language independent
- Supports partial deserialization of fields, without deserializing the whole objects during queries or indexing
Hazelcast achieves these features by having a well-known schema of objects and replicating them across the cluster which enables members and clients to fetch schemas they don’t have in their local registries. Each serialized object carries just a schema identifier and relies on the schema distribution service or configuration to match identifiers with the actual schema. Once the schemas are fetched, they are cached locally on the members and clients so that the next operations that use the schema do not incur extra costs.
Schemas help Hazelcast to identify the locations of the fields on the serialized binary data. With this information, Hazelcast can deserialize individual fields of the data, without reading the whole binary. This results in a better query and indexing performance.
Schemas can evolve freely by adding or removing fields. Even, the types of the fields can be changed. Multiple versions of the schema may live in the same cluster and both the old and new readers may read the compatible parts of the data. This feature is especially useful in rolling upgrade scenarios.
The Compact serialization does not require any changes in the user classes as it doesn’t need a class to implement a particular interface. Serializers might be implemented and specified separately from the classes.
The underlying format of the compact serialized objects is platform and language independent.
Refer to [documentation](https://docs.hazelcast.com/hazelcast/latest/compact-binary-specification) for more details about compact binary serialization.
### 4.3.1. Compact Serializer
Another way to use compact serialization is to implement the `hz_serializer<T> : compact::compact_serializer` specialization for a `T`. A basic serializer could look like:
``` C++
class PersonDTO
{
int age;
std::string name;
std::string surname;
};
namespace hazelcast {
namespace client {
namespace serialization {
template<>
struct hz_serializer<PersonDTO> : compact::compact_serializer
{
static void write(const PersonDTO& object, compact::compact_writer& out)
{
out.write_int32("age", object.age);
out.write_string("name", object.name);
out.write_string("surname", object.surname);
}
static PersonDTO read(compact::compact_reader& in)
{
PersonDTO person;
person.age = in.read_int32("age");
boost::optional<std::string> name = in.read_string("name");
if (name) {
person.name = *name;
}
boost::optional<std::string> surname = in.read_string("surname");
if (surname) {
person.surname = *surname;
}
return person;
}
static std::string type_name() { return "person"; }
};
} // namespace serialization
} // namespace client
} // namespace hazelcast
```
### 4.3.2. Schema Evolution
Compact serialization permits schemas and classes to evolve by adding or removing fields, or by changing the types of fields. More than one version of a class may live in the same cluster and different clients or members might use different versions of the class.
Hazelcast handles the versioning internally. So, you don’t have to change anything in the classes or serializers apart from the added, removed, or changed fields.
Hazelcast achieves this by identifying each version of the class by a unique fingerprint. Any change in a class results in a different fingerprint. Hazelcast uses a 64-bit Rabin Fingerprint to assign identifiers to schemas, which has an extremely low collision rate.
Different versions of the schema with different identifiers are replicated in the cluster and can be fetched by clients or members internally. That allows old readers to read fields of the classes they know when they try to read data serialized by a new writer. Similarly, new readers might read fields of the classes available in the data, when they try to read data serialized by an old writer.
This means that for one type name, there can be several schemas.
In addition, the `compact::compact_reader` class exposes methods such as `field_kind get_field_kind(string name)` which returns the kind (i.e. the actual type) of the field.
### 4.3.3. Generic Record
Compact serialization introduces the `generic_record` and `generic_record_builder` classes, which represents a container and builder object that can be used in place of domain classes. The client always knows how to (de) serialize compact instances and therefore does not require any configuration in order to handle them.
A new record can be created as such:
``` C++
using namespace hazelcast::client::serialization::generic_record;
generic_record record = generic_record_builder{ "type-name" }
.set_boolean("field-name-1", true)
.set_int32("field-name-2", 123)
.set_string("field-name-3", "hello")
.build();
// Put into map and wait
map->put(1234, record).get();
```
A generic record can be used as such:
``` C++
auto rec = map->get<int, generic_record>(1234).get();
bool field1 = rec->get_boolean("field-name-1");
int field2 = rec->get_int32("field-name-2");
boost::optional<std::string> field3 = rec->get_string("field-name-3");
```
Refer to the general [documentation](https://docs.hazelcast.com/hazelcast/latest/serialization/compact-serialization) for more details on how to access domain objects without domain classes. [Supported types](https://docs.hazelcast.com/hazelcast/latest/serialization/compact-serialization#supported-types) are listed here.
## 4.4. Custom Serialization
Hazelcast lets you plug a custom serializer to be used for serialization of objects. It also allows you an integration point for any external serialization frameworks such as protobuf, flatbuffers, etc.
A sample custom_serializer implementation of a `Person` class looks like the following:
```c++
struct Person {
std::string name;
bool male;
int32_t age;
};
namespace hazelcast {
namespace client {
namespace serialization {
template<>
struct hz_serializer<Person> : custom_serializer {
static constexpr int32_t get_type_id() noexcept {
return 3;
}
static void write(const Person &object, object_data_output &out) {
out.write(object.name);
out.write(object.male);
out.write(object.age);
}
static Person read(object_data_input &in) {
return Person{in.read<std::string>(), in.read<bool>(), in.read<int32_t>()};
}
};
}
}
}
```
`hz_serializer<Person>` specialization of `hz_serializer` should implement the above three methods, namely `get_type_id`, `write`, `read`. In case that the object fields are non-public, you can always define struct `hz_serializer<Person>` as friend to your object class. You use the `object_data_output` class methods when serializing the object into binary bytes and you use the `object_data_input` class methods when de-serializing the bytes into the concrete object instance.
## 4.5. JSON Serialization
You can use the JSON formatted strings as objects in Hazelcast cluster. Creating JSON objects in the cluster does not require any server side coding and hence you can just send a JSON formatted string object to the cluster and query these objects by fields.
In order to use JSON serialization, you should use the `hazelcast_json_value` object for the key or value. Here is an example imap usage:
```c++
auto hz = hazelcast::new_client().get();
auto map = hz.get_map("map").get();
map->put("item1", hazelcast::client::hazelcast_json_value("{ \"age\": 4 }")).get();
map->put("item2", hazelcast::client::hazelcast_json_value("{ \"age\": 20 }")).get();
```
`hazelcast_json_value` is a simple wrapper and identifier for the JSON formatted strings. You can get the JSON string from the `hazelcast_json_value` object using the `to_string()` method.
You can construct a `hazelcast_json_value` using one of the constructors. All constructors accept the JSON formatted string as the parameter. No JSON parsing is performed but it is your responsibility to provide correctly formatted JSON strings. The client will not validate the string, and it will send it to the cluster as it is. If you submit incorrectly formatted JSON strings and, later, if you query those objects, it is highly possible that you will get formatting errors since the server will fail to deserialize or find the query fields.
You can query JSON objects in the cluster using the `predicate`s of your choice. An example JSON query for querying the values whose age is less than 6 is shown below:
```c++
// Get the objects whose age is less than 6
auto result = map->values<hazelcast::client::hazelcast_json_value>(
hazelcast::client::query::greater_less_predicate(hz, "age", 6, false, true)).get();
```
## 4.6. Global Serialization
The global serializer is registered as a fallback serializer to handle all other objects if a serializer cannot be located for them.
By default, global serializer is used if there are no specialization `hz_serializer<my_class>` for my class `my_class`.
**Use Cases:**
* Third party serialization frameworks can be integrated using the global serializer.
* For your custom objects, you can implement a single serializer to handle all object serializations.
A sample global serializer that integrates with a third party serializer is shown below.
```c++
class MyGlobalSerializer : public hazelcast::client::serialization::global_serializer {
public:
void write(const boost::any &obj, hazelcast::client::serialization::object_data_output &out) override {
auto const &object = boost::any_cast<Person>(obj);
out.write(object.name);
out.write(object.male);
out.write(object.age);
}
boost::any read(hazelcast::client::serialization::object_data_input &in) override {
return boost::any(Person{in.read<std::string>(), in.read<bool>(), in.read<int32_t>()});
}
};
```
As you can see from the sample, the global serializer class should implement the `hazelcast::client::serialization::global_serializer` interface.
You should register the global serializer in the configuration.
```c++
hazelcast::client::client_config config;
config.get_serialization_config().set_global_serializer(std::make_shared<MyGlobalSerializer>());
auto hz = hazelcast::new_client(std::move(config)).get();
```
You need to utilize the `boost::any_cast` methods tyo actually use the objects provided for serialization and you are expected to return type `boost::any` from the `read` method.
# 5. Setting Up Client Network
All network related configuration of Hazelcast C++ client is performed programmatically via the `client_network_config` object. The following is an example configuration.
Here is an example of configuring the network for C++ Client programmatically.
```c++
client_config clientConfig;
clientConfig.get_network_config().add_addresses({{"10.1.1.21", 5701}, {"10.1.1.22", 5703}});
clientConfig.get_network_config().set_smart_routing(true);
clientConfig.set_redo_operation(true);
clientConfig.get_connection_strategy_config().get_retry_config().set_cluster_connect_timeout(
std::chrono::seconds(30));
```
## 5.1. Providing Member Addresses
Address list is the initial list of cluster addresses which the client will connect to. The client uses this
list to find an alive member. Although it may be enough to give only one address of a member in the cluster
(since all members communicate with each other), it is recommended that you give the addresses for all the members.
```c++
client_config clientConfig;
clientConfig.get_network_config().add_address(address("10.1.1.21", 5701), address("10.1.1.22", 5703));
```
The provided list is shuffled and tried in a random order. If no address is added to the `client_network_config`, then `127.0.0.1:5701` is tried by default.
## 5.2. Setting Smart Routing
Smart routing defines whether the client mode is smart or unisocket. See the [C++ Client Operation Modes section](#72-c-client-operation-modes)
for the description of smart and unisocket modes.
The following is an example configuration.
```c++
client_config clientConfig;
clientConfig.get_network_config().set_smart_routing(true);
```
Its default value is `true` (smart client mode).
## 5.3. Enabling Redo Operation
It enables/disables redo-able operations. While sending the requests to the related members, the operations can fail due to various reasons. Read-only operations are retried by default. If you want to enable retry for the other operations, you can set the `redo_operation` to `true`.
```c++
client_config clientConfig;
clientConfig.set_redo_operation(true);
```
Its default value is `false` (disabled).
## 5.4. Setting Cluster Connection Timeout
Cluster connection timeout is the timeout value for which the client tries to connect to the cluster. If the client cannot connect to the cluster during this timeout duration, the client shuts down itself and it cannot be re-used (you need to obtain a new client).
The following example shows how you can set the cluster connection timeout to 30 seconds.
```c++
client_config().get_connection_strategy_config().get_retry_config().set_cluster_connect_timeout(std::chrono::seconds(30));
```
## 5.5. Advanced Cluster Connection Retry Configuration
When client is disconnected from the cluster, it searches for new connections to reconnect. You can configure the frequency of the reconnection attempts and client shutdown behavior using `connection_retry_config`.
The following is an example configuration.
Below is an example configuration. It configures a total timeout of 30 seconds to connect to a cluster, by initial backoff time being 100 milliseconds and doubling the time before every try with a jitter of 0.8 up to a maximum of 3 seconds backoff between each try..
```c++
client_config().get_connection_strategy_config().get_retry_config().set_cluster_connect_timeout(
std::chrono::seconds(30)).set_multiplier(2.0).set_jitter(0.8).set_initial_backoff_duration(
std::chrono::seconds(100)).set_max_backoff_duration(std::chrono::seconds(3));
```
The following are configuration element descriptions:
* `initial_backoff_duration`: Specifies how long to wait (backoff) after the first failure before retrying.
* `max_backoff_duration`: Specifies the upper limit for the backoff between each cluster connect tries.
* `multiplier`: Factor to multiply the backoff after a failed retry.
* `cluster_connect_timeout`: Timeout value for the client to give up to connect to the current cluster. If the client can not connect during this time, then it shuts down and it can not be re-used.
* `jitter`: Specifies by how much to randomize backoffs.
## 5.6. Enabling Client TLS/SSL
You can use TLS/SSL to secure the connection between the clients and members. If you want to enable TLS/SSL
for the client-cluster connection, you should set an SSL configuration. Please see the [TLS/SSL section](#61-tlsssl).
As explained in the [TLS/SSL section](#61-tlsssl), Hazelcast members have key stores used to identify themselves (to other members) and Hazelcast C++ clients have certificate authorities used to define which members they can trust.
## 5.7. Enabling Hazelcast AWS Discovery
The C++ client can discover the existing Hazelcast servers in the Amazon AWS environment. The client queries the Amazon AWS environment using the [describe-instances](http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) query of AWS. The client finds only the up and running instances and filters them based on the filter config provided at the `client_aws_config` configuration.
The following is an example configuration:
```c++
clientConfig.get_network_config().get_aws_config()
.set_enabled(true)
.set_access_key("my access key id")
.set_secret_key("my secret access key")
.set_tag_key("my tag key")
.set_tag_value("my tag value")
.set_security_group_name("my secure group")
.set_region("us-east-1");
```
You need to enable the discovery by calling the `set_enabled(true)`. You can set your access key and secret in the configuration as shown in this example. You can filter the instances by setting which tags they have or by the security group setting. You can set the region for which the instances will be retrieved from, the default region is `us-east-1`.
See [client_aws_config.h](hazelcast/include/hazelcast/client/config/client_aws_config.h)
and [the AWS examples directory](examples/aws)
for more details.
## 5.8. Enabling Hazelcast Cloud Discovery
If you are using [Hazelcast Cloud](https://cloud.hazelcast.com/) and you want to write an application that will utilize the Hazelcast cloud database service, you can use the C++ client. The configuration is very simple, you just need to set the cluster name, discovery token and enable the cloud discovery on network settings. Here is an example configuration:
```c++
hazelcast::client::client_config config;
config.set_cluster_name("my_cluster(should match with the same cluster name at the cloud web site)");
auto &cloud_configuration = config.get_network_config().get_cloud_config();
cloud_configuration.enabled = true;
cloud_configuration.discovery_token = "My token for the cluster (you can get from the cloud web site)";
auto hz = hazelcast::new_client(std::move(config)).get();
```
That is all the configuration you will need. The client will query the hazelcast coordinator service located at "https://coordinator.hazelcast.cloud/cluster/discovery?token=my_token" with the token you configured and will get a list of available server ip port combinations to connect to. The client will always use the public ip to connect to the cluster. The network connection timeout (`client_network_config::set_connection_timeout(const std::chrono::milliseconds &timeout)`) is used as the timeout value for connecting the coordinator and retrieving the cluster member list (change this setting if you have any timeout problems).
Please check the code sample at `examples/cloud-discovery/connect-cloud.cpp` for a full featured cloud discovery example.
## 5.8.1. Cloud Discovery With SSL Enabled
You can create a Hazelcast cluster in the cloud with "[Enable Encryption](https://docs.hazelcast.com/cloud/encryption.html#setting-up-encryption)" option. When this option is selected the cluster requires the clients to connect using the SSL connection and the client should be configured to do [mutual authentication](#6122-mutual-authentication-two-way-authentication). The required certificate authority file, client certificate, client key file and key file PEM pass phrase are located at the Hazelcast cloud web site cluster configuration `Configure Clients` page. Download the keystore file and unzip it (it will be in a folder such as `hzcloud_xxx_keys` where `xxx` is the cluster number), this zip includes all the required files. Also, copy the `Keystore and truststore password` which is the client key PEM file pass phrase. Once, you have all this information in hand, you can configure the client as in the following code snippet:
```c++
std::string cluster_name = "my_cluster";
std::string cloud_token = "my cloud token for the cluster";
std::string ca_file_path = "/path/to/hzcloud_xxx_keys/ca.pem";
std::string client_certificate = "/path/to/hzcloud_xxx_keys/cert.pem";
std::string client_key = "/path/to/hzcloud_xxx_keys/key.pem";
std::string client_key_pem_pass_phrase = "Keystore and truststore password";
hazelcast::client::client_config config;
config.set_cluster_name(cluster_name);
auto &cloud_configuration = config.get_network_config().get_cloud_config();
cloud_configuration.enabled = true;
cloud_configuration.discovery_token = cloud_token;
// ssl configuration
boost::asio::ssl::context ctx(boost::asio::ssl::context::tlsv12);
ctx.set_verify_mode(boost::asio::ssl::verify_peer);
ctx.load_verify_file(ca_file_path);
ctx.use_certificate_file(client_certificate, boost::asio::ssl::context::pem);
ctx.set_password_callback([&] (std::size_t max_length, boost::asio::ssl::context::password_purpose purpose) {
return client_key_pem_pass_phrase;
});
ctx.use_private_key_file(client_key, boost::asio::ssl::context::pem);
config.get_network_config().get_ssl_config().set_context(std::move(ctx));
auto hz = hazelcast::new_client(std::move(config)).get();
```
As you see in the code snippet, we provide a `boost::asio::ssl::context` in the client configuration in addition to the cloud token and cluster name configurations. It uses mutual authentication (two-way handshake).
Please check the code sample at `examples/cloud-discovery/ssl-connect-cloud.cpp` for a full featured cloud discovery with SSL example.
## 5.9. External Smart Client Discovery
> **NOTE: This feature requires Hazelcast 4.2 or higher version.**
The client sends requests directly to cluster members in the smart client mode (default) in order to reduce hops to
accomplish operations. Because of that, the client should know the addresses of members in the cluster.
In cloud-like environments, or Kubernetes, there are usually two network interfaces: the private and public network
interfaces. When the client is in the same network as the members, it uses their private network addresses. Otherwise,
if the client and the Hazelcast cluster are on different networks, the client cannot connect to members using their
private network addresses. Hazelcast 4.2 introduced External Smart Client Discovery to solve that issue. The client
needs to communicate with all cluster members via their public IP addresses in this case. Whenever Hazelcast cluster
members are able to resolve their own public external IP addresses, they pass this information to the client.
As a result, the client can use public addresses for communication.
In order to use this feature, make sure your cluster members are accessible from the network the client resides in,
then set config `client_network_config()::use_public_address(true)` to true. You should specify the public address of
at least one member in the configuration:
```c++
hazelcast::client::client_config config;
constexpr int server_port = 5701;
constexpr const char *server_public_address = "myserver.publicaddress.com";
config.get_network_config().use_public_address(true).add_address(
hazelcast::client::address{server_public_address, server_port});
```
This solution works everywhere without further configuration (Kubernetes, AWS, GCP, Azure, etc.) as long as the
corresponding plugin is enabled in the Hazelcast server configuration.
## 5.10. Authentication
By default, the client does not use any authentication method and just uses the cluster "dev" to connect to. You can change which cluster to connect by using the configuration API `client_config::set_cluster_name`. This way, you can have multiple clusters in the network but the client will only be able to connect to the cluster with the correct cluster name (server should also be started with the cluster name configured to the same cluster name).
If you want to enable authentication, then the client can be configured in one of the two different ways to authenticate:
* Username password based authentication
* Token based authentication
## 5.10.1. Username Password Authentication
The following is an example configuration where we set the username `test-user` and password `test-pass` to be used while trying to connect to the cluster:
```c++
hazelcast::client::client_config config;
config.set_credentials(std::make_shared<hazelcast::client::security::username_password_credentials>("test-user", "test-pass"));
auto hz = hazelcast::new_client(std::move(config)).get();
```
Note that the server needs to be configured to use the same username and password. An example server xml config is:
```xml
<security enabled="true">
<realms>
<realm name="usernamePasswordIdentityRealm">
<authentication>
<simple>
<user username="test-user" password="test-pass"/>
</simple>
</authentication>
</realm>
</realms>
<client-authentication realm="usernamePasswordIdentityRealm"/>
</security>
```
## 5.10.2. Token Authentication
The following is an example configuration where we set the secret token bytes to be used while trying to connect to the cluster:
```c++
std::vector<hazelcast::byte> my_token = {'S', 'G', 'F', '6', 'Z', 'W'};
config.set_credentials(std::make_shared<hazelcast::client::security::token_credentials>(my_token));
auto hz = hazelcast::new_client(std::move(config)).get();
```
Implementing a custom login module is mandatory to use token authentication by itself. An example custom login module is:
```Java
import com.hazelcast.config.Config;
import com.hazelcast.security.ClusterLoginModule;
import com.hazelcast.security.Credentials;
import com.hazelcast.security.CredentialsCallback;
import com.hazelcast.security.TokenCredentials;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.Arrays;
public class TokenLoginModule extends ClusterLoginModule {
private String name;
private final byte[] expectedToken = "SGF6ZW".getBytes(StandardCharsets.US_ASCII);
@Override
protected boolean onLogin() throws LoginException {
CredentialsCallback cb = new CredentialsCallback();
name = cb.getCredentials().getName();
try {
callbackHandler.handle(new Callback[] { cb });
} catch (IOException | UnsupportedCallbackException e) {
throw new LoginException("Problem getting credentials");
}
Credentials credentials = cb.getCredentials();
if (!(credentials instanceof TokenCredentials)) {
throw new FailedLoginException();
}
byte[] actualToken = ((TokenCredentials) credentials).getToken();
if (Arrays.equals(actualToken, expectedToken)) {
return true;
}
throw new LoginException("Invalid token");
}
@Override
protected String getName() {
return name;
}
}
```
Note that the server needs to be configured to use the same token. An example server xml config is:
```xml
<security enabled="true">
<realms>
<realm name="jaasRealm">
<authentication>
<jaas>
<login-module class-name="com.example.TokenLoginModule" usage="REQUIRED"/>
</jaas>
</authentication>
</realm>
</realms>
<client-authentication realm="jaasRealm"/>
</security>
```
## 5.11. Configuring Backup Acknowledgment
When an operation with sync backup is sent by a client to the Hazelcast member(s), the acknowledgment of the operation's backup is sent to the client by the backup replica member(s). This improves the performance of the client operations.
To disable backup acknowledgement, you should use the `backup_acks_enabled` configuration option.
```c++
// Disable the default backup ack feature
hazelcast_client hz(client_config().backup_acks_enabled(false));
```
Its default value is `true`. This option has no effect for unisocket clients.
You can also fine-tune this feature using `client_config::set_protperty` API as described below:
- `hazelcast.client.operation.backup.timeout.millis`: Default value is `5000` milliseconds. If an operation has backups, this property specifies how long (in milliseconds) the invocation waits for acks from the backup replicas. If acks are not received from some of the backups, there will not be any rollback on the other successful replicas.
- `hazelcast.client.operation.fail.on.indeterminate.state`: Default value is `false`. When it is `true`, if an operation has sync backups and acks are not received from backup replicas in time, or the member which owns primary replica of the target partition leaves the cluster, then the invocation fails. However, even if the invocation fails, there will not be any rollback on other successful replicas.
# 6. Securing Client Connection
This chapter describes the security features of the Hazelcast C++ client. These include using TLS/SSL for connections between members and between clients and members. These security features require **Hazelcast Enterprise** server cluster.
## 6.1. TLS/SSL
One of the offers of Hazelcast is the TLS/SSL protocol which you can use to establish an encrypted communication between the client and the server.
### 6.1.1. TLS/SSL for Hazelcast Members
Hazelcast allows you to encrypt socket level communication between Hazelcast members and between Hazelcast clients and members, for end to end encryption. To use it, see the [TLS/SSL for Hazelcast Members section](https://docs.hazelcast.com/hazelcast/latest/security/tls-ssl.html#tlsssl-for-hazelcast-members) in the Hazelcast Reference Manual.
### 6.1.2. TLS/SSL for Hazelcast C++ Client
The Hazelcast C++ client uses [Boost Asio](https://www.boost.org/doc/libs/1_76_0/doc/html/boost_asio.html) library for networking and secure communication.
To use TLS/SSL with your Hazelcast C++ client, you should build the library with the OpenSSL feature turned on. By default, this feature is turned off. Here are the different ways to install the library with SSL support:
* CMake Users: Provide flag `-DWITH_OPENSSL=ON` flag when configuring. Please note that the CMake `find_package` should be able to locate the OpenSSL installation, otherwise the cmake config will fail. The rest is as usual with the [installation with cmake](#131-cmake-users).
* Conan Users: Use option `with_openssl` while installing the conan project. An example command you can use in the build folder of your project with conan: `conan install -o hazelcast-cpp-client:with_openssl=True .. --build=hazelcast-cpp-client`. This command will install the `hazelcast-cpp-client` with the OpenSSL support.
Once the library is installed properly, you can enable the SSL feature in the client configuration.
You can set the protocol type. If not set, the configuration uses `tlsv12` (TLSv1.2) as the default protocol type and version.
There may be different ways to configure ssl communication at the client side. We utilize the `boost::asio::ssl::context` to configure the SSL communication. You can set the verify mode to ignore or verify the server certificate, set the used SSL protocol, add verify callbacks, and such. The details can be found at the [Boost asio ssl context documentation](https://www.boost.org/doc/libs/1_76_0/doc/html/boost_asio/reference/ssl__context.html).
Here is the most basic way to enable the SSL on the client:
```c++
hazelcast::client::client_config config;
boost::asio::ssl::context ctx(boost::asio::ssl::context::method::tlsv12_client);
config.get_network_config().get_ssl_config().set_context(std::move(ctx));
auto hz = hazelcast::new_client(std::move(config)).get();
```
Once, we set the SSL context, the client will start with SSL enabled and try to connect to the server using the provided context.
#### 6.1.2.1. Enabling Validation Of Server Certificate
If you want to enable the validation of server certificate on the client side and disable any connection without a valid certificate, you can use the [context::set_verify_mode](https://www.boost.org/doc/libs/1_76_0/doc/html/boost_asio/reference/ssl__context/set_verify_mode.html) API. Here is an example:
```c++
hazelcast::client::client_config config;
boost::asio::ssl::context ctx(boost::asio::ssl::context::method::tlsv12_client);
ctx.set_verify_mode(boost::asio::ssl::verify_peer);
ctx.set_default_verify_paths();
config.get_network_config().get_ssl_config().set_context(std::move(ctx));
auto hz = hazelcast::new_client(std::move(config)).get();
```
The client will connect if the server has a certificate which is properly signed by well known Certificate Authorities(CA). On Windows, you may need to set the well known CA Authorities file path since OpenSSL may not find the well known certifite authorities file. This can be solved by providing the [SSL_CERT_FILE](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_default_verify_paths.html) environment variable set to point a file path that has all the needed well known certificate authorities. For example, you can get such a file maintained by Mozilla at https://curl.se/docs/caextract.html.
If the server is using a user generated certificate file which is not signed by the well known CA authorities, then you can use the public certificate of the server to configure the client to connect and verify the server. Here is an example configuration for this:
```c++
hazelcast::client::client_config config;
boost::asio::ssl::context ctx(boost::asio::ssl::context::method::tlsv12_client);
ctx.set_verify_mode(boost::asio::ssl::verify_peer);
ctx.set_default_verify_paths();
ctx.load_verify_file("/path/to/my/server/public/certificate");
config.get_network_config().get_ssl_config().set_context(std::move(ctx));
auto hz = hazelcast::new_client(std::move(config)).get();
```
As you can see in this code snippet, we add the server public certificate using [context::load_verify_file](https://www.boost.org/doc/libs/1_76_0/doc/html/boost_asio/reference/ssl__context/load_verify_file.html) as a verify file so that the client can validate the server certificate as valid and connect to the server. There are also other ways to load verify files and use verify directories. You can find the details at [Boost Asio ssl context documentation](https://www.boost.org/doc/libs/1_76_0/doc/html/boost_asio/reference/ssl__context.html).
You can check `BasicTLSClient.cpp` example for a full featured example.
#### 6.1.2.2. Mutual Authentication (Two Way Authentication)
[Mutual Authentication](https://en.wikipedia.org/wiki/Mutual_authentication) is the process where the client verifies the identity of the server via server's certificate (either self-signed or signed by a CA authority) and the server verifies the client identity via the client provided certificate (either self-signed or signed by a CA authority). If the Hazelcast server is configured for [mutual authentication](https://docs.hazelcast.com/hazelcast/latest/security/tls-ssl.html#tlsssl-for-hazelcast-members) as **REQUIRED**, then we can use the [ssl::context::use_xxx](https://www.boost.org/doc/libs/1_76_0/doc/html/boost_asio/reference/ssl__context.html) methods to add the client's public and private certificates and use them during its authentication to the server. An example configuration is as follows:
```c++
hazelcast::client::client_config config;
boost::asio::ssl::context ctx(boost::asio::ssl::context::method::tlsv12_client);
ctx.set_verify_mode(boost::asio::ssl::verify_peer);
ctx.set_default_verify_paths();
// This config is to validate the server certificate if server does not have a CA signed certificate
ctx.load_verify_file("/path/to/my/server/public/certificate");