Apache Kafka-Spring Kafka生产消费@KafkaListener源码解析

简介: Apache Kafka-Spring Kafka生产消费@KafkaListener源码解析

20191116123525638.png


概述


【依赖】

  <dependency>
      <groupId>org.springframework.kafka</groupId>
      <artifactId>spring-kafka</artifactId>
  </dependency>


【配置】

#kafka
spring.kafka.bootstrap-servers=10.11.114.247:9092
spring.kafka.producer.acks=1
spring.kafka.producer.retries=3
spring.kafka.producer.batch-size=16384
spring.kafka.producer.buffer-memory=33554432
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer
spring.kafka.consumer.group-id=zfprocessor_group
spring.kafka.consumer.enable-auto-commit=false
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties.spring.json.trusted.packages=com.artisan.common.entity.messages
spring.kafka.consumer.max-poll-records=500
spring.kafka.consumer.fetch-min-size=10
spring.kafka.consumer.fetch-max-wait=10000ms
spring.kafka.listener.missing-topics-fatal=false
spring.kafka.listener.type=batch
spring.kafka.listener.ack-mode=manual
logging.level.org.springframework.kafka=ERROR
logging.level.org.apache.kafka=ERROR


Spring-kafka生产者源码流程


ListenableFuture<SendResult<Object, Object>> result = kafkaTemplate.send(TOPICA.TOPIC, messageMock);


主要的源码流程如下


20210401231308744.png

Spring-kafka消费者源码流程(@EnableKafka@KafkaListener

消费的话,比较复杂

 @KafkaListener(topics = TOPICA.TOPIC ,groupId = CONSUMER_GROUP_PREFIX + TOPICA.TOPIC)
    public void onMessage(MessageMock messageMock){
        logger.info("【接受到消息][线程:{} 消息内容:{}]", Thread.currentThread().getName(), messageMock);
    }


划重点,主要关注


Flow


20210402001046269.png


作为引子,我们继续来梳理下源码


20210401232847522.png

继续

20210401232957759.png

继续


20210401233101276.png

KafkaBootstrapConfiguration的主要功能是创建两个bean


KafkaListenerAnnotationBeanPostProcessor


实现了如下接口

implements BeanPostProcessor, Ordered, BeanFactoryAware, SmartInitializingSingleton


主要功能就是监听@KafkaListener注解 。 bean的后置处理器 需要重写 postProcessAfterInitialization

@Override
  public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    if (!this.nonAnnotatedClasses.contains(bean.getClass())) {
       // 获取对应的class
      Class<?> targetClass = AopUtils.getTargetClass(bean);
      // 查找类是否有@KafkaListener注解
      Collection<KafkaListener> classLevelListeners = findListenerAnnotations(targetClass);
      final boolean hasClassLevelListeners = classLevelListeners.size() > 0;
      final List<Method> multiMethods = new ArrayList<>();
      // 查找类中方法上是否有对应的@KafkaListener注解,
      Map<Method, Set<KafkaListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
          (MethodIntrospector.MetadataLookup<Set<KafkaListener>>) method -> {
            Set<KafkaListener> listenerMethods = findListenerAnnotations(method);
            return (!listenerMethods.isEmpty() ? listenerMethods : null);
          });
      if (hasClassLevelListeners) {
        Set<Method> methodsWithHandler = MethodIntrospector.selectMethods(targetClass,
            (ReflectionUtils.MethodFilter) method ->
                AnnotationUtils.findAnnotation(method, KafkaHandler.class) != null);
        multiMethods.addAll(methodsWithHandler);
      }
      if (annotatedMethods.isEmpty()) {
        this.nonAnnotatedClasses.add(bean.getClass());
        this.logger.trace(() -> "No @KafkaListener annotations found on bean type: " + bean.getClass());
      }
      else {
        // Non-empty set of methods
        for (Map.Entry<Method, Set<KafkaListener>> entry : annotatedMethods.entrySet()) {
          Method method = entry.getKey();
          for (KafkaListener listener : entry.getValue()) {
            // 处理@KafkaListener注解   重点看 
            processKafkaListener(listener, method, bean, beanName);
          }
        }
        this.logger.debug(() -> annotatedMethods.size() + " @KafkaListener methods processed on bean '"
              + beanName + "': " + annotatedMethods);
      }
      if (hasClassLevelListeners) {
        processMultiMethodListeners(classLevelListeners, multiMethods, bean, beanName);
      }
    }
    return bean;
  }

重点方法

  protected void processKafkaListener(KafkaListener kafkaListener, Method method, Object bean, String beanName) {
    Method methodToUse = checkProxy(method, bean);
    MethodKafkaListenerEndpoint<K, V> endpoint = new MethodKafkaListenerEndpoint<>();
    endpoint.setMethod(methodToUse);
    processListener(endpoint, kafkaListener, bean, methodToUse, beanName);
  }


