Kafka系列之@KafkaListener常用参数详解

@KafkaListener 详解及消息消费启停控制 如果不想使用默认的"kafkaListenerContainerFactory"容器工厂,则必须手动创建一个"ConcurrentKafkaListenerContainerFactory"类的实例,并且其bean name 不能叫"kafkaListenerContainerFactory"(不然与默认的工厂实例重名了),然后把该对象加入spring容器中。另外,这两个消费者属于同一个组,Topic只有8个分区,2个消费者共10个线程,一个线程消费一个分区,所以必然有两个线程最后属于空闲状态。 阅读详情
AI摘要

本文深入解析了Spring Kafka中@KafkaListener注解的众多配置参数,包括topics、groupId、concurrency等,展示了如何通过这些参数灵活定制Kafka消息监听器行为。

@KafkaListener 注解提供了许多可配置的参数,以便更灵活地定制 Kafka 消息监听器的行为。

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.kafka.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.messaging.handler.annotation.MessageMapping;

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@MessageMapping
@Documented
@Repeatable(KafkaListeners.class)
public @interface KafkaListener {
    String id() default "";

    String containerFactory() default "";

    String[] topics() default {};

    String topicPattern() default "";

    TopicPartition[] topicPartitions() default {};

    String containerGroup() default "";

    String errorHandler() default "";

    String groupId() default "";

    boolean idIsGroup() default true;

    String clientIdPrefix() default "";

    String beanRef() default "__listener";

    String concurrency() default "";

    String autoStartup() default "";

    String[] properties() default {};

    boolean splitIterables() default true;

    String contentTypeConverter() default "";

    String batch() default "";

    String filter() default "";

    String info() default "";

    String containerPostProcessor() default "";
}

topics

指定监听的 Kafka 主题,可以是一个字符串数组。这是最基本的参数,它定义了监听器将从哪个或哪些主题接收消息。

 @KafkaListener(topics = "my-topic")

groupId

指定 Kafka 消费者组的 ID。每个消费者都有自己所属的组。一个组中可以有多个消费者。

 @KafkaListener(groupId = "my-group", topics = "my-topic")

id

描述: 每个Listener实例的重要标识。默认是一个自动生成的唯一 ID。如果不指定groupId,那么id将直接作为groupId。在同一应用中,如果有多个监听器,可以使用不同的id来标识不同的监听器容器。

 @KafkaListener(id = "myListener", topics = "my-topic", groupId = "my-group")

concurrency

指定并发消费者的数量,即监听器容器的线程数。控制监听器的并发性,每个线程会创建一个消费者实例。较大的并发性可以提高消息处理的吞吐量。
会覆盖消费者工厂中的concurrency,这里的并发数就是多线程消费; 比如说单机情况下,你设置了3; 相当于就是启动了3个客户端来分配消费分区;分布式情况 总线程数=concurrency*机器数量; 并不是设置越多越好,视情况而定,一般情况下总线程数=topic的分片数最为合理。

 /**
     * 监听器工厂 
     * @return
     */
    @Bean
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>> concurrencyFactory() {
        ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(kafkaConsumerFactory());
        factory.setConcurrency(6);
        return factory;
    }
@KafkaListener(topics = "my-topic", , containerFactory = "concurrencyFactory", concurrency = "3")

虽然使用的工厂是concurrencyFactory(concurrency配置了6); 但是他最终生成的监听器数量是3。

properties

指定其他的消费者配置属性,以键值对的形式提供。这种方式允许你通过注解的方式灵活地设置特定的消费者属性,而不必在全局配置文件中进行设置。请确保设置的属性是合法的 Kafka 消费者属性,并符合你的应用需求。
kafka中的属性看org.apache.kafka.clients.consumer.ConsumerConfig,同名的都可以修改掉。

@KafkaListener(topics = "my-topic", properties = {"enable.auto.commit=false", "auto.offset.reset=earliest","max.poll.interval.ms:300000","max.poll.records:1"})

