-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathprojections.html
More file actions
352 lines (313 loc) · 15.8 KB
/
Copy pathprojections.html
File metadata and controls
352 lines (313 loc) · 15.8 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
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<title>Projections · Thoth</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content='Thoth doc'/>
<link href="https://fonts.googleapis.com/css?family=Roboto:100normal,100italic,300normal,300italic,400normal,400italic,500normal,500italic,700normal,700italic,900normal,900italicc" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../lib/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../js/page.js"></script>
<script type="text/javascript" src="../js/groups.js"></script>
<link rel="stylesheet" type="text/css" href="../lib/normalize.css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="../lib/foundation/dist/foundation.min.css"/>
<link rel="stylesheet" type="text/css" href="../css/page.css"/>
<!--
<link rel="shortcut icon" href="../images/favicon.ico" />
-->
</head>
<body>
<div class="off-canvas-wrapper">
<div class="off-canvas-wrapper-inner" data-off-canvas-wrapper>
<div class="off-canvas position-left" id="off-canvas-menu" data-off-canvas>
<nav class="off-canvas-nav">
<div class="nav-home">
<a href="../index.html" >
<span class="home-icon">⌂</span>Thoth
</a>
<div class="version-number">
1.1.4*
</div>
</div>
<select class="supergroup" name="Language"><option class="group" value="group-java">Java</option></select>
<div class="nav-toc">
<ul>
<li><a href="../technical-considerations.html" class="page">Technical considerations</a></li>
<li><a href="../banking.html" class="page">In memory example</a></li>
<li><a href="../standard/index.html" class="page">Standard JOOQ/Kafka implementation</a>
<ul>
<li><a href="../standard/banking-real-life.html" class="page">Postgres Kafka event sourcing</a></li>
<li><a href="../standard/projections.html" class="active page">Projections</a></li>
</ul></li>
<li><a href="../database-configuration.html" class="page">Database configuration</a></li>
<li><a href="../advanced/index.html" class="page">Advanced use cases</a>
<ul>
<li><a href="../advanced/message.html" class="page">Warning / Info messages</a></li>
<li><a href="../advanced/event-ordering.html" class="page">Custom message ordering</a></li>
<li><a href="../advanced/aggregatestore.html" class="page">Aggregate store</a></li>
<li><a href="../advanced/event-replay.html" class="page">Event replay</a></li>
<li><a href="../advanced/multi-command.html" class="page">Multiple command handling in the same transaction</a></li>
</ul></li>
<li><a href="../eventually-consistent-projection.html" class="page">Eventually consistent projections</a></li>
<li><a href="../kafka-consumption.html" class="page">Using published events</a></li>
<li><a href="../non-blocking/index.html" class="page">Non blocking JOOQ implementation</a>
<ul>
<li><a href="../non-blocking/banking-real-life-non-blocking.html" class="page">Postgres Kafka, non blocking event sourcing</a></li>
<li><a href="../non-blocking/projections-non-blocking.html" class="page">Projections</a></li>
</ul></li>
<li><a href="../resilient-kafka-consumption.html" class="page">Resilient kafka consumption</a></li>
</ul>
</div>
</nav>
</div>
<div class="off-canvas-content" data-off-canvas-content>
<header class="site-header expanded row">
<div class="small-12 column">
<a href="#" class="off-canvas-toggle hide-for-medium" data-toggle="off-canvas-menu"><svg class="svg-icon svg-icon-menu" version="1.1" id="Menu" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 20 20" enable-background="new 0 0 20 20" xml:space="preserve"> <path class="svg-icon-menu-path" fill="#53CDEC" d="M16.4,9H3.6C3.048,9,3,9.447,3,10c0,0.553,0.048,1,0.6,1H16.4c0.552,0,0.6-0.447,0.6-1C17,9.447,16.952,9,16.4,9z M16.4,13
H3.6C3.048,13,3,13.447,3,14c0,0.553,0.048,1,0.6,1H16.4c0.552,0,0.6-0.447,0.6-1C17,13.447,16.952,13,16.4,13z M3.6,7H16.4
C16.952,7,17,6.553,17,6c0-0.553-0.048-1-0.6-1H3.6C3.048,5,3,5.447,3,6C3,6.553,3.048,7,3.6,7z"/></svg>
</a>
<div class="title-wrapper">
<div class="title-logo"></div>
<div class="title"><a href="../index.html">Thoth</a></div>
</div>
<!--
<a href="https://www.example.com" class="logo show-for-medium">logo</a>
-->
</div>
</header>
<div class="expanded row">
<div class="medium-3 large-2 show-for-medium column">
<nav class="site-nav">
<div class="nav-home">
<a href="../index.html" >
<span class="home-icon">⌂</span>Thoth
</a>
<div class="version-number">
1.1.4*
</div>
</div>
<select class="supergroup" name="Language"><option class="group" value="group-java">Java</option></select>
<div class="nav-toc">
<ul>
<li><a href="../technical-considerations.html" class="page">Technical considerations</a></li>
<li><a href="../banking.html" class="page">In memory example</a></li>
<li><a href="../standard/index.html" class="page">Standard JOOQ/Kafka implementation</a>
<ul>
<li><a href="../standard/banking-real-life.html" class="page">Postgres Kafka event sourcing</a></li>
<li><a href="../standard/projections.html" class="active page">Projections</a></li>
</ul></li>
<li><a href="../database-configuration.html" class="page">Database configuration</a></li>
<li><a href="../advanced/index.html" class="page">Advanced use cases</a>
<ul>
<li><a href="../advanced/message.html" class="page">Warning / Info messages</a></li>
<li><a href="../advanced/event-ordering.html" class="page">Custom message ordering</a></li>
<li><a href="../advanced/aggregatestore.html" class="page">Aggregate store</a></li>
<li><a href="../advanced/event-replay.html" class="page">Event replay</a></li>
<li><a href="../advanced/multi-command.html" class="page">Multiple command handling in the same transaction</a></li>
</ul></li>
<li><a href="../eventually-consistent-projection.html" class="page">Eventually consistent projections</a></li>
<li><a href="../kafka-consumption.html" class="page">Using published events</a></li>
<li><a href="../non-blocking/index.html" class="page">Non blocking JOOQ implementation</a>
<ul>
<li><a href="../non-blocking/banking-real-life-non-blocking.html" class="page">Postgres Kafka, non blocking event sourcing</a></li>
<li><a href="../non-blocking/projections-non-blocking.html" class="page">Projections</a></li>
</ul></li>
<li><a href="../resilient-kafka-consumption.html" class="page">Resilient kafka consumption</a></li>
</ul>
</div>
</nav>
</div>
<div class="small-12 medium-9 large-10 column">
<section class="site-content">
<div class="page-header row">
<div class="medium-12 show-for-medium column">
<div class="nav-breadcrumbs">
<ul>
<li><a href="../index.html">Thoth</a></li>
<li><a href="../standard/index.html">Standard JOOQ/Kafka implementation</a></li>
<li>Projections</li>
</ul>
</div>
</div>
</div>
<div class="page-content row">
<div class="small-12 large-9 column" id="docs">
<h1><a href="#projections" name="projections" class="anchor"><span class="anchor-link"></span></a>Projections</h1>
<p>Out account management system is limited in consultation : all we can do is read accounts by id, one by one.</p>
<p>Projections help us to implement different read scenario. They are built / updated by consuming events.</p>
<h2><a href="#in-transaction-projection" name="in-transaction-projection" class="anchor"><span class="anchor-link"></span></a>In transaction projection</h2>
<p>thoth offers tools for building “in transaction” projections. These projections will be updated in the transaction used to register events in the database, therefore they’ll be updated in “real time”.</p>
<p>Let’s say we want a projection that stores mean withdrawal value.</p>
<pre class="prettyprint"><code class="language-java">public class MeanBalanceProjection implements Projection<Connection, BankEvent, Tuple0, Tuple0> {
private BigDecimal withDrawTotal = BigDecimal.ZERO;
private long withdrawCount = 0L;
@Override
public Future<Tuple0> storeProjection(Connection connection, List<EventEnvelope<BankEvent, Tuple0, Tuple0>> envelopes) {
return Future.of(() -> {
envelopes.forEach(envelope -> {
BankEvent bankEvent = envelope.event;
if(envelope.event instanceof BankEvent.MoneyWithdrawn) {
withDrawTotal = withDrawTotal.add(((BankEvent.MoneyWithdrawn)bankEvent).amount);
withdrawCount ++;
}
});
return Tuple.empty();
});
}
public BigDecimal meanWithdraw() {
return withDrawTotal.divide(BigDecimal.valueOf(withdrawCount));
}
}
</code></pre>
<p>In the above example, we implemented an in memory projection, however in a real use case we should store values somewhere (e.g. in a database).</p>
<p>Next step is to declare the projection in our EventProcessor implementation.</p>
<pre class="prettyprint"><code class="language-java">public class Bank {
private final MeanWithdrawProjection meanWithdrawProjection;
//...
public Bank() {
//...
this.meanWithdrawProjection = new MeanWithdrawProjection();
this.eventProcessor = PostgresKafkaEventProcessor.create(
actorSystem,
eventStore(actorSystem, producerSettings, "bank", dataSource, executorService, new TableNames("bank_journal", "bank_sequence_num") ,eventFormat),
new JdbcTransactionManager(dataSource(), Executors.newFixedThreadPool(5)),
commandHandler,
eventHandler,
List.of(meanWithdrawProjection)
);
}
//...
public BigDecimal meanWithdrawValue() {
return meanWithdrawProjection.meanWithdraw();
}
}
</code></pre>
<h3><a href="#usage" name="usage" class="anchor"><span class="anchor-link"></span></a>Usage</h3>
<pre class="prettyprint"><code class="language-java">public class DemoApplication {
public static void main(String[] args) throws SQLException {
ActorSystem actorSystem = ActorSystem.create();
BankCommandHandler commandHandler = new BankCommandHandler();
BankEventHandler eventHandler = new BankEventHandler();
Bank bank = new Bank(actorSystem, commandHandler, eventHandler);
String id = bank.createAccount(BigDecimal.valueOf(100)).get().get().currentState.get().id;
bank.withdraw(id, BigDecimal.valueOf(50)).get().get().currentState.get();
bank.withdraw(id, BigDecimal.valueOf(10)).get().get().currentState.get();
System.out.println(bank.meanWithdrawValue()); // 30
}
}
</code></pre>
<h3><a href="#catch-up-past-events" name="catch-up-past-events" class="anchor"><span class="anchor-link"></span></a>Catch up past events</h3>
<p>In some cases, the projection will be created while events already exist in the journal. Sometimes these pre-existing events should be added to the projection.</p>
<p>To “catch up” with past events, you need to stream journal content:</p>
<pre class="prettyprint"><code class="language-java">eventStore.loadAllEvents()
.map(enveloppe -> enveloppe.event)
.filter(event -> event instanceof BankEvent.MoneyDeposited || event instanceof BankEvent.MoneyWithdrawn)
.mapAsync(1, event ->
CompletableFuture.supplyAsync(() -> {
try {
if(event instanceof BankEvent.MoneyDeposited deposit) {
String statement = "UPDATE global_balance SET balance=balance+?::money";
try(PreparedStatement preparedStatement = connection.prepareStatement(statement)) {
preparedStatement.setBigDecimal(1, deposit.amount);
preparedStatement.execute();
}
} else if(event instanceof BankEvent.MoneyWithdrawn withdraw) {
String statement = "UPDATE global_balance SET balance=balance-?::money";
try(PreparedStatement preparedStatement = connection.prepareStatement(statement)) {
preparedStatement.setBigDecimal(1, withdraw.amount);
preparedStatement.execute();
}
}
return Tuple.empty();
} catch(SQLException ex) {
throw new RuntimeException(ex);
}
})
).run(actorSystem)
</code></pre>
<p>⚠️ This code should be run while the system is not receiving events, otherwise there is a risk of double consumption. To fix this one solution would be to store consumed event id or sequence num and compare them with incoming events.</p>
<h2><a href="#eventually-consistent-projections" name="eventually-consistent-projections" class="anchor"><span class="anchor-link"></span></a>Eventually consistent projections</h2>
<p>Sometimes projections are too costly to be updated in transaction, sometimes we don’t need real time update.</p>
<p>In these case we could build “eventually consistent” projections, by connecting to our “bank” topic in Kafka, and consuming events from there.</p>
<p><a href="../eventually-consistent-projection.html">Eventually consistent projections</a> show how Thoth can help you to build eventually consistent projections.</p>
<p>See <a href="../kafka-consumption.html">Kafka consumption section</a> for more information on published events and kafka consumption.</p>
<div class="source-github">
The source code for this page can be found <a href="https://github.com/maif/thoth/tree/master/thoth-documentation/src/main/paradox/standard/projections.md">here</a>.
</div>
<div class="nav-next">
<p><strong>Next:</strong> <a href="../database-configuration.html">Database configuration</a></p>
</div>
</div>
<div class="large-3 show-for-large column" data-sticky-container>
<nav class="sidebar sticky" data-sticky data-anchor="docs" data-sticky-on="large">
<div class="page-nav">
<div class="nav-title">On this page:</div>
<div class="nav-toc">
<ul>
<li><a href="../standard/projections.html#projections" class="header">Projections</a>
<ul>
<li><a href="../standard/projections.html#in-transaction-projection" class="header">In transaction projection</a></li>
<li><a href="../standard/projections.html#eventually-consistent-projections" class="header">Eventually consistent projections</a></li>
</ul></li>
</ul>
</div>
</div>
</nav>
</div>
</div>
</section>
</div>
</div>
<footer class="site-footer">
<section class="site-footer-nav">
<div class="expanded row">
<div class="small-12 large-offset-2 large-10 column">
<div class="row site-footer-content">
<div class="small-12 medium-4 large-3 text-center column">
<div class="nav-links">
<ul>
<!-- <li><a href="https://www.example.com/products/">Products</a> -->
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="site-footer-base">
<div class="expanded row">
<div class="small-12 large-offset-2 large-10 column">
<div class="row site-footer-content">
<div class="small-12 text-center large-9 column">
<!--
<div class="copyright">
<span class="text">© 2021</span>
<a href="https://www.example.com" class="logo">logo</a>
</div>
-->
</div>
</div>
</div>
</div>
</section>
</footer>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="../lib/foundation/dist/foundation.min.js"></script>
<script type="text/javascript">jQuery(document).foundation();</script>
<script type="text/javascript" src="../js/magellan.js"></script>
<style type="text/css">@import "../lib/prettify/prettify.css";</style>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">jQuery(function(){window.prettyPrint && prettyPrint()});</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-112498312-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-112498312-1');
</script>
</html>