Axon - Consume Event from another Microservice - java

I have defined a Microservice:
AccountManagementService
Handles CreateAccountCommand
CreateAccountCommand shoots AccountCreatedEvent
The new Account is then stored in mysql db
Axon Server is used to store the event
Now I want another microservice B (that is connected to the same Axon Server) to handle the AccountCreatedEvent too.
Can I simply put
#EventHandler
protected void on(AccountCreatedEvent event){
}
in the second microservice B (for example in an Aggregate)? I tried that under the assumption that the event is stored in Axon Server and my second microservice automatically listens to that published event. It didn't work unfortunately.
How can microservice B subscribe to events (published by AccountManagementService) in the Axon Server?

The key issue you are expiriencing stems from one of your final sentences:
Can I simply put [insert-code-snippet] in the second microservice B (for example in an Aggregate)?
Well, yes you can simply add an #EventHandler annotated function in a regular component, but not in an Aggregate. The Aggregate functionality provided by Axon Framework is aimed towards being a Command Model. As would be used when employing CQRS really.
This makes the Aggregate a component which can solely handle command messages.
The only exception to this, is when you are adding Event Sourcing in the mix too. When Event Sourcing, you will source a given Command Model based on the events it has published. Thus introducing an #EventSourcingHandler annotated function inside your aggregate will only ever handle the events which originated from it.
To circle back to your original question, yes you can simply put the:
#EventHandler
protected void on(AccountCreatedEvent event){
// My event handling operation
}
in (micro)service B. But, that method cannot reside in an Aggregate. This is by design, to follow the CQRS and Event Sourcing paradigm as intended.
Any other component will do just fine though. If you are combining Axon with Spring, simply having the components with your event handling functions is sufficient. If you are not using Spring, you will have to register your components with event handlers to the Configurer or EventProcessingConfigurer.
Hoping this clarifies things for you.

Related

How to represent in UML that one class calls another class method when publishing spring event