org.apache.kafka.clients.consumer.ConsumerConfig类中的常量定义抄录如下:

public class ConsumerConfig extends AbstractConfig {
    public static final String GROUP_ID_CONFIG = "group.id";
    private static final String GROUP_ID_DOC = "A unique string that identifies the consumer group this consumer belongs to. This property is required if the consumer uses either the group management functionality by using <code>subscribe(topic)</code> or the Kafka-based offset management strategy.";
    public static final String GROUP_INSTANCE_ID_CONFIG = "group.instance.id";
    private static final String GROUP_INSTANCE_ID_DOC = "A unique identifier of the consumer instance provided by the end user. Only non-empty strings are permitted. If set, the consumer is treated as a static member, which means that only one instance with this ID is allowed in the consumer group at any time. This can be used in combination with a larger session timeout to avoid group rebalances caused by transient unavailability (e.g. process restarts). If not set, the consumer will join the group as a dynamic member, which is the traditional behavior.";
    public static final String MAX_POLL_RECORDS_CONFIG = "max.poll.records";
    private static final String MAX_POLL_RECORDS_DOC = "The maximum number of records returned in a single call to poll(). Note, that <code>max.poll.records</code> does not impact the underlying fetching behavior. The consumer will cache the records from each fetch request and returns them incrementally from each poll.";
    public static final String MAX_POLL_INTERVAL_MS_CONFIG = "max.poll.interval.ms";
    private static final String MAX_POLL_INTERVAL_MS_DOC = "The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. For consumers using a non-null <code>group.instance.id</code> which reach this timeout, partitions will not be immediately reassigned. Instead, the consumer will stop sending heartbeats and partitions will be reassigned after expiration of <code>session.timeout.ms</code>. This mirrors the behavior of a static consumer which has shutdown.";
    public static final String SESSION_TIMEOUT_MS_CONFIG = "session.timeout.ms";
    private static final String SESSION_TIMEOUT_MS_DOC = "The timeout used to detect client failures when using Kafka's group management facility. The client sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are received by the broker before the expiration of this session timeout, then the broker will remove this client from the group and initiate a rebalance. Note that the value must be in the allowable range as configured in the broker configuration by <code>group.min.session.timeout.ms</code> and <code>group.max.session.timeout.ms</code>.";
    public static final String HEARTBEAT_INTERVAL_MS_CONFIG = "heartbeat.interval.ms";
    private static final String HEARTBEAT_INTERVAL_MS_DOC = "The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than <code>session.timeout.ms</code>, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances.";
    public static final String BOOTSTRAP_SERVERS_CONFIG = "bootstrap.servers";
    public static final String CLIENT_DNS_LOOKUP_CONFIG = "client.dns.lookup";
    public static final String ENABLE_AUTO_COMMIT_CONFIG = "enable.auto.commit";
    private static final String ENABLE_AUTO_COMMIT_DOC = "If true the consumer's offset will be periodically committed in the background.";
    public static final String AUTO_COMMIT_INTERVAL_MS_CONFIG = "auto.commit.interval.ms";
    private static final String AUTO_COMMIT_INTERVAL_MS_DOC = "The frequency in milliseconds that the consumer offsets are auto-committed to Kafka if <code>enable.auto.commit</code> is set to <code>true</code>.";
    public static final String PARTITION_ASSIGNMENT_STRATEGY_CONFIG = "partition.assignment.strategy";
    private static final String PARTITION_ASSIGNMENT_STRATEGY_DOC = "A list of class names or class types, ordered by preference, of supported partition assignment strategies that the client will use to distribute partition ownership amongst consumer instances when group management is used. Available options are:<ul><li><code>org.apache.kafka.clients.consumer.RangeAssignor</code>: Assigns partitions on a per-topic basis.</li><li><code>org.apache.kafka.clients.consumer.RoundRobinAssignor</code>: Assigns partitions to consumers in a round-robin fashion.</li><li><code>org.apache.kafka.clients.consumer.StickyAssignor</code>: Guarantees an assignment that is maximally balanced while preserving as many existing partition assignments as possible.</li><li><code>org.apache.kafka.clients.consumer.CooperativeStickyAssignor</code>: Follows the same StickyAssignor logic, but allows for cooperative rebalancing.</li></ul><p>The default assignor is [RangeAssignor, CooperativeStickyAssignor], which will use the RangeAssignor by default, but allows upgrading to the CooperativeStickyAssignor with just a single rolling bounce that removes the RangeAssignor from the list.</p><p>Implementing the <code>org.apache.kafka.clients.consumer.ConsumerPartitionAssignor</code> interface allows you to plug in a custom assignment strategy.</p>";
    public static final String AUTO_OFFSET_RESET_CONFIG = "auto.offset.reset";
    public static final String AUTO_OFFSET_RESET_DOC = "What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server (e.g. because that data has been deleted): <ul><li>earliest: automatically reset the offset to the earliest offset<li>latest: automatically reset the offset to the latest offset</li><li>none: throw exception to the consumer if no previous offset is found for the consumer's group</li><li>anything else: throw exception to the consumer.</li></ul>";
    public static final String FETCH_MIN_BYTES_CONFIG = "fetch.min.bytes";
    private static final String FETCH_MIN_BYTES_DOC = "The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. The default setting of 1 byte means that fetch requests are answered as soon as a single byte of data is available or the fetch request times out waiting for data to arrive. Setting this to something greater than 1 will cause the server to wait for larger amounts of data to accumulate which can improve server throughput a bit at the cost of some additional latency.";
    public static final String FETCH_MAX_BYTES_CONFIG = "fetch.max.bytes";
    private static final String FETCH_MAX_BYTES_DOC = "The maximum amount of data the server should return for a fetch request. Records are fetched in batches by the consumer, and if the first record batch in the first non-empty partition of the fetch is larger than this value, the record batch will still be returned to ensure that the consumer can make progress. As such, this is not a absolute maximum. The maximum record batch size accepted by the broker is defined via <code>message.max.bytes</code> (broker config) or <code>max.message.bytes</code> (topic config). Note that the consumer performs multiple fetches in parallel.";
    public static final int DEFAULT_FETCH_MAX_BYTES = 52428800;
    public static final String FETCH_MAX_WAIT_MS_CONFIG = "fetch.max.wait.ms";
    private static final String FETCH_MAX_WAIT_MS_DOC = "The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by fetch.min.bytes.";
    public static final String METADATA_MAX_AGE_CONFIG = "metadata.max.age.ms";
    public static final String MAX_PARTITION_FETCH_BYTES_CONFIG = "max.partition.fetch.bytes";
    private static final String MAX_PARTITION_FETCH_BYTES_DOC = "The maximum amount of data per-partition the server will return. Records are fetched in batches by the consumer. If the first record batch in the first non-empty partition of the fetch is larger than this limit, the batch will still be returned to ensure that the consumer can make progress. The maximum record batch size accepted by the broker is defined via <code>message.max.bytes</code> (broker config) or <code>max.message.bytes</code> (topic config). See fetch.max.bytes for limiting the consumer request size.";
    public static final int DEFAULT_MAX_PARTITION_FETCH_BYTES = 1048576;
    public static final String SEND_BUFFER_CONFIG = "send.buffer.bytes";
    public static final String RECEIVE_BUFFER_CONFIG = "receive.buffer.bytes";
    public static final String CLIENT_ID_CONFIG = "client.id";
    public static final String CLIENT_RACK_CONFIG = "client.rack";
    public static final String RECONNECT_BACKOFF_MS_CONFIG = "reconnect.backoff.ms";
    public static final String RECONNECT_BACKOFF_MAX_MS_CONFIG = "reconnect.backoff.max.ms";
    public static final String RETRY_BACKOFF_MS_CONFIG = "retry.backoff.ms";
    public static final String METRICS_SAMPLE_WINDOW_MS_CONFIG = "metrics.sample.window.ms";
    public static final String METRICS_NUM_SAMPLES_CONFIG = "metrics.num.samples";
    public static final String METRICS_RECORDING_LEVEL_CONFIG = "metrics.recording.level";
    public static final String METRIC_REPORTER_CLASSES_CONFIG = "metric.reporters";
    /** @deprecated */
    @Deprecated
    public static final String AUTO_INCLUDE_JMX_REPORTER_CONFIG = "auto.include.jmx.reporter";
    public static final String CHECK_CRCS_CONFIG = "check.crcs";
    private static final String CHECK_CRCS_DOC = "Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance.";
    public static final String KEY_DESERIALIZER_CLASS_CONFIG = "key.deserializer";
    public static final String KEY_DESERIALIZER_CLASS_DOC = "Deserializer class for key that implements the <code>org.apache.kafka.common.serialization.Deserializer</code> interface.";
    public static final String VALUE_DESERIALIZER_CLASS_CONFIG = "value.deserializer";
    public static final String VALUE_DESERIALIZER_CLASS_DOC = "Deserializer class for value that implements the <code>org.apache.kafka.common.serialization.Deserializer</code> interface.";
    public static final String SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG = "socket.connection.setup.timeout.ms";
    public static final String SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG = "socket.connection.setup.timeout.max.ms";
    public static final String CONNECTIONS_MAX_IDLE_MS_CONFIG = "connections.max.idle.ms";
    public static final String REQUEST_TIMEOUT_MS_CONFIG = "request.timeout.ms";
    private static final String REQUEST_TIMEOUT_MS_DOC = "The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.";
    public static final String DEFAULT_API_TIMEOUT_MS_CONFIG = "default.api.timeout.ms";
    public static final String INTERCEPTOR_CLASSES_CONFIG = "interceptor.classes";
    public static final String INTERCEPTOR_CLASSES_DOC = "A list of classes to use as interceptors. Implementing the <code>org.apache.kafka.clients.consumer.ConsumerInterceptor</code> interface allows you to intercept (and possibly mutate) records received by the consumer. By default, there are no interceptors.";
    public static final String EXCLUDE_INTERNAL_TOPICS_CONFIG = "exclude.internal.topics";
    private static final String EXCLUDE_INTERNAL_TOPICS_DOC = "Whether internal topics matching a subscribed pattern should be excluded from the subscription. It is always possible to explicitly subscribe to an internal topic.";
    public static final boolean DEFAULT_EXCLUDE_INTERNAL_TOPICS = true;
    static final String LEAVE_GROUP_ON_CLOSE_CONFIG = "internal.leave.group.on.close";
    static final String THROW_ON_FETCH_STABLE_OFFSET_UNSUPPORTED = "internal.throw.on.fetch.stable.offset.unsupported";
    public static final String ISOLATION_LEVEL_CONFIG = "isolation.level";
    public static final String ISOLATION_LEVEL_DOC = "Controls how to read messages written transactionally. If set to <code>read_committed</code>, consumer.poll() will only return transactional messages which have been committed. If set to <code>read_uncommitted</code> (the default), consumer.poll() will return all messages, even transactional messages which have been aborted. Non-transactional messages will be returned unconditionally in either mode. <p>Messages will always be returned in offset order. Hence, in  <code>read_committed</code> mode, consumer.poll() will only return messages up to the last stable offset (LSO), which is the one less than the offset of the first open transaction. In particular any messages appearing after messages belonging to ongoing transactions will be withheld until the relevant transaction has been completed. As a result, <code>read_committed</code> consumers will not be able to read up to the high watermark when there are in flight transactions.</p><p> Further, when in <code>read_committed</code> the seekToEnd method will return the LSO</p>";
    public static final String DEFAULT_ISOLATION_LEVEL;
    public static final String ALLOW_AUTO_CREATE_TOPICS_CONFIG = "allow.auto.create.topics";
    private static final String ALLOW_AUTO_CREATE_TOPICS_DOC = "Allow automatic topic creation on the broker when subscribing to or assigning a topic. A topic being subscribed to will be automatically created only if the broker allows for it using `auto.create.topics.enable` broker configuration. This configuration must be set to `false` when using brokers older than 0.11.0";
    public static final boolean DEFAULT_ALLOW_AUTO_CREATE_TOPICS = true;
    public static final String SECURITY_PROVIDERS_CONFIG = "security.providers";
    private static final String SECURITY_PROVIDERS_DOC = "A list of configurable creator classes each returning a provider implementing security algorithms. These classes should implement the <code>org.apache.kafka.common.security.auth.SecurityProviderCreator</code> interface.";
}

