forked from sboesebeck/morphium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Morphium Documentation.html
3989 lines (3148 loc) · 186 KB
/
Morphium Documentation.html
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
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Morphium 4.2 Documentation</title>
</head>
<body>
<h1 id="morphium-documentation">Morphium Documentation</h1>
<div class="TOC">
<ul>
<li><a href="#morphium-documentation">Morphium Documentation</a>
<ul>
<li><a href="#what-is-morphium">What is <em>Morphium</em></a></li>
<li><a href="#about-this-document">About this document</a></li>
<li><a href="#using-morphium-as-a-messaging-system">Using <em>Morphium</em> as a messaging system</a>
<ul>
<li><a href="#why-morphium-messaging">why <em>Morphium</em> messaging</a></li>
<li><a href="#quick-start-messaging">Quick start Messaging</a></li>
<li><a href="#answering-messages">Answering messages</a></li>
<li><a href="#more-advanced-settings">more advanced settings</a>
<ul>
<li><a href="#custom-message-classes">Custom message classes</a></li>
<li><a href="#message-priorities">Message priorities</a></li>
<li><a href="#pausing-unpausing-of-messaging">Pausing / unpausing of messaging</a></li>
<li><a href="#multithreading-multimessage-processing">Multithreading / Multimessage
processing</a></li>
<li><a href="#custom-messagequeue-name">Custom MessageQueue name</a></li>
<li><a href="#jms-support">JMS Support</a></li>
</ul>
</li>
<li><a href="#examples">Examples</a>
<ul>
<li><a href="#simple-producer-consumer-setup">Simple producer consumer setup:</a></li>
<li><a href="#direct-messages">Direct messages</a></li>
<li><a href="#exclusive-broadcast-messages">Exclusive Broadcast messages</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#inmemory-driver">InMemory Driver</a>
<ul>
<li><a href="#how-to-use-the-inmemory-driver">how to use the inMemory Driver</a></li>
<li><a href="#dumping-inmemory-data">Dumping InMemory data</a></li>
</ul>
</li>
<li><a href="#morphium-pojo-mapping"><em>Morphium</em> POJO Mapping</a>
<ul>
<li><a href="#ideas-and-design-criteria">Ideas and design criteria</a></li>
<li><a href="#concepts">Concepts</a></li>
<li><a href="#advantages-features">Advantages / Features</a>
<ul>
<li><a href="#pojo-mapping">POJO Mapping</a></li>
<li><a href="#declarative-caching">Declarative caching</a></li>
<li><a href="#cache-synchronization">cache synchronization</a></li>
<li><a href="#auto-versioning">Auto-Versioning</a></li>
<li><a href="#type-ids">Type IDs</a></li>
<li><a href="#sequences">Sequences</a></li>
<li><a href="#transparent-encryption-of-values">transparent encryption of values</a>
</li>
<li><a href="#binary-serialization">binary serialization</a></li>
<li><a href="#complex-data-structures">complex data structures</a></li>
<li><a href="#support-for-mapreduce">Support for MapReduce</a></li>
<li><a href="#automatic-retries-on-error">automatic retries on error</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#configuring-morphium-morphiumconfig">configuring <em>Morphium</em>:
<code>MorphiumConfig</code></a>
<ul>
<li><a href="#different-sources">Different sources</a>
<ul>
<li><a href="#json">Json</a></li>
<li><a href="#properties">Properties</a></li>
<li><a href="#java-code">Java-Code</a></li>
</ul>
</li>
<li><a href="#configuration-options">Configuration Options</a></li>
<li><a href="#authentication">authentication</a>
<ul>
<li><a href="#corresponding-mongod-config">corresponding MongoD Config</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#entity-definition">Entity Definition</a>
<ul>
<li><a href="#indexes">indexes</a>
<ul>
<li><a href="#text-indexes">Text indexes</a></li>
</ul>
</li>
<li><a href="#capped-collections">capped collections</a></li>
</ul>
</li>
<li><a href="#querying">Querying</a>
<ul>
<li><a href="#simple-queries">Simple queries</a></li>
<li><a href="#or-queries">Or Queries</a>
<ul>
<li><a href="#limitations">Limitations</a></li>
</ul>
</li>
<li><a href="#the-iterator">the Iterator</a></li>
</ul>
</li>
<li><a href="#storing">Storing</a>
<ul>
<li><a href="#names-of-entities-and-fields">Names of entities and fields</a>
<ul>
<li><a href="#camelcase-conversion">CamelCase conversion</a></li>
<li><a href="#using-the-full-qualified-classname">using the full qualified classname</a>
</li>
<li><a href="#specifying-a-collection-fieldname">Specifying a collection / fieldname</a>
</li>
<li><a href="#accessing-fields">Accessing fields</a></li>
<li><a href="#using-nameproviders">Using NameProviders</a></li>
<li><a href="#examples">examples</a></li>
</ul>
</li>
<li><a href="#automatic-values">Automatic values</a></li>
</ul>
</li>
<li><a href="#asynchronous-api">Asynchronous API</a>
<ul>
<li><a href="#difference-asynchronous-write-write-buffer">Difference asynchronous write / write
buffer</a></li>
</ul>
</li>
<li><a href="#validation-support">Validation support</a></li>
<li><a href="#annotations">Annotations</a>
<ul>
<li><a href="#entity">Entity</a></li>
<li><a href="#embedded">Embedded</a></li>
<li><a href="#asyncwrites">AsyncWrites</a></li>
<li><a href="#nocache">NoCache</a></li>
<li><a href="#capped">Capped</a></li>
<li><a href="#collation">Collation</a></li>
<li><a href="#additionaldata">AdditionalData</a></li>
<li><a href="#aliases">Aliases</a></li>
<li><a href="#creationtime">CreationTime</a></li>
<li><a href="#lastaccess">LastAccess</a></li>
<li><a href="#lastchange">LastChange</a></li>
<li><a href="#defaultreadpreference">DefaultReadPreference</a></li>
<li><a href="#id">Id</a></li>
<li><a href="#index">Index</a></li>
<li><a href="#ignorefields">IgnoreFields</a></li>
<li><a href="#limittofields">LimitToFields</a></li>
<li><a href="#property">Property</a></li>
<li><a href="#readonly">ReadOnly</a></li>
<li><a href="#version">Version</a></li>
<li><a href="#reference">Reference</a>
<ul>
<li><a href="#lazy-loaded-references">Lazy Loaded references</a></li>
</ul>
</li>
<li><a href="#transient">Transient</a></li>
<li><a href="#cache">Cache</a></li>
<li><a href="#encrypted">Encrypted</a></li>
<li><a href="#useifnull">UseIfNull</a></li>
<li><a href="#lifecycle">LifeCycle</a></li>
<li><a href="#version">Version</a></li>
<li><a href="#writesafety">WriteSafety</a>
<ul>
<li><a href="#cluster-awareness">Cluster awareness</a></li>
</ul>
</li>
<li><a href="#annotation-inheritance">Annotation Inheritance</a></li>
<li><a href="#implementation">Implementation</a></li>
</ul>
</li>
<li><a href="#changestream-support">Changestream support</a>
<ul>
<li><a href="#partial-updating">partial updating</a></li>
<li><a href="#bulkrequest-support">BulkRequest support</a></li>
<li><a href="#transaction-support">Transaction support</a></li>
</ul>
</li>
<li><a href="#listeners-in-morphium">Listeners in <em>Morphium</em></a>
<ul>
<li><a href="#replicasetstatuslistener">ReplicasetStatusListener</a></li>
</ul>
</li>
<li><a href="#cachelistener">CacheListener</a>
<ul>
<li><a href="#cachesynclistener">CacheSyncListener</a></li>
<li><a href="#changestreamlistener">ChangeStreamListener</a></li>
<li><a href="#messagelistener">MessageListener</a></li>
<li><a href="#morphiumstoragelistener">MorphiumStorageListener</a></li>
<li><a href="#oploglistener">OplogListener</a></li>
<li><a href="#profiling-listener">Profiling Listener</a></li>
</ul>
</li>
<li><a href="#the-aggregation-framework">The Aggregation Framework</a>
<ul>
<li><a href="#aggregation-expressions">Aggregation Expressions</a></li>
</ul>
</li>
<li><a href="#additional-information-sources">Additional information sources</a></li>
<li><a href="#code-examples">Code Examples</a>
<ul>
<li><a href="#cache-synchronization">Cache Synchronization</a></li>
<li><a href="#geo-spacial-search">Geo Spacial Search</a></li>
<li><a href="#iterator">Iterator</a></li>
<li><a href="#asynchronous-read">Asynchronous Read</a></li>
<li><a href="#asynchronous-write">Asynchronous Write</a></li>
</ul>
</li>
<li><a href="#disclaimer">Disclaimer</a></li>
</ul>
</li>
</ul>
</div>
<h2 id="what-is-morphium">What is <em>Morphium</em></h2>
<p><em>Morphium</em> started as a feature rich access layer and POJO mapper for MongoDB in java. It was built with speed
and flexibility in mind. So it supported cluster aware caching out of the box, lazy loading references and much
more. The POJO Mapping is the <em>core</em> of <em>Morphium</em>, all other features were built around that. It
makes accessing MongoDB easy, supports all great features of MongoDB and adds some more.</p>
<p>But with time, the MongoDB based messaging became one of the most popular features in <em>Morphium</em>. It is fast,
reliable, customisable and stable. </p>
<h2 id="about-this-document">About this document</h2>
<p>This document is a documentation for <em>Morphium</em> in the current (4.2) version. It would be best, if you had a
basic understanding of MongoDB and a good knowledge on <em>Morphium</em>. If you want to know about MongoDB's
features, that <em>Morphium</em> implements here, have a look at the official MongoDB pages and the documentation
there.</p>
<p>This documentation covers all features <em>Morphium</em> has to offer.</p>
<p>Later in this document there are chapters about the POJO mapping, querying data and using the aggregation framework.
Also a chapter about the InMemory driver, which is quite useful for testing. But let's start with the messaging
subsystem first. </p>
<h2 id="using-morphium-as-a-messaging-system">Using <em>Morphium</em> as a messaging system</h2>
<p><em>Morphium</em> itself is simple to use, easy to customise to your needs and was built for high performance and
scalability. The messaging system is no different. It relies on the <code>watch</code> functionality, that MongoDB
offers since V3.6 (you can also use messaging with older versions of MongoDB, but it will result in polling for new
messages). With that feature, the messages are <em>pushed</em> to all listeners. This makes it a very efficient
messaging system based on MongoDB.</p>
<h3 id="why-morphium-messaging">why <em>Morphium</em> messaging</h3>
<p>There is a ton of messaging solutions out there. All of them have their advantages and offer lots of features. But
only few of them offer the things that <em>Morphium</em> has:</p>
<ul>
<li>the message queue can easily be inspected and you can use mongo search queries to find the messages you are
looking for<sup><a class="footnote" href="#fn1-10247" id="fnr1-10247" title="see footnote">1</a></sup></li>
<li>the message queue can be altered (update single messages with ease, delete messages or just <em>add</em> new
messages)
</li>
<li>Possibility to broadcast messages, that are only processed by one client max (Exclusive Messages). With V4.2 of
<em>Morphium</em> this also works with a group of recipients.
</li>
<li>Messaging is multithreaded and thread safe</li>
<li>pausing and unpausing of message processing without data loss</li>
<li><em>Morphium</em> messaging picks up all pending messages on startup - no data loss.</li>
<li>no need to install additional servers or provide separate infrastructure. Just use your MongoDB you likely
already have in place.
</li>
</ul>
<p>There are people out there using <em>Morphium</em> and its messaging for production grade development. For example <a
href="https://www.genios.de">Genios.de</a> uses Morphium messaging to power a microservice architecture with an
enterprise message bus.</p>
<h3 id="quick-start-messaging">Quick start Messaging</h3>
<pre><code class="java">Morphium m=new Morphium();
Messaging messaging=new Messaging(m);
messaging.addMessageListener((messaging, msg) -> {
log.info("Got message!");
return null; //not sending an answer
});
</code></pre>
<p>This is a simple example of how to implement a message consumer. This consumer listens to <em>all</em> incoming
messages, regardless of name. </p>
<p>Messages do have some fields, that you might want to use for your purpose. But you can create your own message type
as well (see below). the Msg-Class defines those properties:</p>
<ul>
<li><code>name</code> the name of the Message - you can define listeners only listening to messages of a specific
name using <code>addListenerForMessageNamed</code>. Similar to a <em>topic</em> in other messaging systems
</li>
<li><code>msg</code>: String message</li>
<li><code>value</code>: well - a String value</li>
<li><code>mapValue</code>: for more complex use cases where you need to send more information</li>
<li><code>additional</code>: list value - used for more complex use cases</li>
<li>all messages do store some values for the processing algorithm, like <code>processed_by</code>, <code>in_answer_to</code>,
<code>timestamp</code> etc.
</li>
</ul>
<p>So if you want to send a Message, that is also simple:</p>
<pre><code class="java">messaging.queueMessage(new Msg("name","A message","the value");
</code></pre>
<p>queueMessage is running asynchronously, which means, that the message is <em>not</em> directly stored. If you need
more speed and shorter reaction time, you should use <code>sendMessage</code> instead (directly storing message to
mongo).</p>
<h3 id="answering-messages">Answering messages</h3>
<p><em>Morphium</em> is able to answer any message for you. Your listener implementation only needs to return an
instance of the <code>Msg</code>-Class(fn). This will then be sent back to the sender as an answer. </p>
<p>When sending a message, you also may wait for the incoming answer. The Messaging class offers a method for that
purpose:</p>
<pre><code>//new messaging instance with polling frequency of 100ms, not multithreaded
//polling only used in case of non-Replicaset connections and in some
//cases like unpausing to find pending messages
Messaging sender = new Messaging(_Morphium_, 100, false);
sender.start();
gotMessage1 = false;
gotMessage2 = false;
gotMessage3 = false;
gotMessage4 = false;
Messaging m1 = new Messaging(_Morphium_, 100, false);
m1.addMessageListener((msg, m) -> {
gotMessage1 = true;
return new Msg(m.getName(), "got message", "value", 5000);
});
m1.start();
Thread.sleep(2500);
Msg answer = sender.sendAndAwaitFirstAnswer(new Msg("test", "Sender", "sent", 15000), 15000);
assert (answer != null);
assert (answer.getName().equals("test"));
assert (answer.getInAnswerTo() != null);
assert (answer.getRecipient() != null);
assert (answer.getMsg().equals("got message"));
m1.terminate();
sender.terminate();
</code></pre>
<p>As the whole communication is asynchronous, you will have to specify a timeout after wich the wait for answer will be
aborted with an exception. And, there might be more than one answers to the same message, hence you will only get
the first one.</p>
<p>in the above example, the timeout for the answer is set to 15s (and the TTL for messages also).</p>
<h3 id="more-advanced-settings">more advanced settings</h3>
<h4 id="custom-message-classes">Custom message classes</h4>
<p>As mentioned above, you can define your own Message-Class to be send back and forth. This class just needs to extend
the standard <code>Msg</code>-Class. When adding a listener to messaging, you have the option to also use generics
to specify the Msg-Type you want to use. </p>
<h4 id="message-priorities">Message priorities</h4>
<p>Every message does have a priority field. That is used for giving queued messages precedence over others. The
priority could be changed <em>after</em> a message is queued directly in MongoDB (or using <em>Morphium</em>).</p>
<p>But as the messaging is built on pushing of messages, when is the priority field used? Several cases:</p>
<ul>
<li>when starting up messaging. When starting Messaging, the system does look for pending messages in the queue,
highes prio is used first
</li>
<li>when unpausing a messaging instance, it will look for any messages in the queue and will process them according
to their priority.
</li>
</ul>
<h4 id="pausing-unpausing-of-messaging">Pausing / unpausing of messaging</h4>
<p>In some cases it might be necessary to pause message processing for a time. That might be the case, if the message is
triggering some long running task or so. If so, it would be good not to process any additional messages (at least of
that type).</p>
<p>You can call <code>messaging.pauseProcessingOfMessagesNamed</code> to <em>not</em> process any more messages of a
certain type.</p>
<p><em>Attention</em>: if you have long running tasks triggered by messages, you should pause processing in the
onMessage method and unpause it when finished.</p>
<h4 id="multithreading-multimessage-processing">Multithreading / Multimessage processing</h4>
<p>When instantiating Messaging, you can specify two booleans:</p>
<ul>
<li>multithreading: if true, every incoming message will be processed in an own thread (Executor - see
MorphiumConfig below). That means, several messages can be processed in parallel
</li>
<li><p>processMultiple: this setting is only important in case of startup or unpausing(fn). If true, messaging will
lock all(fn) messages available for this listener and process them one by one (or in parallel if multithreading
is enabled). </p>
These settings are influenced by other settings:
</li>
<li><code>messagingWindowSize</code> in MorphiumConfig or as constructor parameter / setter in Messaging: this
defines how many messages are marked for processing at once. Those might be processed in parallel (depending
whether <code>processMultiple</code> is true, and the executor configuration, how many threads can be run in
parallel)
</li>
<li><code>useChangeStream</code> in Messaging. Usually messaging determines by the cluster status, whether or not to
use the changestream or not. If in a cluster, use it, if not use polling. But if you explicitly want to use
polling, you can set this value to <code>false</code>. The advantage here might be, that the messages are
processed by priority with every poll. This might be useful depending on your usecase. If this is set to false
(or you are connected to an single instance), the <code>pause</code> configuration option (aka polling
frequency) in Messaging will determine how fast your messages can be consumed. <strong>Attention</strong> high
polling frequency (a low <code>pause</code> value), will increase the load on MongoDB.
</li>
<li><code>ThreadPoolMessagingCoreSize</code> in MorphiumConfig: If you define messaging to be multithreaded it will
spawn a new thread with each incoming message. this is the core size of the corresponding thread pool. If your
messaging instance is not configured for multithreading, this setting is not used.
</li>
<li><code>ThreadPoolMessagingMaxSize</code>: max size of the thread pool. similar to above.</li>
<li><p><code>ThreadPoolMessagingKeepAliveTime</code>: time of threads to live in ms</p>
some examples to clarify that:
</li>
<li>your messaging instance is configured for multithreaded processing, multiple processing, having a <code>windowSize</code>
of 100 and a <code>ThreadPoolMessagingMaxSize</code> of 10, then there will be 100 messages in queue marked for
being processed by this specific messaging instance, but only 10 will be processed in parallel.
</li>
<li>multithreaded processing is false, then the <code>windowSize</code> determines how many messages are marked for
being processed, but are only processed one by one
</li>
<li>multithreaded processing and multiple processing is false, then only one message is marked for being processed
at a time. As soon as this processing is finished, the next message is being taken.
</li>
<li>having <code>multithreaded</code> set to true and <code>processMultiple</code> set to false would result in
running each message processing in one separate thread, but only one at a time. This is very similar to having
<code>multithreaded</code> and <code>process multiple</code> both set to false.
</li>
</ul>
<h4 id="custom-messagequeue-name">Custom MessageQueue name</h4>
<p>When creating a Messaging instance, you can set a collection name to use. This could be compared to having a separate
message queue in the system. Messages sent to one queue are not being registered by another.</p>
<h4 id="jms-support">JMS Support</h4>
<p><em>Morphium</em> messaging also implements the standard JMS-API to a certain extend and can be used this way. Please
keep in mind that JMS does not support most of the features, <em>Morphium</em> messaging offers, and that the JMS
implementation does not cover 100% of the JMS API yet:</p>
<pre><code class="java">@Test
public void basicSendReceiveTest() throws Exception {
JMSConnectionFactory factory = new JMSConnectionFactory(morphium);
JMSContext ctx1 = factory.createContext();
JMSContext ctx2 = factory.createContext();
JMSProducer pr1 = ctx1.createProducer();
Topic dest = new JMSTopic("test1");
JMSConsumer con = ctx2.createConsumer(dest);
con.setMessageListener(message -> log.info("Got Message!"));
Thread.sleep(1000);
pr1.send(dest, "A test");
ctx1.close();
ctx2.close();
}
@Test
public void synchronousSendRecieveTest() throws Exception {
JMSConnectionFactory factory = new JMSConnectionFactory(morphium);
JMSContext ctx1 = factory.createContext();
JMSContext ctx2 = factory.createContext();
JMSProducer pr1 = ctx1.createProducer();
Topic dest = new JMSTopic("test1");
JMSConsumer con = ctx2.createConsumer(dest);
final Map<String, Object> exchange = new ConcurrentHashMap<>();
Thread senderThread = new Thread(() -> {
JMSTextMessage message = new JMSTextMessage();
try {
message.setText("Test");
} catch (JMSException e) {
e.printStackTrace();
}
pr1.send(dest, message);
log.info("Sent out message");
exchange.put("sent", true);
});
Thread receiverThread = new Thread(() -> {
log.info("Receiving...");
Message msg = con.receive();
log.info("Got incoming message");
exchange.put("received", true);
});
receiverThread.start();
senderThread.start();
Thread.sleep(5000);
assert (exchange.get("sent") != null);
assert (exchange.get("received") != null);
}
</code></pre>
<p><strong>Caveats:</strong></p>
<p>The JMS Implementation uses the answering mechanism for acknowledging incoming messages. This makes JMS more or less
half as fast as the direct usage of <em>Morphium</em> messaging. </p>
<p>Also, the implementation is very basic at the moment. A lot of methods lack implementation<sup><a class="footnote"
href="#fn2-10247"
id="fnr2-10247"
title="see footnote">2</a></sup>.
If you notice some missing functionality, just open an issue at <a href="https://github.com/sboesebeck/morphium">github</a>.
</p>
<p>Because of the JMS Implementation being very basic at the moment, it should not be considered production ready!</p>
<h3 id="examples">Examples</h3>
<h4 id="simple-producer-consumer-setup">Simple producer consumer setup:</h4>
<pre><code class="java">Morphium m=new Morphium(config);
// create messaging instance with default settings, meaning
// no multithreading, windowSize of 100, processMultiple false
Messaging producer=new Messaging(m);
producer.queueMessage(new Msg("name","a message","a value"));
the receiver needs to connect to the same mongo and the same database:
Morphium m=new Morphium(config);
Messaging consumer=new Messaging(m);
consumer.start(); //needed for receiving messages
consumer.addMessageListener((messaging, msg) -> {
//Incoming message
System.out.println("Got a message of name "+msg.getName());
return null; //no answer to send back
});
</code></pre>
<p>you can also register listeners only for specific messages:consumer.start(); //needed for receiving messages</p>
<pre><code class="java">consumer.addListenerForMessageNamed("name",(messaging, msg) -> {
//Incoming message, is always named "name"
System.out.println("Got value: "+msg.getValue());
Msg answer=new Msg(msg.getName(),"answer","the answerValue");
return answer; //no answer to send back
});
</code></pre>
<p><strong>Attention</strong>: the producer will only be able to process incoming messages, if <code>start()</code> was
called!</p>
<p>The message sent there was a broadcast message. All registered listeners will receive that message and will process
it!</p>
<h4 id="direct-messages">Direct messages</h4>
<p>In order to send a message directly to a specific messaging instance, you need to get the unique ID of it. This id is
add as sender to any message. </p>
<pre><code>Msg m=new Msg("Name","Message","value");
m.addRecipient(messaging1.getId());
//you could add more recipients if necessary
</code></pre>
<p><em>Background</em>: This is used to send answers back to the sender. If you return a message instance in <code>onMessage</code>,
this message will be sent directly back to the sender.</p>
<p>You can add as many recipients as needed, if no recipient is defined, the message by default is sent to all
listeners.</p>
<h4 id="exclusive-broadcast-messages">Exclusive Broadcast messages</h4>
<p>Broadcast messages are fine for informing all listeners about something. But for some more complex scenarios, you
would need a way to queue a message, and have only one listener process it - no matter which one (load
balancing?)</p>
<p><em>Morphium</em> supports this kind of messages, it is called "exclusive broadcast". This way, you can
easily scale up by just adding listener instances.</p>
<p>Sending a exclusive broadcast message is simple:</p>
<pre><code> Msg m=new Message("exclusive","The message","and value");
m.setExclusive(true);
messaging.queueMessage(m);
</code></pre>
<p>The listener only need to implement the standard <code>onMessage</code>-Method to get this message. Due to some
sophisticated locking of messages, <em>Morphium</em> makes this message exclusive - which means, it is only
processed once!</p>
<p>Since <em>Morphium</em> V4.2 it is also possible to send an exclusive message to certain recipients<sup><a
class="footnote" href="#fn3-10247" id="fnr3-10247" title="see footnote">3</a></sup>. </p>
<p>The behaviour is the same: the message will only be processed by <em>one</em> of the specified recipients, whereas it
will be processed by <em>all</em> recipients, if not exclusive.</p>
<h2 id="inmemory-driver">InMemory Driver</h2>
<p>One main purpose of the <code>InMemoryDriver</code> is to be able to do testing without having a MongoDB installed.
The InMemoryDriver adds the opportunity to let all MongoDB-code run in Memory, with a couple of exceptions</p>
<ul>
<li>unfortunately, the InMemoryDriver cannot do aggregations. It will throw an Exception, when trying Aggregations
with this driver
</li>
<li>the inMemoryDriver is also not capable to return cluster information, run mongodb commands</li>
<li>it does not support spacial indexes or queries</li>
</ul>
<p>If you want to mock those things in testing, you need to:</p>
<ol>
<li>create a subclass of the inMemoryDriver</li>
<li>override the corresponding method, for example <code>aggregate()</code> for aggregation and return the properly
mocked data
</li>
<li>set the driver back to default in order to have it work</li>
</ol>
<pre><code class="java"> @Test
public void mockAggregation() throws Exception{
MorphiumDriver original=morphium.getDriver();
morphium.setDriver(new InMemoryDriver(){
@Override
public List<Map<String, Object>> aggregate(String db, String collection, List<Map<String, Object>> pipeline, boolean explain, boolean allowDiskUse, Collation collation, ReadPreference readPreference) throws MorphiumDriverException {
return Arrays.asList(Utils.getMap("MockedData",123.0d));
}
});
Aggregator<UncachedObject, Map> agg = morphium.createAggregator(UncachedObject.class, Map.class);
//...
assert(agg.aggregate().get(0).get("MockedData").equals(123.0d)); //checking mocked data
morphium.getDriver().close();
morphium.setDriver(original);
}
</code></pre>
<h3 id="how-to-use-the-inmemory-driver">how to use the inMemory Driver</h3>
<p>you just need to set the Driver properly in your <em>Morphium</em> configuration. </p>
<pre><code> MorphiumConfig cfg = new MorphiumConfig();
cfg.addHostToSeed("inMem");
cfg.setDatabase("test");
cfg.setDriverClass(InMemoryDriver.class.getName());
cfg.setReplicasetMonitoring(false);
morphium = new Morphium(cfg);
</code></pre>
<p>Of course, the <em>InMemDriver</em> does not need hosts to connect to, but for compatibility reasons, you need to add
at least one host (although it will be ignored).</p>
<p>You can also set the Driver in the settings, e.g. in properties:</p>
<pre><code>morphium.driverClass = "de.caluga.morphium.driver.inmem.InMemoryDriver"
</code></pre>
<p>After that initialisation you can use this <em>Morphium</em> instance as always, except that it will "persist"
data only in Memory.</p>
<h3 id="dumping-inmemory-data">Dumping InMemory data</h3>
<p>As in memory storage is by definition not lasting, it might be a good idea to store your data onto disk for later
use. The InMemoryDriver does support that:</p>
<pre><code class="java"> @Test
public void driverDumpTest() throws Exception {
for (int i = 0; i < 100; i++) {
UncachedObject e = new UncachedObject();
e.setCounter(i);
e.setValue("value" + i);
e.setIntData(new int[]{i, i + 1, i + 2});
e.setDval(42.00001);
e.setBinaryData(new byte[]{1, 2, 3, 4, 5});
morphium.store(e);
ComplexObject o = new ComplexObject();
o.setEinText("A text " + i);
o.setEmbed(new EmbeddedObject("emb", "v1", System.currentTimeMillis()));
o.setRef(e);
morphium.store(o);
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
InMemoryDriver driver = (InMemoryDriver) morphium.getDriver();
driver.dump(morphium, morphium.getDriver().listDatabases().get(0), bout);
log.info("database dump is " + bout.size());
driver.close();
driver.connect();
driver.restore(new ByteArrayInputStream(bout.toByteArray()));
assert (morphium.createQueryFor(UncachedObject.class).countAll() == 100);
assert (morphium.createQueryFor(ComplexObject.class).countAll() == 100);
for (ComplexObject co : morphium.createQueryFor(ComplexObject.class).asList()) {
assert (co.getEinText() != null);
assert (co.getRef() != null);
}
}
</code></pre>
<p>In this example, data is stored to a binary stream, which could also be stored to disk somewhere.</p>
<p>But you can also create a dump in <em>JSON</em> format, which makes it easier to edit and maybe to create from
scratch:</p>
<pre><code class="java">
@Test
public void jsonDumpTest() throws Exception {
MorphiumTypeMapper<ObjectId> mapper = new MorphiumTypeMapper<ObjectId>() {
@Override
public Object marshall(ObjectId o) {
Map<String, String> m = new HashMap<>();
m.put("value", o.toHexString());
m.put("class_name", o.getClass().getName());
return m;
}
@Override
public ObjectId unmarshall(Object d) {
return new ObjectId(((Map) d).get("value").toString());
}
};
morphium.getMapper().registerCustomMapperFor(ObjectId.class, mapper);
for (int i = 0; i < 10; i++) {
UncachedObject e = new UncachedObject();
e.setCounter(i);
e.setValue("value" + i);
morphium.store(e);
}
ExportContainer cnt = new ExportContainer();
cnt.created = System.currentTimeMillis();
cnt.data = ((InMemoryDriver) morphium.getDriver()).getDatabase(morphium.getDriver().listDatabases().get(0));
Map<String, Object> s = morphium.getMapper().serialize(cnt);
System.out.println(Utils.toJsonString(s));
morphium.dropCollection(UncachedObject.class);
ExportContainer ex = morphium.getMapper().deserialize(ExportContainer.class, Utils.toJsonString(s));
assert (ex != null);
((InMemoryDriver) morphium.getDriver()).setDatabase(morphium.getDriver().listDatabases().get(0), ex.data);
List<UncachedObject> result = morphium.createQueryFor(UncachedObject.class).asList();
assert (result.size() == 10);
assert (result.get(1).getCounter() == 1);
}
@Entity
public static class ExportContainer {
@Id
public Long created;
public Map<String, List<Map<String, Object>>> data;
}
</code></pre>
<p>The JSON output of this little dump looks like this:</p>
<pre><code class="json">{
"_id" : 1599853076411,
"data" : {
"uncached_object_0" : [
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b51"
},
"counter" : 0,
"dval" : 0,
"value" : "value0"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b53"
},
"counter" : 1,
"dval" : 0,
"value" : "value1"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b55"
},
"counter" : 2,
"dval" : 0,
"value" : "value2"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b57"
},
"counter" : 3,
"dval" : 0,
"value" : "value3"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b59"
},
"counter" : 4,
"dval" : 0,
"value" : "value4"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b5b"
},
"counter" : 5,
"dval" : 0,
"value" : "value5"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b5d"
},
"counter" : 6,
"dval" : 0,
"value" : "value6"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b5f"
},
"counter" : 7,
"dval" : 0,
"value" : "value7"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b61"
},
"counter" : 8,
"dval" : 0,
"value" : "value8"
},
{
"_id" : {
"class_name" : "org.bson.types.ObjectId",
"value" : "5f5bd214f8fd82e792ef3b63"
},
"counter" : 9,
"dval" : 0,
"value" : "value9"
}
]
}
}
</code></pre>
<h2 id="morphium-pojo-mapping"><em>Morphium</em> POJO Mapping</h2>
<h3 id="ideas-and-design-criteria">Ideas and design criteria</h3>
<p>In the early days of MongoDB there were not many POJO mapping libraries available. One was called <em>morphia</em>.
Unfortunately we had a lot of problems adapting this to our needs. </p>
<p>Hence we built <strong>Morphium</strong> and we named it similar to <em>morphia</em> to show where the initial idea
came from.</p>
<p><em>Morphium</em> is built with flexibility, thread safety, performance and cluster awareness in mind. </p>
<ul>
<li>flexibility: it is possible to exchange most of the internal implementations of <em>Morphium</em>. You could
have your own Driver class for connecting to MongoDB(fn) or have a custom implementation for the query
processing.
</li>
<li>thread safety: all aspects of <em>Morphium</em> were tested multithreaded so that it can be used in production
</li>
<li>performance: one of the main goals of <em>Morphium</em> was to improve performance. The Object Mapping in use is
a custom implementation that was built especially for <em>Morphium</em>, is very fast and to improve speed even
further, caching is part of the core features of <em>Morphium</em></li>
<li>cluster awareness: this is essential nowadays for high availability or just mere speed. _Morphium_s caches are
all cluster aware which means you will not end up with dirty reads in a clustered environment when using <em>Morphium</em>(fn)
</li>
<li>independent from mongoDB Driver: <em>Morphium</em> does not have a direct dependency on the mongoDB java driver,
instead it considers it to be provided. This means, you can have a different version of the driver in use than
the one <em>Morphium</em> was last tested with (you do not need the latest and grates, usually it is backward
compatible). In addition to that, <em>Morphium</em> does not directly use MongoDB or BSON classes but offers its
own implementation. For example the <code>MorphiumId</code>, wich is a drop in replacement for
<code>ObjectId</code>.
</li>
</ul>
<h3 id="concepts">Concepts</h3>
<p><em><em>Morphium</em></em> is built to be very flexible and can be used in almost any environment. So the
architecture needs to be flexible and sustainable at the same time. Hence it's possible to use your own
implementation for the cache if you want to.</p>
<p>There are four major components of <em><em>Morphium</em></em>:</p>
<ol>
<li>the <em><em>Morphium</em></em> Instance: This is you main entry point for interaction with Mongo. Here you
create Queries and you write data to mongo. All writes will then be forwarded to the configured Writer
implementation, all reads are handled by the Query-Object
</li>
<li>Query-Object: you need a query object to do reads from mongo. This is usually created by using <code>_Morphium_.createQueryFor(Class<T>
cls)</code>. With a Query, you can easily get data from database or have some things changed (update) and alike.
</li>
<li>the Cache: For every request that should be sent to mongo, <em><em>Morphium</em></em> checks first, whether this
collection is to be cached and if there is already a result being stored for the corresponding request.
</li>
<li>The Writers: there are 3 different types of writers in <em><em>Morphium</em></em>: The Default Writer (<code>_Morphium_Writer</code>)
- writes directly to database, waiting for the response, the BufferedWriter (<code>BufferedWriter</code>) - does
not write directly. All writes are stored in a buffer which is then processed as a bulk. The last type of writer
ist the asynchronous writer (<code>AsyncWriter</code>) which is similar to the buffered one, but starts writing
immediately - only asynchronous. <em><em>Morphium</em></em> decides which writer to use depending on the
configuration and the annotations of the given Entities. But you can <em>always</em> use asynchronous calls just
by adding a<code>AsyncCallback</code> implementation to your request.
</li>
</ol>
<p>Simple rule when using <em><em>Morphium</em></em>: You want to read -> Use the Query-Object. You want to write:
Use the <em><em>Morphium</em></em> Object.</p>
<p>There are some additional features built upon this architecture:</p>
<ul>
<li>messaging: <em><em>Morphium</em></em> has its own production grade messaging system. Its has a lot of features,
that are unique for a messaging system.
</li>
<li>cache synchronization: Synchronize caches in a clustered environment. Uses messaging.</li>
<li>custom mappers - you can tell <em><em>Morphium</em></em> how to map a certain type from and to MongoDB. For
example there is a "custom" mapper implementation for mapping <code>BigInteger</code> instances to
MongoDB.
</li>
<li>every one of those implementations can be changed: it is possible to set the class name for the <code>BufferedWriter</code>
to a custom built one (in <code>MorphiumConfig</code>). Also you could replace the object mapper with your own
implementation by implementing the <code>ObjectMapper</code> interface and telling <em>Morphium</em> which class
to use instead. In short, these things can be changed in <em>Morphium</em> / MorphiumConfig:
<ul>
<li>MorphiumCache</li>
<li>ObjectMapper</li>
<li>Query</li>
<li>Field</li>
<li>QueryFactory</li>
<li>Aggregator</li>
<li>AggregatorFactory</li>
<li>MorphiumDriver (> V3.0, for connecting to MongoDB or any other data source if you want to. For
example, there is an In-Memory-Driver you might want to use for testing. As an example, there is also an
InfluxDB-Driver available.)
</li>
</ul>
</li>
<li>Object Mapping from and to Strings (using the object mapper) and JSON.</li>
<li>full support for the Aggregation Framework</li>
<li>Transaction support (for supporting MongoDB versions)</li>
<li>Automatic encryption of fields (this is a re-implementation of the MongoDB enterprise feature in pure java -
works declarative)
</li>
</ul>