Panduan untuk Rangka Kerja Axon

1. Gambaran keseluruhan

Dalam artikel ini, kami akan melihat Axon dan bagaimana ia membantu kami melaksanakan aplikasi dengan mempertimbangkan CQRS (Command Query Responsibility Segregation) dan Event Sourcing .

Semasa panduan ini, Axon Framework dan Axon Server akan digunakan. Yang pertama akan merangkumi pelaksanaan kami dan yang terakhir akan menjadi penyelesaian Event Store dan Message Routing khusus kami.

Contoh aplikasi yang akan kami bina fokus pada domain Pesanan Untuk ini, kami akan memanfaatkan blok bangunan CQRS dan Event Sourcing yang disediakan oleh Axon kepada kami .

Perhatikan bahawa banyak konsep bersama berasal dari DDD, yang berada di luar ruang lingkup artikel semasa ini.

2. Pergantungan Maven

Kami akan membuat aplikasi Axon / Spring Boot. Oleh itu, kita perlu menambahkan pergantungan axon-spring-boot-starter terkini ke pom.xml kami , serta ketergantungan ujian axon untuk ujian:

 org.axonframework axon-spring-boot-starter 4.1.2   org.axonframework axon-test 4.1.2 test 

3. Pelayan Axon

Kami akan menggunakan Pelayan Axon untuk menjadi Event Store kami dan penyelesaian arahan, acara dan pertanyaan khusus kami.

Sebagai Kedai Acara, ia memberi kita ciri-ciri ideal yang diperlukan semasa menyimpan acara. Artikel ini memberikan latar belakang mengapa perkara ini diinginkan.

Sebagai penyelesaian Penghantaran Mesej, kami memberi pilihan untuk menyambungkan beberapa contoh bersama tanpa memfokuskan diri untuk mengkonfigurasi perkara seperti topik RabbitMQ atau Kafka untuk berkongsi dan menghantar mesej.

Pelayan Axon boleh dimuat turun di sini. Oleh kerana ia adalah fail JAR sederhana, operasi berikut cukup untuk memulakannya:

java -jar axonserver.jar

Ini akan memulakan satu contoh Axon Server yang boleh diakses melalui localhost: 8024 . Titik akhir memberikan gambaran keseluruhan aplikasi yang terhubung dan mesej yang dapat mereka tangani, serta mekanisme pertanyaan ke arah Event Store yang terdapat di dalam Axon Server.

Konfigurasi lalai Axon Server bersama dengan pergantungan axon-spring-boot-starter akan memastikan perkhidmatan Pesanan kami akan bersambung secara automatik dengannya.

4. API Perkhidmatan Pesanan - Perintah

Kami akan menyediakan perkhidmatan Pesanan dengan mempertimbangkan CQRS. Oleh itu, kami akan menekankan mesej yang melalui aplikasi kami.

Pertama, kita akan menentukan Perintah, yang bermaksud ungkapan niat. Perkhidmatan Pesanan mampu menangani tiga jenis tindakan:

  1. Membuat pesanan baru
  2. Mengesahkan pesanan
  3. Penghantaran pesanan

Secara semula jadi, akan ada tiga pesanan pesanan yang dapat ditangani oleh domain kita - PlaceOrderCommand , ConfirmOrderCommand , dan ShipOrderCommand :