errorHandler

指定错误处理器,用于处理监听器方法抛出的异常。定义一个错误处理器,可以在发生异常时进行自定义处理。

实现KafkaListenerErrorHandler,然后做一些异常处理。如下:

@Component
public class KafkaDefaultListenerErrorHandler implements KafkaListenerErrorHandler {
    @Override
    public Object handleError(Message<?> message, ListenerExecutionFailedException exception) {
        return null;
    }

    @Override
    public Object handleError(Message<?> message, ListenerExecutionFailedException exception, Consumer<?, ?> consumer) {
    	//do someting
        return null;
    }
}

调用的时候填写beanName。例如errorHandler=“kafkaDefaultListenerErrorHandler”。

@KafkaListener(topics = "my-topic", errorHandler = "kafkaDefaultListenerErrorHandler")

containerFactory

指定用于创建监听器容器的工厂类。可以用于配置监听器容器的属性。通过设置 containerFactory,可以更灵活地配置监听器容器的一些属性,例如消息转换器、错误处理器等。

containerFactory中的属性会被@KafkaListener注解里面的concurrency属性或者properties属性中的配置覆盖。

/**
 * 监听器工厂 批量消费
 * @return
 */
@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>> myContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
            new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(kafkaConsumerFactory());
    //设置为批量消费,每个批次数量在Kafka配置参数中设置ConsumerConfig.MAX_POLL_RECORDS_CONFIG
    factory.setBatchListener(true);
    return factory;
}