I want to draw UML diagram which represents my Spring boot application. I'm new in UML and don't know how to represent an interaction between two classes that uses other classes for it. I have a class that publishes spring events and a class which handles such events. Publisher example:
import org.springframework.context.ApplicationEventPublisher;
class Publisher {
ApplicationEventPublisher springPublisher;
public publishEvent() {
springPublisher.publishEvent(new SomeEvent());
}
}
Handler:
import org.springframework.context.event.EventListener;
class EventHandler {
#EventListener
public handleEvent(Event event) {
// some processing
}
}
So, when I publish some events via Spring ApplicationEventPublisher my handler handles events via method annotated with #EventListener. But it is not a direct calling of the method. How I can illustrate it on the UML diagram?
The class diagram
As qwerty_so rightly pointed out, in a class diagram, we do not represent interactions: we represent structure, such as classes, association between classes, and dependencies:
On the EventHandler side, you have a dependency to Event. Since it's an #EventListener, Event is probably an ApplicationEvent
On the Publisher side, your code has a dependency to SomeEvent. Since it's an ApplicationEventPublisher, SomeEvent is probably an ApplicationEvent.
You may therefore want to show a dependency to the common ApplicationEvent:
The Spring magic
I'm not a Spring expert, but I understand that behind the "spring magic" is the annotation which hides an automatic registration of the listener to publisher, based on the signature of the annotated method.
You could be tempted to show in your model the (automatic) association between the listener and the publisher. But IMHO, this would not reflect well your design, since your model would hardwire the magic, whereas your code is dynamic in this regard. This is why the simpler diagram I show above, seems more appropriate: the magic is caused by the common Event denominator. Just use the right intermetiary type.
The interactions
If you want to show the dynamics of the interactions, it's a little more complex. You could for example use an sequence diagram, and encabulate the magic in a :SpringFramework lifeline, and materialize the automatic registration with messages sent to this "virtual" lifeline. Moreover:
Event sending would then be a message from the publisher to the framework,
Event listening would be a message sent by the framework to one or several listener.
It's not the real details. But the readers of your diagram do not need to know these details (except if they'd belong to the spring development team). So keep it as simple as possible, but not more :-)
You use either an activity or in this case probably better a sequence diagram. Those show behavior. In the SD draw a message arrow from Publisher to Eventhandler instances (life lines) and label it with the operation handleEvent().
A class diagram only shows static constructs.
It helps a lot to understand an architecture if methods are linked in a class diagram. You can do that with a dashed line and write <<use>> on it. Of course, if the architecture is complex, you won't be able to represent all these associations.
Unfortunately a lot of people discourage to do that and purpose sequence diagram instead (which doesn't give any context of what the class contains...). Furthermore, a lot of software to represent UML class diagrams doesn't work very well to link methods together.

Axon - Projection or event enricher?

I have following setup:
HTTP request arrives on REST endpoint and I receive it in my Application Service.
Application service maps request to command C1 and forwards it to aggregate using commandGateway.sendAndWait(new C1(restPostBody));.
Aggregate is loaded from repo, new command is applied and new event is produced an saved to store.
At this point in time, I need to enrich this event and use it as response of REST call.
So far I can see this options:
Use view projector, and project new event to create view model that can be forwarded as response in REST call. I guees here I would need to use queryGateway.subscriptionQuery(... and sqr.updates().blockFirst() for waiting for event to be processed by projector and then create response. Also, I guess this should be synchronous, since projection could get out of sync if system fails between storing event to DB and storing projection to DB?
Use some event enricher after event is published from aggregate and add needed properties to it and add response to REST call. This is similar to Projection, but in this case I would not save it to DB, since only time I need the data is as response to REST endpoint at the time command is issued. This should be definitelly synchronous, since if something fails, I would loose response. In case of async - I would need to have Aggregate handle duplicate events, and still emit events to event enricher but without storing to db. This seems to make things a lot complicated.
Are there any best practices related to this?
UPDATE
what I'm having currently is:
#Autowired
public void configure(EventProcessingConfigurer configurer){
configurer.usingSubscribingEventProcessors();
}
for synchronous Event processing in aggregate and view-model. Then I can query view model using (looks a bit ugly - is there better way?)
try {
sc = queryGateway.query(new MyQuery("123", "123),
ResponseTypes.instanceOf(SomeView.class)).get();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
And I can return this SomeView as response on REST api.
So, #bojanv55, you're trying to spoof your application to be a synchronous set up, whilst the command-event-query approach with Axon Framework enforces you to go the other way.
Ideally, your front-end should be compliant to this situation.
Thus, if you hit an end point which publishes a command, then you'd do a fire and forget. The events updating your query model will be pushed as updates, as they happen, to the front-end. So shortly, embracing the fact it's asynchronous should, in the end, make everything feel more seamless.
However, that's easier said then done; you're asking this question with a reason of course.
I personally like the usage of the subscription query, which you're also pointing towards, to spoof the operation to become synchronous.
This repository by Frans shows how to do this with Axon Framework quite nicely I think.
What he does, is handle the REST operation and first dispatching a subscription query for the thing you know will be updated pretty soon.
Secondly, the command is dispatched to the aggregate, the aggregate makes a decision to publish an event and the event updates the query model.
The query model update then constitutes in an update being emitted towards your subscription query, allowing you to only return the result as soon as the query model has actually be adjusted.
Concluding, I'd always recommend my first suggestion to embrace the asynchronous situation you're in. Secondly though, I think the subscription query solution I've just shared could resolve the problem you're having as well.
Hope this helps you out!

Java/OSGi modifying existing application into an OSGi service

I am quite new to OSGi and everything that is close to that.
Jump into the problem: I have a server-class that keeps a list of listeners, the listeners can register theirselves via a method (register(this)) that puts the listener into that above mentioned list (all listeners implement the server-class listener interface of course):
public void register(ServerListener listener) {
if(theListeners == null)
theListeners = new ArrayList<ServerListener>();
theListeners.add(listener);
}
That's the ServerListener interface:
public interface ServerListener {
public void update(JsonObject data);
}
Now the server-class provides the listeners with new data from time to time via an update(JsonObject object) method.
public void updateListeners() {
new Thread() {
public void run() {
for(ServerListener l : theListeners) {
l.update(jsonObject);
}
}
}.start();
}
Now, I want to modify the server-class into a service bundle in an OSGi framework (Knopflerfish). I am not familiar with that at all. I want to try just for fun, but the way I am doing it right now would not work, the listeners actually don't know that they should implement the ServerListener interface. So the server can't register them via the interface.
The thing is, I want to server to push data, not the clients to pull (that would be easier, in my understanding). Can someone (who understood my poor explanation) point me in the right direction?
An 'OSGi-centric' approach is to use a pattern known as the whiteboard pattern, rather than the listener pattern as you might with plain Java. Instead of registering with the server-class, your listeners register as services with the OSGi service registry. This means the framework takes care of handling registration, unregistration, and listeners which go away.
There's a free whitepaper on the whiteboard pattern here: http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf, and we've also got a discussion of it in chapter 5 of Enterprise OSGi in Action (http://www.manning.com/cummins ).
It can take a while to get your head wrapped around the listener pattern, because it's your listeners which provide services, and your 'server' which consumes the services, which feels backwards at first. Once you get used to it, though, it works really well. Your server consumes all the services which implement the ServiceListener interface, and pushes data out to them as required.
It's best not to use the OSGi APIs directly to register and consume the services - use either declarative services (SCR) or blueprint for dependency injection of the OSGi services. These allow you to register and consume the services with an XML metadata file or annotations.
(As other have suggested, using a package-level dependencies for the ServerListener interface should allow it to be imported by both the server and listener bundles, no matter which bundle exports the package.)
You've got multiple problems here:
You need to expose a service (the server class) for other objects to register with
Interested objects need to find the service in order to register themselves
The other objects need to implement a particular interface for this to work
In general, trying to retrofit existing code into the OSGi can be painful unless you already have a modular architecture.
The listener interface can live in the server bundle or you could put it in a seperate API/contract bundle - both are valid designs.
From how you are describing the problem it sounds like you don't know the different types of dependency you can have in OSGi.
Coming from traditional Java development, most developers will start with the 'my dependencies are based on JARs' - this is not the best model.
OSGi offers package-level dependencies. In this way as long as some bundle offers the needed package, you're bundle doesn't care which bundle/JAR provided the dependency.
So if you used a package-level dependency for your listener interface, the implementation doesn't need to care if it comes from the server bundle or a contract/API bundle.
As a final note your design tightly couples the server to the listeners. What happens if a listener fails? Or hangs? Pub/sub is a better model for this type of communication.
* edit *
And Holly's answer reminded me again of the whiteboard pattern - definitely a good idea.

Why people use message/event buses in their code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 4 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I think that you have heard of message/event buses, it's the single place when all events in the system flow. Similar architectures are found in computer's motherboards and LAN networks. It's a good approach for motherboards and networks as it reduces the number of wires, but is it good for software development? We don't have such restrictions as electronics does.
The simplest implementation of message bus/event bus can be like:
class EventBus {
void addListener(EventBusListener l}{...}
void fireEvent(Event e) {...}
}
Posting events is done with bus.fireEvent(event), receiving messages is enabled by bus.addListener(listener). Such architectures are sometimes used for software development, for example MVP4G implements similar message bus for GWT.
Active projects:
Google Guava EventBus
MBassador by Benjamin Diedrichsen
Mycila PubSub by Mathieu Carbou
mvp4g Event Bus
Simple Java Event Bus
Dormant/Dead projects:
Sun/Oracle JavaBeans InfoBus
https://eventbus.dev.java.net/ [Broken link]
It's just the popular Observer (Listener) pattern made 'globally' - each object in the system can listen to each message, and I think it's bad, it breaks the Encapsulation principle (each object knows about everything) and Single Responsibility principle (eg when some object needs to a new type of message, event bus often needs to be changed for example to add a new Listener class or a new method in the Listener class).
For these reasons I think, that for most software, Observer pattern is better than event bus. What do you think about event bus, does it make any good sense for typical applications?
EDIT: I'm not talking about 'big' enterprise solutions like ESB - they can be useful (what's more ESB offers much, much more than just an event bus). I'm asking about usefulness of using message bus in 'regular' Java code for object-to-object connection - some people do it, check the links above. Event bus is probably best solution for telephone-to-telephone communication or computer-to-computer communication because each telefone (or computer) in a network can typically talk to each other, and bus reduces the number of wires. But objects rarely talk to each other - how many collaborators one object can have - 3, 5?
I am considering using a In memory Event Bus for my regular java code and my rationale is as follows
Each object in the system can listen to each message, and I think it's
bad, it breaks the Encapsulation principle (each object knows about
everything)
I am not sure if this is really true, I class needs to register with the event bus to start with, similar to observer pattern, Once a class has registered with the Event Bus, only the methods which have the appropriate signature and annotation are notified.
and Single Responsibility principle (eg when some object needs to a
new type of message, event bus often needs to be changed for example
to add a new Listener class or a new method in the Listener class).
I totally disagree with
event bus often needs to be changed
The event bus is never changed
I agree with
add a new Listener class or a new method in the Listener class
How does this break SRP ?, I can have a BookEventListener which subscribes to all events pertaining to my Book Entity, and yes I can add methods to this class but still this class is cohesive ...
Why I plan to use it ? It helps me model the "when" of my domain ....
Usually we hear some thing like send a mail "when" book is purchased
we go write down
book.purchase();
sendEmail()
Then we are told add a audit log when a book is purchased , we go to the above snippet
book.purchase();
sendEmail();
**auditBook();**
Right there OCP violated
I Prefer
book.purchase();
EventBus.raiseEvent(bookPurchasedEvent);
Then keep adding handlers as needed Open for Extension Closed for Modification
Thanks
Some people like it because it is the embodiment of the Facade pattern or Mediator pattern. It centralizes cross-cutting activities like logging, alerting, monitoring, security, etc.
Some people don't like it because it is often a Singleton point of failure. Everyone has to know about it.
I use it heavily in JavaScript. There can be so many various widgets that all need to do some sort of action whenever something else happens -- there is no real hierarchy of ownership of objects. Instead of passing references of every object to every object, or just making every object global, when something significant happens inside a particular widget, I can just publish "/thisWidget/somethingHappened" -- instead of filling that widget with all kinds of code specific to the API of other widgets. The I have a single class that contains all the "wiring", or "plubming" as they like to call it in the Java Spring framework. This class contains references to all of my widgets, and has all of the code for what happens after each various event fires.
It is centralized, easy to access and maintain, and if one thing changes or I want a new process to occur on a specific event, I don't have to search through every single class/object/widget to try to find out where something is being handled. I can just go to my "operator" class -- the one that handles all the "wiring" when a particular event happens, and see every repercussion of that event. In this system, every individual widget is completely API agnostic of the other widgets. It simply publishes what has happened to it or what it is doing.
I'm having trouble understanding what you're really asking in your question. You give an example of a simple event bus which is actually just Observable with a different name, then you say;
For these reasons I think, that for
most software, Observer pattern is
better than event bus. What do you
think about event bus, does it make
any good sense for typical
applications?
..but given your example, they are the same. This makes me wonder if you have ever used something like a Enterprise Service Bus. At a base level an ESB logically does the same thing as the observer pattern, but commercial products add much, much more. Its like an event bus on steroids. They are complicated software products and offer;
Message pickup
Generate events by listening to various endpoints. The endpoint can be a listener (such as a HTTP server), a messaging system (such as JMS), a database or pretty much anything else you want.
Message routing
Take your event and send it to one/many endpoint. Routing can be pretty smart, the bus might route the message depending on the message type, the message contents or any other criteria. Routing can be intelligent and dynamic.
Message Transformation
Transforms your message into another format, this can be as simnple as from XML to JSON or from a row on a database table to a HTTP request. Transformation can occur within the data itself, for example swapping date formats.
Data Enrichment
Adds or modifies data in your message by calling services along the way. For example if a message has a postcode in it the bus might use a postcode lookup service to add in address data.
..and lots, lots more. When you start looking into the details you can really start to see why people use these things.
Because it can be an important step in the way to decouple the application modules to a service based architecture.
So in your case if you have not the intention to decouple the modules of your application into isolated services then the native implementation of the Observer pattern will make it a simpler solution.
But If you want to build lets say a micro-services architecture the event-bus will allow to get the benefits of this architecture style so you could for instance update and deploy just some part of your application without affect others, because they are just connected through the event-bus.
So the main question here is the desired level of application components decoupling.
Some references about it:
http://microservices.io/patterns/data/event-driven-architecture.html
http://tech.grammarly.com/blog/posts/Decoupling-A-Monolithic-Server-Application.html
A good analogy is that of a telephone exchange, where every handset can dial to every other handset. A compromised handset can tune into other conversations. Program control flows like wires(cyclomatic complexity anyone!) This is similar to the requirement of having a connection/physical medium between two end points. This is So for N handsets instead of having NC2 (Combinatorial logic) flows for every new handset we tend to get N flows.
A reduction in complexity implies easy to understand code. Lets start with the prominent points you have highlighted: 1. Global knowledge 2. Intrusive modifications.
Global Knowledge: Consider message event to be an envelop. From event handler/sender perspective there is no data being exposed, it is seeing an envelop (unless an derived class tries to do some inspection using 'instanceof' checks). In a good OOP design, this would never occur.
Intrusive modifications: Instead of having a event specific listener approach, one can use a global event handling approach. As such we have a global event type (on which data is piggy backed and down-casted). This is much like the PropertyBeanSupport model in Java. With a single event type we are required to have a single sender and listener types. This implies you need not modify the bus/listeners every time you see something new. The ugly down-casting can be soothened using Adapter pattern (Please don't start that another level of redirection quote!). Programmers can write assembly in any language. So need for commonsense and smartness can not be substituted. All I intend to state is it can be a effective tool.
The actual event receivers can use the listeners (composition/proxy) easily. In such a Java code base, listeners would look like stand alone inner class declarations (with unused warning being flagged in certain IDEs). This is akeen to two players on the beach playing a ball game, the players don't react until they see the ball.
'#duffymo' points out another interesting aspect: 'Single point of failure'. This would/can in theory effect any object residing in memory(RAM) and not specific to MessageHandlers.
As a practical example, our app sync's with a web service every x number of minutes, and if any new data is received, we need to update the GUI. Now, because the SyncAdapter runs on a background thread, you can't simply point to a textview and modify its properties, you have to bubble up an event. And the only way to make sure you catch that event is if you have a shared (static,singleton) object passing that event around for subscribers to handle.

Java equivalent of Cocoa NSNotification?

I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model's state).
Is there something in Java similar to Cocoa's NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects "fire off" a notification?
Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don't worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it "ScanListener", like
public interface ScanListener
{
public void scanStarted();
public void scanCompleted();
}
Now the Loader defines a method for your other code to register for callbacks, like
public void addScanListener(ScanListener listener)
{
listeners.add(listener);
}
The Loader, when it starts a scan, executes the following code
for (ScanListener listener : listeners)
{
listener.scanStarted();
}
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls "loader.addScanListener(this)". Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It's all up to you.
What sort of notifications are you looking for? If all you want is for one object to be able to tell anybody else "hey, I've changed, update accordingly", the easiest way is to use the existing Observer interface and Observable class. Or write your own with an interface that defines what you want to get called on the listeners from the one that's changed.
There's no pre-existing per-process service that dispatches events in java that's equivalent to the default NSNotificationCenter. In java, the type of the event is specified by the event object being a particular type (which also means that the notification method depends on that type) rather than using a string. Prior to generics, writing a general event dispatcher and receiver that is also typesafe isn't really possible (witness the proliferation of *Event classes and *EventListener interfaces in the AWT and Spring libraries).
There are some facilities for event dispatch. As Paul mentioned, there's java.util.Observable, which as you point out, requires subclassing. There's also java.beans.PropertyChangeSupport, which could be useful depending on your situation.
You could also write one yourself. The source for PropertyChangeSupport is likely available in the openjdk, and you could look at the abandoned Apache Commons Event project. Depending on your needs, you may have to worry about stuff like threading, seralization, memory leaks (ensuring deregistration or using weak references), and concurrent modification (iterate over a copy of your list of listeners, as a listener may decide to unregister itself in response to a change).
Now that generics exist in Java, a generic event dispatch library would be possible; however, I haven't come across any. Anyone?
There's actually a facility built in to Java that does exactly what you want, but it's not something you may have considered, and, to be honest, it is likely a bit heavyweight for what you want.
That said, however, it does exist.
It's JMX.
You create MBeans, and then others can register for events from those MBeans. The MBean can then send of a Notification.
I personally wouldn't consider using it for this case (I'd just pound out my own), but the facility is there and it well defined and documented.
Not Java, but the IPython project has a notification center written in Python here that you could use as a template for a Java version.
In Java this would be a provider firing notifications to its listeners. But Java does not offer the loose coupling you get with Cocoa's NSNotification because in Java providers and subscribers must have references to each other. Compare for this chapter 18 in "Learn Objective-C for Java Developers".
There is an implementation of IOS NSNotificationCenter in Java.
You can find sources code in :
This Github project

Categories

Resources