Bring your favorite Kafka to Java EE with CDI

Slides:



Advertisements
Similar presentations
Practical Session 6 Multitasking vs. multithreading Threads Concurrency vs. Parallelism Java Threads Thread confinement Object/Class Immutability.
Advertisements

JSF Portlet Backing Beans and UI Components Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in.
13/04/2015Client-server Programming1 Block 6: Threads 1 Jin Sa.
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Written by: Dr. JJ Shepherd
Mari Göransson - KaU - Datavetenskap - DAVD11 1 Java Beans - Events and Properties -
JBoss Seam: Contextual Components Jason Bechtel
Internet Technologies 1 Master of Information System Management Java Server Faces Model/View/Controller Design Pattern for Web Development Slides.
Objects and Classes First Programming Concepts. 14/10/2004Lecture 1a: Introduction 2 Fundamental Concepts object class method parameter data type.
Ch 13. Features Found Only in Java Timothy Budd Oregon State University.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L20 (Chapter 24) Multithreading.
5.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
Neal Stublen Practice Solution  Create a new solution  Add a WinForms project  Add a Class Library project  Reference the library.
GT3 Tutorial Chapter 5, 6, and 7 Lecture for Cluster and Grid Computing, CSCE 490/590 Fall 2004, University of Arkansas, Dr. Amy Apon
Pittsburgh Java User Group– Dec Java PureFaces: A JSF Framework Extension.
Spring Overview, Application demo -Midhila Paineni 09/23/2011 Spring Overview, Application demo9/8/20151.
Chapter 10 Introduction to Components. Process Phases Discussed in This Chapter Requirements Analysis Design Implementation ArchitectureFramework Detailed.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An.
1 Stateful Session Beans Stateless Session Beans Michael Brockway Sajjad Shami Northumbria University School of Computing, Engineering & Information Sciences.
Web applications using JavaServer Faces (JSF) A brief introduction 1JavaServer Faces (JSF)
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
1 Kuali Nervous System (KNS) Part 2 Presented by: Jerry Neal – KFS Development Manager Geoff McGregor – KC Lead Developer Brian McGough – KRice Project.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
JSF Framework Java Server Faces Presented by Songkran Totiya (6/10/2014)
Introduction to Spring Web Flow Andrew Petro Software Developer Unicon, Inc. Jasig 2011 Westminster, CO 23 May 2011 © Copyright Unicon, Inc., Some.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Sofia, Bulgaria | 9-10 October ASP.NET: Developing Portal UI With Web Parts Goksin Bakir Yage Ltd Microsoft Regional Director, MEA Goksin Bakir Yage Ltd.
Chính phủ điện tử TS. Phạm Văn Tính Khoa CNTT, ĐH Nông Lâm TP.HCM
Java Beans. Definitions A reusable software component that can be manipulated visually in a ‘builder tool’. (from JavaBean Specification) The JavaBeans.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
Professional Java EE Design Patterns Alex alextheedom.com.
Jonathan Gallimore | Tomitribe Cluster your application with JCache and CDI.
Java EE - JSR 303 Bean validation - Pierre-Johan CHARTRE
Test it! Unit, mocking and in-container Meet Arquillian! Ivan St. Ivanov.
Written by: Dr. JJ Shepherd
Messageforge – A Messaging Framework Jawaid Hakim  Introduction  Requirements for Successful Development  CodeStreet Message Framework  Features 
SDJ INFOSOFT PVT. LTD. 2 BROWSERBROWSER JSP JavaBean DB Req Res Application Layer Enterprise server/Data Sources.
EJB. Introduction Enterprise Java Beans is a specification for creating server- side scalable, transactional, multi-user secure enterprise-level applications.
Test Java EE applications with Arquillian Ivan St. Ivanov.
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
The Holmes Platform and Applications
Written by: Dr. JJ Shepherd
Actions and Behaviours
OPERATING SYSTEM CONCEPT AND PRACTISE
Java Programming Language
Java Beans Sagun Dhakhwa.
Delegates and Events 14: Delegates and Events
Customizing your device experience with assigned access
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
EE 422C Java FX.
Mike Dickson Tidal Software
null, true, and false are also reserved.
Android Topics UI Thread and Limited processing resources
Java Lesson 36 Mr. Kalmes.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Android Topics Asynchronous Callsbacks
Objects First with Java A Practical Introduction using BlueJ
9. Threads SE2811 Software Component Design
CIS 199 Final Review.
Threads in Java James Brucker.
Objects First with Java A Practical Introduction using BlueJ
Using threads for long running tasks.
Threads and Multithreading
Preference Activity class
Testing your DAO’s with Java
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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 Kafka User DB Forum DB