调用的时候填写beanName。例如containerFactory = “myContainerFactory”。

@KafkaListener(topics = "my-topic", containerFactory = "myContainerFactory")

autoStartup

指定是否在启动时自动启动监听器容器。默认是 true。如果设置为false,则需要手动调用容器的start() 方法来启动监听器。

 @KafkaListener(topics = "my-topic", autoStartup = "false")

clientIdPrefix

指定 Kafka 消费者的客户端 ID 前缀。可以通过设置clientIdPrefix来自定义消费者的客户端 ID。

 @KafkaListener(topics = "my-topic", clientIdPrefix = "my-client")

containerGroup

指定监听器容器所属的组。如果有多个应用使用相同的消费者组,可以通过设置 containerGroup来区分它们。

 @KafkaListener(topics = "my-topic", containerGroup = "my-group")

这些参数可以根据实际需求进行组合和配置,以满足特定场景的要求。例如,通过调整 concurrency 可以控制监听器的并发性,通过设置 autoStartup 可以控制监听器容器是否在应用启动时自动启动。其他参数也可以根据需要进行调整。

【Kafka】SpringBoot 整合 Kafka 以及 @KafkaListener 注解的使用 一、前提已经安装好 kafka 我是在 windows 中安装的 Kafka,用于在本地测试用的 Windows 安装 kafka 二、新建 SpringBoot 项目 1、添加项目依赖 <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId& 阅读详情

