Say hello to kafEEne ! A blog series which will show Kafka and Java EE examples
This one is about Kafka + (Java EE) Websocket API. Code is on Github and you can refer to the README on how to get this up and running using Docker. Although the focus is on Websocket, here is a list of other Java EE specs which have been used – EJB, CDI & a bit of JSON-B (part of Java EE 8)
Consumer
- Kafka Consumer is a
@Stateless
EJB - Initialized in the
@PostConstruct
callback - The consumer logic is executed within a while loop controlled by a (atomic) boolean flag which can potentially be mutated by the container. It sends the event data in form of a custom
Payload
object using CDIEvent
s - Consumer shutdown is exposed within a
@PreDestroy
method where it invokes thewakeup
method to interrupt the consumer while loop - A simple (one time) EJB timer job triggers the Consumer process – this is just for simplicity. No harm in exposing the consumer startup through, say, a REST endpoint
See Consumer
for more details
Websocket endpoint
A server side Websocket endpoint which is actually does very little to be honest. Client can call it with the interested topic in the URL itself
- The
@OnOpen
callback makes sure that the WebsocketSession
is added and tracked and the topic is added to theSession
properties (Map
) @OnClose
callback removes theSession
from the memory
Broadcasting
- It is enabled by a CDI observer (
@Observe
) for thePayload
object - Simply loops over all the
Session
s and broadcasts the key-value pair (received from the Kafka topic) if it registered for that topic to begin with - It uses the JSON-B API to convert the
Payload
POJO to a JSON format
See KafkaWebsocketEndpoint
for more details
Connected clients
- A
@Singleton
EJB maintains a list of connected clients - Its provides a synchronized wrapper over the collection of Websocket
Session
objects
See Peers
for more details
Websocket Client
A simple Javascript based front end. See index.html
for more details. I am not a front end guy – please pardon me!
Producer application
It’s a bare bones Java based producer application which pushes random data to couple of Kafka topics
Further reading
- Websocket book & other Websocket blogs
- Other Kafka blogs on simplydistributed
- Java EE 8, JSON-B and it’s RI Yasson
Cheers!
Pingback: Kafka & Websocket | Simply Distributed