SlideShare a Scribd company logo
1 of 31
Bring your favorite Kafka to
Java EE with CDI
Ivan St. Ivanov
Who am I?
@ivan_stefanov
Agenda
•Kafka 10...1
•CDI@Kafka
•Kafka portable
Showcase app
User service Forum service
User DB Forum DB
Kafka
CDI primer
@ApplicationScoped
public class UserModificationKafkaProducer {
private KafkaProducer<String, String>
kafkaProducer;
public void userModified(User modifiedUser) {
String record =
CDI primer
@ApplicationScoped
public class UserModificationKafkaProducer {
@Inject
private KafkaProducer<String, String>
kafkaProducer;
public void userModified(User modifiedUser) {
String record =
CDI primer
@ApplicationScoped
public class UserModificationKafkaProducer {
@Inject
@KafkaProducerConfig(bootstrapServers =
"mykafkahost:9090")
private KafkaProducer<String, String>
kafkaProducer;
public void userModified(User modifiedUser) {
CDI primer
public @interface KafkaProducerConfig {
Class keyType() default String.class;
Class valueType() default String.class;
String bootstrapServers() default "localhost:9092";
}
CDI primer
@ApplicationScoped
public class KafkaProducerFactory {
@Produces
public <K,V> KafkaProducer<K, V> createProducer(
InjectionPoint injectionPoint) {
KafkaProducerConfig annotation = injectionPoint
.getAnnotated()
.getAnnotation(KafkaProducerConfig.class);
Properties producerProperties = new Properties();
producerProperties.setProperty(
"bootstrap.servers", annotation.bootstrapServers());
// Set other props
return new KafkaProducer<>(producerProperties);
}
}
CDI primer
@ApplicationScoped
public class UserModificationKafkaProducer {
@Inject
@KafkaProducerConfig(bootstrapServers =
"mykafkahost:9090")
private KafkaProducer<String, String>
kafkaProducer;
public void userModified(@Observes User
CDI primer
public class KafkaUpdatesListener implements Runnable {
@Inject
@KafkaConsumerConfig(subscriptions = "user")
private KafkaConsumer<String, String> consumer;
@Override
public void run() {
while (continuePolling) {
ConsumerRecords<String, String> records =
consumer.poll(100);
if (!records.isEmpty()) {
// Update microservice storage
But what if...
• Leave factories boilerplate to the framework
• Leave polling updates to the framework
• Do it this way:
public class UserModificationKafkaConsumer {
•
@Consumes(topic = "user")
public void listenForUsers(
ConsumerRecord<String, String> record) {
• String userJson = record.value();
• // Store the user in DB
}
CDI extensions
•CDI magic
•Hook into the lifecycle
•Override default behavior
•Portable across containers
CDI extension prerequisites
•Implement javax.enterprise.inject.spi.Extension
•Observe events of interest
•Register service provider
Before Bean Discovery
Process Annotated Types
After Type Discovery
Type discovery
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Running
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
Kafka CDI extension tasks
• Register the factories and listener thread
• Create Kafka Consumer for all @Consumes methods
• Start polling consumers for changes
• Invoke @Consumes methods when change happens
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
public void addKafkaSpecificTypes(
@Observes BeforeBeanDiscovery bbd,
BeanManager beanManager) {
bbd.addAnnotatedType(
beanManager.createAnnotatedType(KafkaProducerFactory.class));
bbd.addAnnotatedType(
beanManager.createAnnotatedType(KafkaUpdatesListener.class));
}
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
public void collectConsumerMethods(
@Observes @WithAnnotations(Consumes.class)
ProcessAnnotatedType<?> pat) {
pat.getAnnotatedType().getMethods().stream()
.filter(m -> m.isAnnotationPresent(Consumes.class))
.forEach(m -> handleConsumerMethod(pat.getAnnotatedType(), m));
}
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
private void handleConsumerMethod(AnnotatedType<?> clazz,
AnnotatedMethod<?> am) {
List<AnnotatedParameter<?>> parameters = am.getParameters();
if (parameters.size() != 1) {
errors.add(new IllegalArgumentException(
"@Consume methods should only have one parameter"));
} else {
consumerDescriptors.add(new KafkaConsumerDescriptor(
clazz.getJavaClass(), am,
am.getAnnotation(Consumes.class).topic()));
}
}
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
public void startMonitoring(@Observes AfterDeploymentValidation adv,
BeanManager bm) {
if (!errors.isEmpty()) {
errors.forEach(adv::addDeploymentProblem);
} else {
KafkaUpdatesListener kafkaUpdatesListener = initializeListener(bm);
startListener(kafkaUpdatesListener, adv);
this.kafkaUpdatesListener = kafkaUpdatesListener;
}
}
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
private KafkaUpdatesListener initializeListener(BeanManager bm) {
Class<KafkaUpdatesListener> clazz = KafkaUpdatesListener.class;
KafkaUpdatesListener reference = createBean(bm, clazz);
consumerDescriptors.forEach(m -> addTopicToListen(m, reference));
return reference;
}
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
static Object createBean(BeanManager bm, Class<?> clazz) {
Set<Bean<?>> listenerBeans = bm.getBeans(clazz);
Bean<?> listenerBean = bm.resolve(listenerBeans);
CreationalContext<?> creationalContext =
bm.createCreationalContext(listenerBean);
return bm.getReference(listenerBean, clazz, creationalContext);
}
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
private void startListener(KafkaUpdatesListener kafkaUpdatesListener) {
try {
ExecutorService executorService =
InitialContext.doLookup("java:comp/DefaultManagedExecutorService");
executorService.submit(kafkaUpdatesListener);
} catch (NamingException e) {
// Handle NamingException
}
}
Before Bean Discovery
Process Annotated Types
After Type Discovery
Process Injection Point
Process Injection Target
Process Bean Attributes
After Deployment Validation
Before shutdown
Process Producer Method / Field
Process Observer Method
After Bean Discovery
Process Bean
Type discovery
Bean
discovery
Before shutdown
Running
public void stopListener(@Observes BeforeShutdown bsh) {
kafkaUpdatesListener.stopPolling();
}
Wrap up
• CDI is powerful
• Extensions are portable
• New features and improvements to add
• Create extensions for other libraries
• Evangelize
Resources
• The extension
https://github.com/bgjug/kafka-cdi-extension
• Showcase app
https://github.com/ivannov/kafka
• Article by Antoine
http://www.next-presso.com/2017/02/nobody-expects-the-cdi-portable-
extensions/
• Another Kafka CDI extension
https://github.com/aerogear/kafka-cdi

More Related Content

What's hot

Java build tool_comparison
Java build tool_comparisonJava build tool_comparison
Java build tool_comparisonManav Prasad
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle BuildAndres Almiray
 
Linecook - A Chef Alternative
Linecook - A Chef AlternativeLinecook - A Chef Alternative
Linecook - A Chef Alternativethinkerbot
 
Супер быстрая автоматизация тестирования на iOS
Супер быстрая автоматизация тестирования на iOSСупер быстрая автоматизация тестирования на iOS
Супер быстрая автоматизация тестирования на iOSSQALab
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbtFabio Fumarola
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2Yakov Fain
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.catPablo Godel
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testingPeter Edwards
 

What's hot (12)

Java build tool_comparison
Java build tool_comparisonJava build tool_comparison
Java build tool_comparison
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle Build
 
Linecook - A Chef Alternative
Linecook - A Chef AlternativeLinecook - A Chef Alternative
Linecook - A Chef Alternative
 
Супер быстрая автоматизация тестирования на iOS
Супер быстрая автоматизация тестирования на iOSСупер быстрая автоматизация тестирования на iOS
Супер быстрая автоматизация тестирования на iOS
 
Everything as a code
Everything as a codeEverything as a code
Everything as a code
 
Simple Build Tool
Simple Build ToolSimple Build Tool
Simple Build Tool
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbt
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testing
 
(Re)discover your AEM
(Re)discover your AEM(Re)discover your AEM
(Re)discover your AEM
 
De Java 8 a Java 17
De Java 8 a Java 17De Java 8 a Java 17
De Java 8 a Java 17
 

Similar to Bring Your Favorite Kafka to Java EE with CDI

OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016Stephen Fink
 
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docxJava Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docxpriestmanmable
 
Test your microservices with REST-Assured
Test your microservices with REST-AssuredTest your microservices with REST-Assured
Test your microservices with REST-AssuredMichel Schudel
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odysseyMike Hagedorn
 
Code your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnCode your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnDan Rinzel
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggStreamNative
 
Build pipelines with TeamCity and Kotlin DSL
Build pipelines with TeamCity and Kotlin DSLBuild pipelines with TeamCity and Kotlin DSL
Build pipelines with TeamCity and Kotlin DSLAnton Arhipov
 
Developing applications with Hyperledger Fabric SDK
Developing applications with Hyperledger Fabric SDKDeveloping applications with Hyperledger Fabric SDK
Developing applications with Hyperledger Fabric SDKHorea Porutiu
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIos890
 
The Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da AppleThe Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da AppleRodrigo Leite
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworksTomáš Kypta
 
AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...
AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...
AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...Amazon Web Services
 
AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...
AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...
AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...Amazon Web Services
 
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineCocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineChris Adamson
 
Extending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss ForgeExtending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss ForgeAntoine Sabot-Durand
 
Apache DeltaSpike
Apache DeltaSpikeApache DeltaSpike
Apache DeltaSpikeos890
 

Similar to Bring Your Favorite Kafka to Java EE with CDI (20)

OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016OpenWhisk Under the Hood -- London Oct 16 2016
OpenWhisk Under the Hood -- London Oct 16 2016
 
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docxJava Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
Java Advance 4deleteQuery.PNGJava Advance 4deleteQuerySucc.docx
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Test your microservices with REST-Assured
Test your microservices with REST-AssuredTest your microservices with REST-Assured
Test your microservices with REST-Assured
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odyssey
 
Java beans
Java beansJava beans
Java beans
 
Code your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnCode your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard Learn
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris Kellogg
 
Build pipelines with TeamCity and Kotlin DSL
Build pipelines with TeamCity and Kotlin DSLBuild pipelines with TeamCity and Kotlin DSL
Build pipelines with TeamCity and Kotlin DSL
 
Developing applications with Hyperledger Fabric SDK
Developing applications with Hyperledger Fabric SDKDeveloping applications with Hyperledger Fabric SDK
Developing applications with Hyperledger Fabric SDK
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODI
 
The Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da AppleThe Developer Conference - CloudKit, entendendo a Cloud da Apple
The Developer Conference - CloudKit, entendendo a Cloud da Apple
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...
AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...
AWS July Webinar Series: Overview: Build and Manage your APIs with Amazon API...
 
AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...
AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...
AWS July Webinar Series - Overview Build and Manage your APs with amazon api ...
 
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineCocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
 
Maven
MavenMaven
Maven
 
Extending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss ForgeExtending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss Forge
 
Apache DeltaSpike
Apache DeltaSpikeApache DeltaSpike
Apache DeltaSpike
 

Recently uploaded

Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Andrea Goulet
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersEmilyJiang23
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfQ-Advise
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAlluxio, Inc.
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesNeo4j
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024vaibhav130304
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityamy56318795
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems ApproachNeo4j
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationWave PLM
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)Max Lee
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...naitiksharma1124
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfFurqanuddin10
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1KnowledgeSeed
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfmbmh111980
 

Recently uploaded (20)

Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
AI Hackathon.pptx
AI                        Hackathon.pptxAI                        Hackathon.pptx
AI Hackathon.pptx
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 

Bring Your Favorite Kafka to Java EE with CDI

  • 1. Bring your favorite Kafka to Java EE with CDI Ivan St. Ivanov
  • 4. Showcase app User service Forum service User DB Forum DB Kafka
  • 5.
  • 6. CDI primer @ApplicationScoped public class UserModificationKafkaProducer { private KafkaProducer<String, String> kafkaProducer; public void userModified(User modifiedUser) { String record =
  • 7. CDI primer @ApplicationScoped public class UserModificationKafkaProducer { @Inject private KafkaProducer<String, String> kafkaProducer; public void userModified(User modifiedUser) { String record =
  • 8. CDI primer @ApplicationScoped public class UserModificationKafkaProducer { @Inject @KafkaProducerConfig(bootstrapServers = "mykafkahost:9090") private KafkaProducer<String, String> kafkaProducer; public void userModified(User modifiedUser) {
  • 9. CDI primer public @interface KafkaProducerConfig { Class keyType() default String.class; Class valueType() default String.class; String bootstrapServers() default "localhost:9092"; }
  • 10. CDI primer @ApplicationScoped public class KafkaProducerFactory { @Produces public <K,V> KafkaProducer<K, V> createProducer( InjectionPoint injectionPoint) { KafkaProducerConfig annotation = injectionPoint .getAnnotated() .getAnnotation(KafkaProducerConfig.class); Properties producerProperties = new Properties(); producerProperties.setProperty( "bootstrap.servers", annotation.bootstrapServers()); // Set other props return new KafkaProducer<>(producerProperties); } }
  • 11. CDI primer @ApplicationScoped public class UserModificationKafkaProducer { @Inject @KafkaProducerConfig(bootstrapServers = "mykafkahost:9090") private KafkaProducer<String, String> kafkaProducer; public void userModified(@Observes User
  • 12. CDI primer public class KafkaUpdatesListener implements Runnable { @Inject @KafkaConsumerConfig(subscriptions = "user") private KafkaConsumer<String, String> consumer; @Override public void run() { while (continuePolling) { ConsumerRecords<String, String> records = consumer.poll(100); if (!records.isEmpty()) { // Update microservice storage
  • 13. But what if... • Leave factories boilerplate to the framework • Leave polling updates to the framework • Do it this way: public class UserModificationKafkaConsumer { • @Consumes(topic = "user") public void listenForUsers( ConsumerRecord<String, String> record) { • String userJson = record.value(); • // Store the user in DB }
  • 14. CDI extensions •CDI magic •Hook into the lifecycle •Override default behavior •Portable across containers
  • 15. CDI extension prerequisites •Implement javax.enterprise.inject.spi.Extension •Observe events of interest •Register service provider
  • 16. Before Bean Discovery Process Annotated Types After Type Discovery Type discovery
  • 17. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery
  • 18. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Running
  • 19. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running
  • 20. Kafka CDI extension tasks • Register the factories and listener thread • Create Kafka Consumer for all @Consumes methods • Start polling consumers for changes • Invoke @Consumes methods when change happens
  • 21. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running public void addKafkaSpecificTypes( @Observes BeforeBeanDiscovery bbd, BeanManager beanManager) { bbd.addAnnotatedType( beanManager.createAnnotatedType(KafkaProducerFactory.class)); bbd.addAnnotatedType( beanManager.createAnnotatedType(KafkaUpdatesListener.class)); }
  • 22. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running public void collectConsumerMethods( @Observes @WithAnnotations(Consumes.class) ProcessAnnotatedType<?> pat) { pat.getAnnotatedType().getMethods().stream() .filter(m -> m.isAnnotationPresent(Consumes.class)) .forEach(m -> handleConsumerMethod(pat.getAnnotatedType(), m)); }
  • 23. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running private void handleConsumerMethod(AnnotatedType<?> clazz, AnnotatedMethod<?> am) { List<AnnotatedParameter<?>> parameters = am.getParameters(); if (parameters.size() != 1) { errors.add(new IllegalArgumentException( "@Consume methods should only have one parameter")); } else { consumerDescriptors.add(new KafkaConsumerDescriptor( clazz.getJavaClass(), am, am.getAnnotation(Consumes.class).topic())); } }
  • 24. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running public void startMonitoring(@Observes AfterDeploymentValidation adv, BeanManager bm) { if (!errors.isEmpty()) { errors.forEach(adv::addDeploymentProblem); } else { KafkaUpdatesListener kafkaUpdatesListener = initializeListener(bm); startListener(kafkaUpdatesListener, adv); this.kafkaUpdatesListener = kafkaUpdatesListener; } }
  • 25. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running private KafkaUpdatesListener initializeListener(BeanManager bm) { Class<KafkaUpdatesListener> clazz = KafkaUpdatesListener.class; KafkaUpdatesListener reference = createBean(bm, clazz); consumerDescriptors.forEach(m -> addTopicToListen(m, reference)); return reference; }
  • 26. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running static Object createBean(BeanManager bm, Class<?> clazz) { Set<Bean<?>> listenerBeans = bm.getBeans(clazz); Bean<?> listenerBean = bm.resolve(listenerBeans); CreationalContext<?> creationalContext = bm.createCreationalContext(listenerBean); return bm.getReference(listenerBean, clazz, creationalContext); }
  • 27. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running private void startListener(KafkaUpdatesListener kafkaUpdatesListener) { try { ExecutorService executorService = InitialContext.doLookup("java:comp/DefaultManagedExecutorService"); executorService.submit(kafkaUpdatesListener); } catch (NamingException e) { // Handle NamingException } }
  • 28. Before Bean Discovery Process Annotated Types After Type Discovery Process Injection Point Process Injection Target Process Bean Attributes After Deployment Validation Before shutdown Process Producer Method / Field Process Observer Method After Bean Discovery Process Bean Type discovery Bean discovery Before shutdown Running public void stopListener(@Observes BeforeShutdown bsh) { kafkaUpdatesListener.stopPolling(); }
  • 29.
  • 30. Wrap up • CDI is powerful • Extensions are portable • New features and improvements to add • Create extensions for other libraries • Evangelize
  • 31. Resources • The extension https://github.com/bgjug/kafka-cdi-extension • Showcase app https://github.com/ivannov/kafka • Article by Antoine http://www.next-presso.com/2017/02/nobody-expects-the-cdi-portable- extensions/ • Another Kafka CDI extension https://github.com/aerogear/kafka-cdi