相关推荐

SpringKafka动态指定@KafkaListener的topics和groupId

1.@KafkaListener @KafkaListener是kafka的消费者,topics是其主题名,groupId是组名; 属性值一般只支持常量,再集群的情况下,topics、groupId如果不是动态的,那集群环境中只有一台能消费同主题上的任务; 2.动态指定topics、groupId两个属性 @KafkaListener中有一个beanRef属性,专门获取spring容器中的bean; beanRef:此注释中的SpEL表达式中使用的伪bean名称,用于引用定义此侦听器的当前.

u014259503的博客 1万+

【kafka】@KafkaListener 注解解读

简介 Kafka 目前主要作为一个分布式的发布订阅式的消息系统使用,也是目前最流行的消息队列系统之一。因此,也越来越多的框架对 kafka 做了集成,比如本文将要说到的 spring-kafka。 Kafka 既然作为一个消息发布订阅系统,就包括消息生成者和消息消费者。本文主要讲述的 spring-kafka 框架的 kafkaListener 注解的深入解读和使用案例。 解读 源码解读 @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.

占星安啦的博客 2万+

@KafkaListener原理和动态监听kafka topic

首先分析了@KafkaListener的原理,并从其原理入手,通过读取配置,实例化KafkaMessageListenerContainer并调用其start()方法,实现动态kafka topic的监听

