forked from hazelcast/hazelcast-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
665 lines (641 loc) · 17.3 KB
/
example_test.go
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
/*
* Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hazelcast_test
import (
"context"
"fmt"
"log"
"math/rand"
"strconv"
"sync"
"time"
"github.com/hazelcast/hazelcast-go-client"
"github.com/hazelcast/hazelcast-go-client/aggregate"
"github.com/hazelcast/hazelcast-go-client/predicate"
"github.com/hazelcast/hazelcast-go-client/serialization"
)
func Example() {
// Create the configuration
config := hazelcast.Config{}
config.Cluster.Name = "dev"
config.Cluster.Network.SetAddresses("localhost:5701")
// Start the client with the configuration provider.
ctx := context.TODO()
client, err := hazelcast.StartNewClientWithConfig(ctx, config)
if err != nil {
log.Fatal(err)
}
// Retrieve a map.
peopleMap, err := client.GetMap(ctx, "people")
if err != nil {
log.Fatal(err)
}
// Call map functions.
err = peopleMap.Set(ctx, "jane", "doe")
if err != nil {
log.Fatal(err)
}
// Stop the client once you are done with it.
client.Shutdown(ctx)
}
func ExampleSet() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Retrieve the set named my-set.
set, err := client.GetSet(ctx, "my-set")
if err != nil {
log.Fatal(err)
}
_, err = set.AddAll(ctx, "item1", "item2", "item3", "item2", "item1")
if err != nil {
log.Fatal(err)
}
// Get the items. Note that there are no duplicates.
items, err := set.GetAll(ctx)
if err != nil {
log.Fatal(err)
}
for _, item := range items {
fmt.Println("Item:", item)
}
}
func ExamplePNCounter() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Retrieve the PN counter named my-pn.
pn, err := client.GetPNCounter(ctx, "my-pn")
if err != nil {
log.Fatal(err)
}
// Add the given value and retrieve the result.
_, err = pn.AddAndGet(ctx, 43)
if err != nil {
log.Fatal(err)
}
// Decrement the given value and retrieve the result.
value, err := pn.DecrementAndGet(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(value)
}
func ExampleMap() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Retrieve a map.
peopleMap, err := client.GetMap(ctx, "people")
if err != nil {
log.Fatal(err)
}
// Call map functions.
err = peopleMap.Set(ctx, "jane", "doe")
if err != nil {
log.Fatal(err)
}
// Stop the client once you are done with it.
client.Shutdown(ctx)
}
func ExampleMultiMap() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Retrieve a map.
peopleMap, err := client.GetMultiMap(ctx, "people")
if err != nil {
log.Fatal(err)
}
// Call map functions.
success, err := peopleMap.Put(ctx, "jane", "doe")
if err != nil {
log.Fatal(err)
}
if !success {
log.Fatal("map operation failed")
}
// Add multiple values to existing key
if err = peopleMap.PutAll(ctx, "jane", "smith", "mason"); err != nil {
log.Fatal(err)
}
values, err := peopleMap.Get(ctx, "jane")
if err != nil {
log.Fatal(err)
}
// ["smith", "mason", "doe"] order of values may not be preserved
fmt.Println(values)
// Stop the client once you are done with it.
client.Shutdown(ctx)
}
func ExampleMap_Aggregate() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
myMap, err := client.GetMap(ctx, "my-map")
if err != nil {
log.Fatal(err)
}
if err = myMap.Set(ctx, "k1", serialization.JSON(`{"A": "foo", "B": 10}`)); err != nil {
log.Fatal(err)
}
if err = myMap.Set(ctx, "k2", serialization.JSON(`{"A": "bar", "B": 30}`)); err != nil {
log.Fatal(err)
}
result, err := myMap.Aggregate(ctx, aggregate.LongSum("B"))
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
func ExampleMap_AddEntryListener() {
// error handling was omitted for brevity
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
entryListenerConfig := hazelcast.MapEntryListenerConfig{
IncludeValue: true,
}
m, err := client.GetMap(ctx, "somemap")
if err != nil {
log.Fatal(err)
}
// enable receiving entry added events
entryListenerConfig.NotifyEntryAdded(true)
// enable receiving entry removed events
entryListenerConfig.NotifyEntryRemoved(true)
// enable receiving entry updated events
entryListenerConfig.NotifyEntryUpdated(true)
// enable receiving entry evicted events
entryListenerConfig.NotifyEntryEvicted(true)
// enable receiving entry loaded events
entryListenerConfig.NotifyEntryLoaded(true)
subscriptionID, err := m.AddEntryListener(ctx, entryListenerConfig, func(event *hazelcast.EntryNotified) {
switch event.EventType {
// this is an entry added event
case hazelcast.EntryAdded:
fmt.Println("Entry Added:", event.Key)
// this is an entry removed event
case hazelcast.EntryRemoved:
fmt.Println("Entry Removed:", event.Key)
// this is an entry updated event
case hazelcast.EntryUpdated:
fmt.Println("Entry Updated:", event.Key)
// this is an entry evicted event
case hazelcast.EntryEvicted:
fmt.Println("Entry Evicted:", event.Key)
// this is an entry loaded event
case hazelcast.EntryLoaded:
fmt.Println("Entry Loaded:", event.Key)
}
})
if err != nil {
log.Fatal(err)
}
// performing modifications on the map entries
key := strconv.Itoa(int(time.Now().Unix()))
if err := m.Set(ctx, key, "1"); err != nil {
log.Fatal(err)
}
if err := m.Set(ctx, key, "2"); err != nil {
log.Fatal(err)
}
if err := m.Delete(ctx, key); err != nil {
log.Fatal(err)
}
// you can use the subscriptionID later to remove the event listener.
if err := m.RemoveEntryListener(ctx, subscriptionID); err != nil {
log.Fatal(err)
}
}
func ExampleMap_AddListener() {
// error handling was omitted for brevity
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
m, err := client.GetMap(ctx, "somemap")
if err != nil {
log.Fatal(err)
}
subscriptionID, err := m.AddListener(ctx, hazelcast.MapListener{
EntryAdded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Added:", event.Key)
},
EntryUpdated: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Updated:", event.Key)
},
EntryRemoved: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Removed:", event.Key)
},
EntryEvicted: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Evicted:", event.Key)
},
EntryLoaded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Loaded:", event.Key)
},
}, true)
if err != nil {
log.Fatal(err)
}
// performing modifications on the map entries
key := strconv.Itoa(int(time.Now().Unix()))
if err := m.Set(ctx, key, "1"); err != nil {
log.Fatal(err)
}
if err := m.Set(ctx, key, "2"); err != nil {
log.Fatal(err)
}
if err := m.Delete(ctx, key); err != nil {
log.Fatal(err)
}
// you can use the subscriptionID later to remove the event listener.
if err := m.RemoveListener(ctx, subscriptionID); err != nil {
log.Fatal(err)
}
}
func ExampleMap_AddListenerWithKey() {
// error handling was omitted for brevity
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
m, err := client.GetMap(ctx, "somemap")
if err != nil {
log.Fatal(err)
}
key := strconv.Itoa(int(time.Now().Unix()))
subscriptionID, err := m.AddListenerWithKey(ctx, hazelcast.MapListener{
EntryAdded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Added:", event.Key)
},
EntryUpdated: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Updated:", event.Key)
},
EntryRemoved: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Removed:", event.Key)
},
EntryEvicted: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Evicted:", event.Key)
},
EntryLoaded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Loaded:", event.Key)
},
}, key, true)
if err != nil {
log.Fatal(err)
}
// performing modifications on the map entries
if err := m.Set(ctx, key, "1"); err != nil {
log.Fatal(err)
}
if err := m.Set(ctx, key, "2"); err != nil {
log.Fatal(err)
}
if err := m.Delete(ctx, key); err != nil {
log.Fatal(err)
}
// you can use the subscriptionID later to remove the event listener.
if err := m.RemoveListener(ctx, subscriptionID); err != nil {
log.Fatal(err)
}
}
func ExampleMap_AddListenerWithPredicate() {
// error handling was omitted for brevity
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
m, err := client.GetMap(ctx, "somemap")
if err != nil {
log.Fatal(err)
}
subscriptionID, err := m.AddListenerWithPredicate(ctx, hazelcast.MapListener{
EntryAdded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Added:", event.Key)
},
EntryUpdated: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Updated:", event.Key)
},
EntryRemoved: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Removed:", event.Key)
},
EntryEvicted: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Evicted:", event.Key)
},
EntryLoaded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Loaded:", event.Key)
},
}, predicate.True(), true)
if err != nil {
log.Fatal(err)
}
// performing modifications on the map entries
key := strconv.Itoa(int(time.Now().Unix()))
if err := m.Set(ctx, key, "1"); err != nil {
log.Fatal(err)
}
if err := m.Set(ctx, key, "2"); err != nil {
log.Fatal(err)
}
if err := m.Delete(ctx, key); err != nil {
log.Fatal(err)
}
// you can use the subscriptionID later to remove the event listener.
if err := m.RemoveListener(ctx, subscriptionID); err != nil {
log.Fatal(err)
}
}
func ExampleMap_AddListenerWithPredicateAndKey() {
// error handling was omitted for brevity
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
m, err := client.GetMap(ctx, "somemap")
if err != nil {
log.Fatal(err)
}
key := strconv.Itoa(int(time.Now().Unix()))
subscriptionID, err := m.AddListenerWithPredicateAndKey(ctx, hazelcast.MapListener{
EntryAdded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Added:", event.Key)
},
EntryUpdated: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Updated:", event.Key)
},
EntryRemoved: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Removed:", event.Key)
},
EntryEvicted: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Evicted:", event.Key)
},
EntryLoaded: func(event *hazelcast.EntryNotified) {
fmt.Println("Entry Loaded:", event.Key)
},
}, predicate.True(), key, true)
if err != nil {
log.Fatal(err)
}
// performing modifications on the map entries
if err := m.Set(ctx, key, "1"); err != nil {
log.Fatal(err)
}
if err := m.Set(ctx, key, "2"); err != nil {
log.Fatal(err)
}
if err := m.Delete(ctx, key); err != nil {
log.Fatal(err)
}
// you can use the subscriptionID later to remove the event listener.
if err := m.RemoveListener(ctx, subscriptionID); err != nil {
log.Fatal(err)
}
}
func ExampleMap_NewLockContext() {
// lockAndIncrement locks the given key, reads the value from it and sets back the incremented value.
lockAndIncrement := func(myMap *hazelcast.Map, key string, wg *sync.WaitGroup) {
// Signal completion before this goroutine exits.
defer wg.Done()
intValue := int64(0)
// Create a new unique lock context.
lockCtx := hazelcast.NewLockContext(context.Background())
// Lock the key.
// The key cannot be unlocked without the same lock context.
if err := myMap.Lock(lockCtx, key); err != nil {
panic(err)
}
// Remember to unlock the key, otherwise it won't be accessible elsewhere.
defer myMap.Unlock(lockCtx, key)
// The same lock context, or a derived one from that lock context must be used,
// otherwise the Get operation below will block.
v, err := myMap.Get(lockCtx, key)
if err != nil {
panic(err)
}
// If v is not nil, then there's already a value for the key.
if v != nil {
intValue = v.(int64)
}
// Increment and set the value back.
intValue++
// The same lock context, or a derived one from that lock context must be used,
// otherwise the Set operation below will block.
if err = myMap.Set(lockCtx, key, intValue); err != nil {
panic(err)
}
}
const goroutineCount = 100
const key = "counter"
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Get a random map.
myMap, err := client.GetMap(ctx, "map")
if err != nil {
log.Fatal(err)
}
// Lock and increment the value stored in key for goroutineCount times.
wg := &sync.WaitGroup{}
wg.Add(goroutineCount)
for i := 0; i < goroutineCount; i++ {
go lockAndIncrement(myMap, key, wg)
}
// Wait for all goroutines to complete.
wg.Wait()
// Retrieve the final value.
// A lock context is not needed, since the key is unlocked.
if lastValue, err := myMap.Get(context.Background(), key); err != nil {
panic(err)
} else {
fmt.Println("lastValue", lastValue)
}
client.Shutdown(ctx)
}
func ExampleQueue() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Get a random queue
q, err := client.GetQueue(ctx, "queue-1")
if err != nil {
log.Fatal(err)
}
// Add an item to the queue if space is available (non-blocking)
added, err := q.Add(ctx, "item 1")
if err != nil {
log.Fatal(err)
}
if added {
fmt.Println("Added item 1")
}
// Get the head of the queue if available and print item
item, err := q.Poll(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(item)
// Add an item waiting for capacity until timeout
added, err = q.AddWithTimeout(ctx, "item 2", 2*time.Second)
if err != nil {
log.Fatal(err)
}
if added {
fmt.Println("Added item 2")
}
// Wait indefinetely to add an item
err = q.Put(ctx, "item 3")
if err != nil {
log.Fatal(err)
}
// Wait indefintely to take the head and print item
item, err = q.Take(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(item)
// Shutdown client
client.Shutdown(ctx)
}
func ExampleReplicatedMap() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Get a random replicated map
replicatedMap, err := client.GetReplicatedMap(ctx, "replicated-map-1")
if err != nil {
log.Fatal(err)
}
// Populate map
replacedValue, err := replicatedMap.Put(ctx, "key", "value")
if err != nil {
log.Fatal(err)
}
fmt.Println(replacedValue)
// Get value and print
value, err := replicatedMap.Get(ctx, "key")
if err != nil {
log.Fatal(err)
}
fmt.Println(value)
// Shutdown client
client.Shutdown(ctx)
}
func ExampleTopic() {
// messageListener handles incoming messages to the topic
messageListener := func(event *hazelcast.MessagePublished) {
fmt.Println("Received message: ", event.Value)
}
messageCount := 10
// Start the client with defaults
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Get a random topic
rand.Seed(time.Now().Unix())
topicName := fmt.Sprintf("sample-%d", rand.Int())
topic, err := client.GetTopic(ctx, topicName)
if err != nil {
log.Fatal(err)
}
// Add a message listener to the topic
topic.AddMessageListener(ctx, messageListener)
// Publish messages to topic
for i := 0; i < messageCount; i++ {
topic.Publish(ctx, fmt.Sprintf("Message %d", i))
}
// Shutdown client
client.Shutdown(ctx)
}
func ExampleMap_GetEntrySetWithPredicate() {
// Start the client with defaults
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Get a random map
m, err := client.GetMap(ctx, "map-1")
if err != nil {
log.Fatal(err)
}
// Populate the map, error handling is omitted here for brevity
m.Put(ctx, "key-1", serialization.JSON(`{"property: 5}`))
m.Put(ctx, "key-2", serialization.JSON(`{"property": 10}`))
m.Put(ctx, "key-3", serialization.JSON(`{"property": 15}`))
// Filter the entries in the map based on a predicate and print those
pred := predicate.And(predicate.Less("property", 12), predicate.Greater("property", 8))
entries, err := m.GetEntrySetWithPredicate(ctx, pred)
if err != nil {
log.Fatal(err)
}
fmt.Println(entries)
// Shutdown client
client.Shutdown(ctx)
}
func ExampleList() {
ctx := context.TODO()
client, err := hazelcast.StartNewClient(ctx)
if err != nil {
log.Fatal(err)
}
// Get a random list
list, err := client.GetList(ctx, "list-1")
if err != nil {
log.Fatal(err)
}
// Get and print list size
size, err := list.Size(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(size)
// Add data, error handling is omitted here for brevity
list.Add(ctx, "Item 1")
list.Add(ctx, "Item 2")
// Get and print list size
size, err = list.Size(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(size)
// Shutdown client
client.Shutdown(ctx)
}