继续 processListener

protected void processListener(MethodKafkaListenerEndpoint<?, ?> endpoint, KafkaListener kafkaListener,
      Object bean, Object adminTarget, String beanName) {
    String beanRef = kafkaListener.beanRef();
    if (StringUtils.hasText(beanRef)) {
      this.listenerScope.addListener(beanRef, bean);
    }
    // 构建 endpoint
    endpoint.setBean(bean);
    endpoint.setMessageHandlerMethodFactory(this.messageHandlerMethodFactory);
    endpoint.setId(getEndpointId(kafkaListener));
    endpoint.setGroupId(getEndpointGroupId(kafkaListener, endpoint.getId()));
    endpoint.setTopicPartitions(resolveTopicPartitions(kafkaListener));
    endpoint.setTopics(resolveTopics(kafkaListener));
    endpoint.setTopicPattern(resolvePattern(kafkaListener));
    endpoint.setClientIdPrefix(resolveExpressionAsString(kafkaListener.clientIdPrefix(), "clientIdPrefix"));
    String group = kafkaListener.containerGroup();
    if (StringUtils.hasText(group)) {
      Object resolvedGroup = resolveExpression(group);
      if (resolvedGroup instanceof String) {
        endpoint.setGroup((String) resolvedGroup);
      }
    }
    String concurrency = kafkaListener.concurrency();
    if (StringUtils.hasText(concurrency)) {
      endpoint.setConcurrency(resolveExpressionAsInteger(concurrency, "concurrency"));
    }
    String autoStartup = kafkaListener.autoStartup();
    if (StringUtils.hasText(autoStartup)) {
      endpoint.setAutoStartup(resolveExpressionAsBoolean(autoStartup, "autoStartup"));
    }
    resolveKafkaProperties(endpoint, kafkaListener.properties());
    endpoint.setSplitIterables(kafkaListener.splitIterables());
    KafkaListenerContainerFactory<?> factory = null;
    String containerFactoryBeanName = resolve(kafkaListener.containerFactory());
    if (StringUtils.hasText(containerFactoryBeanName)) {
      Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name");
      try {
        factory = this.beanFactory.getBean(containerFactoryBeanName, KafkaListenerContainerFactory.class);
      }
      catch (NoSuchBeanDefinitionException ex) {
        throw new BeanInitializationException("Could not register Kafka listener endpoint on [" + adminTarget
            + "] for bean " + beanName + ", no " + KafkaListenerContainerFactory.class.getSimpleName()
            + " with id '" + containerFactoryBeanName + "' was found in the application context", ex);
      }
    }
    endpoint.setBeanFactory(this.beanFactory);
    String errorHandlerBeanName = resolveExpressionAsString(kafkaListener.errorHandler(), "errorHandler");
    if (StringUtils.hasText(errorHandlerBeanName)) {
      endpoint.setErrorHandler(this.beanFactory.getBean(errorHandlerBeanName, KafkaListenerErrorHandler.class));
    }
    // 将endpoint注册到registrar
    this.registrar.registerEndpoint(endpoint, factory);
    if (StringUtils.hasText(beanRef)) {
      this.listenerScope.removeListener(beanRef);
    }
  }


继续看 registerEndpoint

  public void registerEndpoint(KafkaListenerEndpoint endpoint, KafkaListenerContainerFactory<?> factory) {
    Assert.notNull(endpoint, "Endpoint must be set");
    Assert.hasText(endpoint.getId(), "Endpoint id must be set");
    // Factory may be null, we defer the resolution right before actually creating the container
    // 把endpoint封装为KafkaListenerEndpointDescriptor
    KafkaListenerEndpointDescriptor descriptor = new KafkaListenerEndpointDescriptor(endpoint, factory);
    synchronized (this.endpointDescriptors) {
      if (this.startImmediately) { // Register and start immediately
        this.endpointRegistry.registerListenerContainer(descriptor.endpoint,
            resolveContainerFactory(descriptor), true);
      }
      else {
         // 将descriptor添加到endpointDescriptors
        this.endpointDescriptors.add(descriptor);
      }
    }
  }



总的来看: 得到一个含有KafkaListener基本信息的Endpoint,将Endpoint被封装到KafkaListenerEndpointDescriptor,KafkaListenerEndpointDescriptor被添加到KafkaListenerEndpointRegistrar.endpointDescriptors中,至此这部分的流程结束了,感觉没有下文呀。

20210402223326415.png


KafkaListenerEndpointRegistrar.endpointDescriptors 这个List中的数据怎么用呢?

public class KafkaListenerEndpointRegistrar implements BeanFactoryAware, InitializingBean {}


KafkaListenerEndpointRegistrar 实现了 InitializingBean 接口,重写 afterPropertiesSet,该方法会在bean实例化完成后执行

  @Override
  public void afterPropertiesSet() {
    registerAllEndpoints();
  }