qq_34826261的博客 1万+

@KafkaListener详解与使用

目录 1 id 监听器的id 2 监听topic 3 errorHandler 异常处理 4 containerFactory 监听器工厂 5 clientIdPrefix 客户端前缀 6 concurrency并发数 从2.2.4版开始,您可以直接在注释上指定Kafka使用者属性,这些属性将覆盖在使用者工厂中配置的具有相同名称的所有属性。 可以使用#{…​}或属性占位符(${…​})在SpEL上配置注释上的大多数属性。 比如: @KafkaListe...

码灵的博客 3万+

【架构师面试-缓存与搜索-1】-缓存与缓存置换策略源码实现

1:什么是缓存 缓存:加速数据访问的存储,降低延迟(latency),提升吞吐量(Throughput)的利器。 1:缓存演进历史 1. 查库 2. ConcurrentHashMap 3. LRU 4. Guava Cache 5. 分布式缓存(redis,MemCache) 6. 多级缓存 2:在什么地方加缓存 缓存对于每个开发者来说是相当熟悉了,为了提高程序的性能我们会去加缓存,但是在什么地方加缓存,如何加缓存呢? 举个栗子:假设一个网站,需要提高性能,缓存可以放在浏览器,可以放

chongfa2008的博客 6438

Agent + 监控平台:自动诊断告警根因

根因分析、智能监控、AI Agent、告警风暴、异常检测、可观测性、故障诊断在现代分布式系统中,快速定位和解决问题是维持系统稳定性的关键。传统的监控系统虽然能够生成大量告警,但往往缺乏对告警根因的自动诊断能力,导致运维团队在告警风暴中难以快速定位问题。本文深入探讨了将AI Agent技术与监控平台结合,实现告警根因自动诊断的技术架构、理论基础和实现方法。我们将从第一性原理出发,分析根因诊断问题的本质,介绍基于Agent的智能监控系统设计,并通过实际案例展示其应用价值。文章同时涵盖了从理论到实践的全链路,包括

AIGC应用创新大全的博客 304

【spring-kafka】@KafkaListener详解与使用

说明 从2.2.4版开始,您可以直接在注释上指定Kafka使用者属性,这些属性将覆盖在使用者工厂中配置的具有相同名称的所有属性。您不能通过这种方式指定group.id和client.id属性。他们将被忽略; 可以使用#{…​}或属性占位符(${…​})在SpEL上配置注释上的大多数属性。 比如: @KafkaListener(id = "consumer-id",topics = "SHI_TOPIC1",concurrency = "${listen.concurrency:3}",