public class PlaceOrderCommand { @TargetAggregateIdentifier private final String orderId; private final String product; // constructor, getters, equals/hashCode and toString } public class ConfirmOrderCommand { @TargetAggregateIdentifier private final String orderId; // constructor, getters, equals/hashCode and toString } public class ShipOrderCommand { @TargetAggregateIdentifier private final String orderId; // constructor, getters, equals/hashCode and toString }

The TargetAggregateIdentifier anotasi memberitahu Axon bahawa bidang beranotasi adalah id agregat tertentu yang arahan perlu disasarkan. Kami akan menyentuh secara ringkas agregat kemudian dalam artikel ini.

Juga, perhatikan bahawa kami menandai bidang dalam perintah sebagai akhir. Ini disengajakan, kerana ini adalah amalan terbaik agar sebarang penerapan mesej tidak berubah .

5. API Perkhidmatan Pesanan - Acara

Gabungan kami akan menangani perintah tersebut , karena bertanggung jawab untuk memutuskan apakah Pesanan dapat dilakukan, disahkan, atau dikirimkan.

Ini akan memberitahukan selebihnya penerapan keputusannya dengan menerbitkan acara. Kami akan mempunyai tiga jenis acara - OrderPlacedEvent, OrderConfirmedEvent , dan OrderShippedEvent :

public class OrderPlacedEvent { private final String orderId; private final String product; // default constructor, getters, equals/hashCode and toString } public class OrderConfirmedEvent { private final String orderId; // default constructor, getters, equals/hashCode and toString } public class OrderShippedEvent { private final String orderId; // default constructor, getters, equals/hashCode and toString }

6. Model Perintah - Susunan Agregat

Sekarang setelah kita memodelkan API inti kita sehubungan dengan perintah dan peristiwa, kita dapat mulai membuat Model Perintah.

Oleh kerana domain kami berfokus untuk berurusan dengan Pesanan, kami akan membuat OrderAggregate sebagai pusat Model Perintah kami.

6.1. Kelas Agregat

Oleh itu, mari buat kelas agregat asas kami:

@Aggregate public class OrderAggregate { @AggregateIdentifier private String orderId; private boolean orderConfirmed; @CommandHandler public OrderAggregate(PlaceOrderCommand command) { AggregateLifecycle.apply(new OrderPlacedEvent(command.getOrderId(), command.getProduct())); } @EventSourcingHandler public void on(OrderPlacedEvent event) { this.orderId = event.getOrderId(); orderConfirmed = false; } protected OrderAggregate() { } }

The Agregat anotasi adalah khusus anotasi Axon Spring menandakan kelas ini sebagai agregat. Ini akan memberitahu kerangka kerja bahawa blok bangunan khusus CQRS dan Event Sourcing yang diperlukan perlu dibuat untuk OrderAggregate ini .

Sebagai agregat akan menangani perintah yang ditargetkan untuk contoh agregat tertentu, kita perlu menentukan pengenal dengan anotasi AggregateIdentifier .

Agregat kami akan memulakan kitaran hayatnya setelah mengendalikan PlaceOrderCommand dalam 'command handling konstruktor' OrderAggregate . Untuk memberitahu kerangka kerja bahawa fungsi yang diberikan dapat menangani perintah, kami akan menambahkan anotasi CommandHandler .

Semasa mengendalikan PlaceOrderCommand , ia akan memberitahu sisa aplikasi bahawa pesanan telah dilakukan dengan menerbitkan OrderPlacedEvent. Untuk menerbitkan acara dari dalam agregat, kami akan menggunakan AggregateLifecycle # berlaku (Objek…) .

Dari sudut ini, kita benar-benar dapat mulai memasukkan Event Sourcing sebagai pendorong untuk mencipta semula contoh agregat dari aliran acara.

We start this off with the ‘aggregate creation event', the OrderPlacedEvent, which is handled in an EventSourcingHandler annotated function to set the orderId and orderConfirmed state of the Order aggregate.

Also note that to be able to source an aggregate based on its events, Axon requires a default constructor.

6.2. Aggregate Command Handlers

Now that we have our basic aggregate, we can start implementing the remaining command handlers:

@CommandHandler public void handle(ConfirmOrderCommand command) { apply(new OrderConfirmedEvent(orderId)); } @CommandHandler public void handle(ShipOrderCommand command) { if (!orderConfirmed) { throw new UnconfirmedOrderException(); } apply(new OrderShippedEvent(orderId)); } @EventSourcingHandler public void on(OrderConfirmedEvent event) { orderConfirmed = true; }

The signature of our command and event sourcing handlers simply states handle({the-command}) and on({the-event}) to maintain a concise format.

Additionally, we've defined that an Order can only be shipped if it's been confirmed. Thus, we'll throw an UnconfirmedOrderException if this is not the case.

This exemplifies the need for the OrderConfirmedEvent sourcing handler to update the orderConfirmed state to true for the Order aggregate.

7. Testing the Command Model

First, we need to set up our test by creating a FixtureConfiguration for the OrderAggregate:

private FixtureConfiguration fixture; @Before public void setUp() { fixture = new AggregateTestFixture(OrderAggregate.class); }

The first test case should cover the simplest situation. When the aggregate handles the PlaceOrderCommand, it should produce an OrderPlacedEvent:

String orderId = UUID.randomUUID().toString(); String product = "Deluxe Chair"; fixture.givenNoPriorActivity() .when(new PlaceOrderCommand(orderId, product)) .expectEvents(new OrderPlacedEvent(orderId, product));

Next, we can test the decision-making logic of only being able to ship an Order if it's been confirmed. Due to this, we have two scenarios — one where we expect an exception, and one where we expect an OrderShippedEvent.

Let's take a look at the first scenario, where we expect an exception:

String orderId = UUID.randomUUID().toString(); String product = "Deluxe Chair"; fixture.given(new OrderPlacedEvent(orderId, product)) .when(new ShipOrderCommand(orderId)) .expectException(IllegalStateException.class); 

And now the second scenario, where we expect an OrderShippedEvent:

String orderId = UUID.randomUUID().toString(); String product = "Deluxe Chair"; fixture.given(new OrderPlacedEvent(orderId, product), new OrderConfirmedEvent(orderId)) .when(new ShipOrderCommand(orderId)) .expectEvents(new OrderShippedEvent(orderId));

8. The Query Model – Event Handlers

So far, we've established our core API with the commands and events, and we have the Command model of our CQRS Order service, the Order aggregate, in place.

Next, we can start thinking of one of the Query Models our application should service.

One of these models is the OrderedProducts:

public class OrderedProduct { private final String orderId; private final String product; private OrderStatus orderStatus; public OrderedProduct(String orderId, String product) { this.orderId = orderId; this.product = product; orderStatus = OrderStatus.PLACED; } public void setOrderConfirmed() { this.orderStatus = OrderStatus.CONFIRMED; } public void setOrderShipped() { this.orderStatus = OrderStatus.SHIPPED; } // getters, equals/hashCode and toString functions } public enum OrderStatus { PLACED, CONFIRMED, SHIPPED }

We'll update this model based on the events propagating through our system. A Spring Service bean to update our model will do the trick:

@Service public class OrderedProductsEventHandler { private final Map orderedProducts = new HashMap(); @EventHandler public void on(OrderPlacedEvent event) { String orderId = event.getOrderId(); orderedProducts.put(orderId, new OrderedProduct(orderId, event.getProduct())); } // Event Handlers for OrderConfirmedEvent and OrderShippedEvent... }

As we've used the axon-spring-boot-starter dependency to initiate our Axon application, the framework will automatically scan all the beans for existing message-handling functions.

As the OrderedProductsEventHandler has EventHandler annotated functions to store an OrderedProduct and update it, this bean will be registered by the framework as a class that should receive events without requiring any configuration on our part.

9. The Query Model – Query Handlers

Next, to query this model, for example, to retrieve all the ordered products, we should first introduce a Query message to our core API:

public class FindAllOrderedProductsQuery { }

Second, we'll have to update the OrderedProductsEventHandler to be able to handle the FindAllOrderedProductsQuery:

@QueryHandler public List handle(FindAllOrderedProductsQuery query) { return new ArrayList(orderedProducts.values()); }

The QueryHandler annotated function will handle the FindAllOrderedProductsQuery and is set to return a List regardless, similarly to any ‘find all' query.

10. Putting Everything Together

We've fleshed out our core API with commands, events, and queries, and set up our Command and Query model by having an OrderAggregate and OrderedProducts model.

Next is to tie up the loose ends of our infrastructure. As we're using the axon-spring-boot-starter, this sets a lot of the required configuration automatically.

First, as we want to leverage Event Sourcing for our Aggregate, we'll need an EventStore. Axon Server which we have started up in step three will fill this hole.

Secondly, we need a mechanism to store our OrderedProduct query model. For this example, we can add h2 as an in-memory database and spring-boot-starter-data-jpa for ease of use:

 org.springframework.boot spring-boot-starter-data-jpa com.h2database h2 runtime 

10.1. Setting up a REST Endpoint

Next, we need to be able to access our application, for which we'll be leveraging a REST endpoint by adding the spring-boot-starter-web dependency:

 org.springframework.boot spring-boot-starter-web 

From our REST endpoint, we can start dispatching commands and queries:

@RestController public class OrderRestEndpoint { private final CommandGateway commandGateway; private final QueryGateway queryGateway; // Autowiring constructor and POST/GET endpoints }

The CommandGateway is used as the mechanism to send our command messages, and the QueryGateway, in turn, to send query messages. The gateways provide a simpler, more straightforward API, compared to the CommandBus and QueryBus that they connect with.

From here on, our OrderRestEndpoint should have a POST endpoint to place, confirm, and ship an order:

@PostMapping("/ship-order") public void shipOrder() { String orderId = UUID.randomUUID().toString(); commandGateway.send(new PlaceOrderCommand(orderId, "Deluxe Chair")); commandGateway.send(new ConfirmOrderCommand(orderId)); commandGateway.send(new ShipOrderCommand(orderId)); }

This rounds up the Command side of our CQRS application.

Now, all that's left is a GET endpoint to query all the OrderedProducts:

@GetMapping("/all-orders") public List findAllOrderedProducts() { return queryGateway.query(new FindAllOrderedProductsQuery(), ResponseTypes.multipleInstancesOf(OrderedProduct.class)).join(); }

In the GET endpoint, we leverage the QueryGateway to dispatch a point-to-point query. In doing so, we create a default FindAllOrderedProductsQuery, but we also need to specify the expected return type.

As we expect multiple OrderedProduct instances to be returned, we leverage the static ResponseTypes#multipleInstancesOf(Class) function. With this, we have provided a basic entrance into the Query side of our Order service.

We completed the setup, so now we can send some commands and queries through our REST Controller once we've started up the OrderApplication.

POST-ing to endpoint /ship-order will instantiate an OrderAggregate that'll publish events, which, in turn, will save/update our OrderedProducts. GET-ing from the /all-orders endpoint will publish a query message that'll be handled by the OrderedProductsEventHandler, which will return all the existing OrderedProducts.

11. Conclusion

In this article, we introduced the Axon Framework as a powerful base for building an application leveraging the benefits of CQRS and Event Sourcing.

We implemented a simple Order service using the framework to show how such an application should be structured in practice.

Lastly, Axon Server posed as our Event Store and the message routing mechanism.

The implementation of all these examples and code snippets can be found over on GitHub.

For any additional questions you may have, also check out the Axon Framework User Group.