继续 registerAllEndpoints();

  protected void registerAllEndpoints() {
    synchronized (this.endpointDescriptors) {
    // 遍历KafkaListenerEndpointDescriptor 
      for (KafkaListenerEndpointDescriptor descriptor : this.endpointDescriptors) {
          // 注册 
        this.endpointRegistry.registerListenerContainer(
            descriptor.endpoint, resolveContainerFactory(descriptor));
      }
      this.startImmediately = true;  // trigger immediate startup
    }
  }


继续

  public void registerListenerContainer(KafkaListenerEndpoint endpoint, KafkaListenerContainerFactory<?> factory) {
    registerListenerContainer(endpoint, factory, false);
  }


go

public void registerListenerContainer(KafkaListenerEndpoint endpoint, KafkaListenerContainerFactory<?> factory,
      boolean startImmediately) {
    Assert.notNull(endpoint, "Endpoint must not be null");
    Assert.notNull(factory, "Factory must not be null");
    String id = endpoint.getId();
    Assert.hasText(id, "Endpoint id must not be empty");
    synchronized (this.listenerContainers) {
      Assert.state(!this.listenerContainers.containsKey(id),
          "Another endpoint is already registered with id '" + id + "'");   
        // 创建Endpoint对应的MessageListenerContainer,将创建好的MessageListenerContainer放入listenerContainers
      MessageListenerContainer container = createListenerContainer(endpoint, factory);
      this.listenerContainers.put(id, container);
      // 如果KafkaListener注解中有对应的group信息,则将container添加到对应的group中
      if (StringUtils.hasText(endpoint.getGroup()) && this.applicationContext != null) {
        List<MessageListenerContainer> containerGroup;
        if (this.applicationContext.containsBean(endpoint.getGroup())) {
          containerGroup = this.applicationContext.getBean(endpoint.getGroup(), List.class);
        }
        else {
          containerGroup = new ArrayList<MessageListenerContainer>();
          this.applicationContext.getBeanFactory().registerSingleton(endpoint.getGroup(), containerGroup);
        }
        containerGroup.add(container);
      }
      if (startImmediately) {
        startIfNecessary(container);
      }
    }
  }


相关文章
|
9月前
|
缓存 安全 Java
Spring Security通用权限管理模型解析
Spring Security作为Spring生态的核心安全框架,结合RBAC与ACL权限模型,基于IoC与AOP构建灵活、可扩展的企业级权限控制体系,涵盖认证、授权流程及数据库设计、性能优化等实现策略。
640 0
|
9月前
|
缓存 安全 Java
Spring Security权限管理解析
Spring Security是Spring生态中的核心安全框架,采用认证与授权分离架构,提供高度可定制的权限管理方案。其基于过滤器链实现认证流程,通过SecurityContextHolder管理用户状态,并结合RBAC模型与动态权限决策,支持细粒度访问控制。通过扩展点如自定义投票器、注解式校验与前端标签,可灵活适配多租户、API网关等复杂场景。结合缓存优化与无状态设计,适用于高并发与前后端分离架构。
632 0
|
9月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
2944 0
|
9月前
|
SQL Java 数据库连接
Spring Data JPA 技术深度解析与应用指南
本文档全面介绍 Spring Data JPA 的核心概念、技术原理和实际应用。作为 Spring 生态系统中数据访问层的关键组件,Spring Data JPA 极大简化了 Java 持久层开发。本文将深入探讨其架构设计、核心接口、查询派生机制、事务管理以及与 Spring 框架的集成方式,并通过实际示例展示如何高效地使用这一技术。本文档约1500字,适合有一定 Spring 和 JPA 基础的开发者阅读。
852 0
|
8月前
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
8月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
9月前
|
消息中间件 监控 Java
Apache Kafka 分布式流处理平台技术详解与实践指南
本文档全面介绍 Apache Kafka 分布式流处理平台的核心概念、架构设计和实践应用。作为高吞吐量、低延迟的分布式消息系统,Kafka 已成为现代数据管道和流处理应用的事实标准。本文将深入探讨其生产者-消费者模型、主题分区机制、副本复制、流处理API等核心机制,帮助开发者构建可靠、可扩展的实时数据流处理系统。
821 4
|
9月前
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
1714 1
|
9月前
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
762 0
|
9月前
|
安全 Java 数据安全/隐私保护
Spring Security 核心技术解析与实践指南
本文档深入探讨 Spring Security 框架的核心架构、关键组件和实际应用。作为 Spring 生态系统中负责安全认证与授权的关键组件,Spring Security 为 Java 应用程序提供了全面的安全服务。本文将系统介绍其认证机制、授权模型、过滤器链原理、OAuth2 集成以及最佳实践,帮助开发者构建安全可靠的企业级应用。
504 0

热门文章

最新文章

推荐镜像

更多
  • DNS