石臻说AI(szzdzhp001) 【原名 石臻臻的杂货铺】 17万+

爬取百度图片

最开始,我们想要爬取图片,首先需要打开百度图库,然后在搜索栏中输入自己想要的图片(比如说壁纸)。接着右键检查,点击网络:起初可能没有名称信息,刷新界面就可以了。打开信息,查看标头内容可以看到请求URL为:复制这串URL,然后在浏览器中打开这个就是我们搜索的壁纸图片的网页内容。怎么找到图片的URL呢?在上述内容中,找到data,可以发现里面每隔一个aiEditData,下面代码的形式是一样的,就相当于一张图片。

weixin_54143563的博客 1939

Kafka @KafkaListener 注解的详解及使用

消费者的id,默认自动生成唯一 id,没有配置 GroupId 的时候,默认 id 为 GroupId,是每个 Listener 实例的重要标识。消费组id,每个消费者都有自己的消费组,一个组中可以有多个消费者,一个 Topic 的一个分区只能被同一个消费组中的某一个消费者来消费。并发消费的线程数,根据 Topic 的分区来合理设置并发线程数,因为一个分区只能被一个消费组中的一个消费者消费。指定监听容器所属的分组,如果有多个使用相同的消费者组,可以设置 containerGroup 来区分。

weixin_42118323的博客 2119

蓝桥杯算法:打印图形——六芒星

【输入格式】 输入一行包含一个整数 n。 【输出格式】 输出一个六芒星,表示满足题意的图形。 【样例输入】 3 4 【样例输出】 【评测用例规模与约定】 对于所有评测用例,1 ≤ n ≤ 20。 总结: 第一次做图形题,做了蛮久,图形题有很多的方式去完成,它考验的是你能不能找到更简单的那一种方式. 我初看到这个图形,第一种想法是把这个六芒星当做六个小三角形来做,然后以某种规则排列一下,就能做出来,但是尝试了一下感觉太麻烦了。 然后我的第二种想法是,这个图形是对称图形,怎么能写出一半吗? 这样另一半想办

KeepCodeing 3835

Welch 方法详解:一种经典而实用的功率谱密度估计方法

在信号处理领域,谱分析是用于分析信号频率内容的强大工具。Welch方法是现代谱分析中一种广泛使用的功率谱密度估计技术,由Peter D. Welch在1967年提出。它通过对信号进行分段、加窗和平均化处理,提供了一种平滑且稳定的频谱估计方法。Welch方法通过将信号分成多个重叠的段,每段应用窗函数,然后计算每段的周期图,最后对所有周期图进行平均化,得到平滑的功率谱密度估计。welch_psd函数接收信号x、采样频率fs、每段的样本数N、重叠样本数overlap和窗函数类型window。

DuHz的博客 7046

kafka系列(09):SpringBoot 中使用@KafkaListener详解与使用

说明 从2.2.4版开始,您可以直接在注释上指定Kafka使用者属性,这些属性将覆盖在使用者工厂中配置的具有相同名称的所有属性。您不能通过这种方式指定group.id和client.id属性。他们将被忽略; 可以使用#{…​}或属性占位符(${…​})在SpEL上配置注释上的大多数属性。 比如: @KafkaListener(id = "consumer-id",topics = "SHI_TOPIC1",concurrency = "${listen.concurrency:3}", .

xsxy0506的博客 1万+

SAP 供应商寄售(VMI)完整实现方案

摘要:本文详细讲解了SAP系统中供应商寄售(Consignment)和VMI(供应商管理库存)的实现方法。核心逻辑是物料所有权属于供应商,仅在领用时才触发采购。文章包含配置步骤(物料主数据、供应商设置、定价协议、会计科目等)、端到端操作流程(收货、库存查询、领用、结算、付款)、关键差异比较(与普通采购的区别)、核心事务码和数据表。重点说明了寄售流程无需采购订单,通过信息记录维护价格,领用时才产生应付账款的特点,并提供了常见问题解决方案和VMI进阶优化建议。