CDI primer @ApplicationScoped public class UserModificationObserver {      private KafkaProducer<String, String> kafkaProducer;        public void userModified(User modifiedUser) {         String record = modifiedUser.toJson().toString();         kafkaProducer.send(new ProducerRecord<>("user",                            record));     } }

CDI primer @ApplicationScoped public class UserModificationObserver {      @Inject      private KafkaProducer<String, String> kafkaProducer;        public void userModified(User modifiedUser) {         String record = modifiedUser.toJson().toString();         kafkaProducer.send(new ProducerRecord<>("user",                            record));     } }

CDI primer @ApplicationScoped public class UserModificationObserver {      @Inject      @KafkaProducerConfig(bootstrapServers = "mykafkahost:9090")      private KafkaProducer<String, String> kafkaProducer;        public void userModified(User modifiedUser) {         String record = modifiedUser.toJson().toString();         kafkaProducer.send(new ProducerRecord<>("user",                            record));     } }

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 UserModificationObserver {      @Inject      @KafkaProducerConfig(bootstrapServers = "mykafkahost:9090")      private KafkaProducer<String, String> kafkaProducer;        public void userModified(@Observes User modifiedUser) {         String record = modifiedUser.toJson().toString();         kafkaProducer.send(new ProducerRecord<>("user",                            record));     } }

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

Process Annotated Types Before Bean Discovery Type discovery Process Annotated Types After Type Discovery

Type discovery Bean discovery Before Bean Discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation

Type discovery Bean discovery Running Before Bean Discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

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

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types public void addKafkaSpecificTypes(     @Observes BeforeBeanDiscovery bbd,               BeanManager beanManager) {     bbd.addAnnotatedType(         beanManager.createAnnotatedType(KafkaProducerFactory.class));     bbd.addAnnotatedType(         beanManager.createAnnotatedType(KafkaUpdatesListener.class)); } After Type Discovery Bean discovery Process Injection Point Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point 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)); } Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point 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()));     } } Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery 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;     } } Bean discovery Process Injection Point Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point Process Injection Target Process Bean Attributes private KafkaUpdatesListener initializeListener(BeanManager bm) {     Class<KafkaUpdatesListener> clazz = KafkaUpdatesListener.class;     KafkaUpdatesListener reference = createBean(bm, clazz);     consumerDescriptors.forEach(m -> addTopicToListen(m, reference));     return reference; } Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point Process Injection Target 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); } Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery Bean discovery private void startListener(KafkaUpdatesListener kafkaUpdatesListener) {     try {         ExecutorService executorService =          InitialContext.doLookup("java:comp/DefaultManagedExecutorService");               executorService.submit(kafkaUpdatesListener);     } catch (NamingException e) {         // Handle NamingException     } } Process Injection Point Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

Type discovery Bean discovery Running Before shutdown Before Bean Discovery Type discovery Process Annotated Types After Type Discovery Bean discovery Process Injection Point Process Injection Target Process Bean Attributes Process Bean Process Producer Method / Field Process Observer Method public void stopListener(@Observes BeforeShutdown bsh) {     kafkaUpdatesListener.stopPolling(); } After Bean Discovery After Deployment Validation Running Before shutdown Before shutdown

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