金牌架构师 1045

Spring Kafka 之 @KafkaListener 注解详解

Spring Kafka 之 @KafkaListener 注解详解

HY 6894

2、TrustZone(内含链接)——长期学习内容

ARM系列学习路径整理,希望对大家有用。

HoneyIC的博客 232

华为OD机考2025C卷 - 高矮个子排队(Java & Python& JS & C++ & C)

华为OD机考2025C卷 - 高矮个子排队。提供在线OJ刷题。Java、C++、Python、C语言、JavaScript题解,并提供完整思路讲解。

算法大师! 1681

springboot+kafka中@KafkaListener如何动态指定多个topic

springboot+kafka中@KafkaListener如何动态指定多个topic 本项目为springboot+kafak的整合项目,故其用了springboot中对kafak的独特消费注解@KafkaListener 首先,application.properties中配置用逗号隔开的多个topic。 方法一: 运行程序,console打印的效果如下: 因为只开了一条消费者线程,所...

the Blog of Forward 4万+

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Kafka的@KafkaListener注解参数详解

例子: @KafkaListener(topics = “my-topic”,properties={“enable.auto.commit=false”,“auto.offset.reset=earliest”})在同一应用中,如果有多个监听器,可以使用不同的id来标识不同的监听器容器。描述:指定其他的消费者配置属性,以键值对的形式提供。请确保设置的属性是合法的Kafka 消费者属性,并符合你的应用需求。描述: 指定并发消费者的数量,即监听器容器的线程数。描述: 指定 Kafka 消费者组的 ID。

Everybody up 3477

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

springboot使用@KafkaListener监听多个kafka配置_@kafkalistener可以有多个吗

(img-vossTxXg-1713154855759)]拓展其他消费者配置只需配置指定的属性和bean即可。kafka监听容器工厂配置。// 是否开启批量消费。// 消费的超时时间。

2401_84166836的博客 1323

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

spring-Kafka之@KafkaListener深入解读

本文主要通过深入了解源码,梳理从spring启动到真正监听kafka消息的这套流程

持之以恒 1万+

spring中的@KafkaListener 注解详解

@KafkaListener 是 Spring Kafka 的核心注解,用于标记 Kafka 消息消费者方法。它支持多种配置属性,包括监听主题(topics/topicPattern)、消费者组(groupId)、并发度(concurrency)等。消息处理方法可接收简单字符串、ConsumerRecord 对象或批量消息列表,并支持手动确认(Acknowledgment)。通过配置 ConcurrentKafkaListenerContainerFactory 可自定义消费者工厂,设置并发线程数、轮询超时

技术人集结地 2475

Kafka中@KafkaListener如何动态指定多个topic

点击关注公众号,实用技术文章及时了解来源:blog.youkuaiyun.com/qq_35457078/article/details/88838511说明:本项目为springboot+kafak...

Java知音 5781

Kafka-03 @KafkaListener学习

SpringBoot 和 Kafka 搭配使用的场景,引入 spring-kafka 即可;

qq_45149567的博客 1717

Kafka中@KafkaListener不自动监听消费数据了

Kafka中不自动消费的问题解决方案 查看源码 如果项目中有多个不同的topic需要消费,那么一定要注意@KafkaListener中id的配置,源码中如下 /** * The unique identifier of the container managing for this endpoint.(管理此端点的容器的唯一标识符 ) * <p>If none is specified an auto-generated one is provided. * @return the

weixin_43847058的博客 9864

Spring Kafka @KafkaListener 源码剖析

Spring Kafka 中 如何通过 @KafkaListener 实现

chinagui89的博客 569
上一篇: Kafka系列之SpringBoot集成Kafka
下一篇: kafka系列之offset超强总结及消费后不提交offset情况的分析总结
狂奔的小棕棕
博客等级 码龄12年 359粉丝 91原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值