Kafka生产者

(三)Kafka 生产者 假设你是 B2B 供应商,你有一个大客户,它是手持设备 Banana 的制造商。你的日常交易中有 10% 以上的交易与这个客户有关。如果使用默认的哈希分区算法,那么与 Banana 相关的记录就会和其他客户的记录一起被分配给相同的分区,导致这个分区比其他分区大很多。服务器可能会出现存储空间不足、请求处理缓慢等问题。因此,需要给 Banana 分配单独的分区,然后使用哈希分区算法将其他记录分配给其他分区。 阅读详情

这篇文章将主要介绍 Kafka 中的生产者 Producer。 生产者属于Kafka客户端,负责将消息发布到 Kafka 集群,以供消费者进行消费。本篇文章在 Kafka 生产者源代码的基础上,对生产者的创建,生产者内部的一些重要组件和生产者发送消息的大体流程进行介绍,并且对生产者的源代码增加了注释来方便理解。

1. 创建生产者

首先通过Kafka examlpe包中的一个示例来创建生产者。在这个示例中,Producer 封装了 KafkaProducer,并继承 Thread,在线程的 run() 方法中通过while循环来不断发送消息。

Producer producerThread = new Producer("producer", KafkaProperties.BOOTSTRAP_SERVERS, TOPIC_NAME, isAsync, null, false, numRecords, -1, latch);
producerThread.start();

以下为示例中 Producer 的具体实现:

public class Producer extends Thread {
    private final String bootstrapServers;
    private final String topic;
    private final boolean isAsync;
    private final String transactionalId;
    private final boolean enableIdempotency;
    private final int numRecords;
    private final int transactionTimeoutMs;
    private final CountDownLatch latch;
    private volatile boolean closed;

    public Producer(String threadName,
                    String bootstrapServers,
                    String topic,
                    boolean isAsync,
                    String transactionalId,
                    boolean enableIdempotency,
                    int numRecords,
                    int transactionTimeoutMs,
                    CountDownLatch latch) {
        super(threadName);
        this.bootstrapServers = bootstrapServers;
        this.topic = topic;
        this.isAsync = isAsync;
        this.transactionalId = transactionalId;
        this.enableIdempotency = enableIdempotency;
        this.numRecords = numRecords;
        this.transactionTimeoutMs = transactionTimeoutMs;
        this.latch = latch;
    }

    @Override
    public void run() {
        int key = 0;
        int sentRecords = 0;
        
        // 调用 createKafkaProducer() 创建生产者
        try (KafkaProducer<Integer, String> producer = createKafkaProducer()) {
            // while循环发送消息
            while (!closed && sentRecords < numRecords) {
                if (isAsync) {
                    // 异步发送消息
                    asyncSend(producer, key, "test" + key);
                } else {
                    // 同步发送消息
                    syncSend(producer, key, "test" + key);
                }
                key++;
                sentRecords++;
            }
        } catch (Throwable e) {
            Utils.printErr("Unhandled exception");
            e.printStackTrace();
        }
        Utils.printOut("Sent %d records", sentRecords);
        shutdown();
    }

    // 创建 KafkaProducer 
    public KafkaProducer<Integer, String> createKafkaProducer() {
        Properties props = new Properties();
        // 给 producer 配置 bootstrap server 地址来拉取元数据
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        // 客户端 Id
        props.put(ProducerConfig.CLIENT_ID_CONFIG, "client-" + UUID.randomUUID());
        // Kafka消息使用二进制传输,设定对应的序列化器
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        // kafka 事务相关设定
        if (transactionTimeoutMs > 0) {
            // max time before the transaction coordinator proactively aborts the ongoing transaction
            props.put(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, transactionTimeoutMs);
        }
        if (transactionalId != null) {
            // the transactional id must be static and unique
            // it is used to identify the same producer instance across process restarts
            props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, transactionalId);
        }

        // 是否保证分区内幂等性
        props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, enableIdempotency);

        return new KafkaProducer<>(props);
    }
}

2. KafkaProducer的初始化

这一章节主要介绍生产者 KafkaProducer 的初始化,其中包含一些生产者中的重要组件的初始化,主要包括:

  1. 分区器 Partitioner
  2. 序列化器 Serializer
  3. 拦截器 ProducerInterceptor
  4. RecordAccumulator
  5. 元数据 Metadata
  6. Sender
KafkaProducer(ProducerConfig config,
                Serializer<K> keySerializer,
                Serializer<V> valueSerializer,
                ProducerMetadata metadata,
                KafkaClient kafkaClient,
                ProducerInterceptors<K, V> interceptors,
                Time time) {
    try {
        this.producerConfig = config;
        this.time = time;

        String transactionalId = config.getString(ProducerConfig.TRANSACTIONAL_ID_CONFIG);

        this.clientId = config.getString(ProducerConfig.CLIENT_ID_CONFIG);

        LogContext logContext;
        if (transactionalId == null)
            logContext = new LogContext(String.format("[Producer clientId=%s] ", clientId));
        else
            logContext = new LogContext(String.format("[Producer clientId=%s, transactionalId=%s] ", clientId, transactionalId));
        log = logContext.logger(KafkaProducer.class);
        log.trace("Starting the Kafka producer");

        // metrics
        Map<String, String> metricTags = Collections.singletonMap("client-id", clientId);
        MetricConfig metricConfig = new MetricConfig().samples(config.getInt(ProducerConfig.METRICS_NUM_SAMPLES_CONFIG))
                .timeWindow(config.getLong(ProducerConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG), TimeUnit.MILLISECONDS)
                .recordLevel(Sensor.RecordingLevel.forName(config.getString(ProducerConfig.METRICS_RECORDING_LEVEL_CONFIG)))
                .tags(metricTags);
        List<MetricsReporter> reporters = CommonClientConfigs.metricsReporters(clientId, config);
        this.clientTelemetryReporter = CommonClientConfigs.telemetryReporter(clientId, config);
        this.clientTelemetryReporter.ifPresent(reporters::add);
        MetricsContext metricsContext = new KafkaMetricsContext(JMX_PREFIX,
                config.originalsWithPrefix(CommonClientConfigs.METRICS_CONTEXT_PREFIX));
        this.metrics = new Metrics(metricConfig, reporters, time, metricsContext);
        this.producerMetrics = new KafkaProducerMetrics(metrics);

        // 1. 分区器 Partitioner
        this.partitioner = config.getConfiguredInstance(
                ProducerConfig.PARTITIONER_CLASS_CONFIG,
                Partitioner.class,
                Collections.singletonMap(ProducerConfig.CLIENT_ID_CONFIG, clientId));
        warnIfPartitionerDeprecated();
        this.partitionerIgnoreKeys = config.getBoolean(ProducerConfig.PARTITIONER_IGNORE_KEYS_CONFIG);
        // 重试间隔时间
        long retryBackoffMs = config.getLong(ProducerConfig.RETRY_BACKOFF_MS_CONFIG);
        long retryBackoffMaxMs = config.getLong(ProducerConfig.RETRY_BACKOFF_MAX_MS_CONFIG);

        // 2. 序列化器 Serializer
        if (keySerializer == null) {
            this.keySerializer = config.getConfiguredInstance(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                                                                                        Serializer.class);
            this.keySerializer.configure(config.originals(Collections.singletonMap(ProducerConfig.CLIENT_ID_CONFIG, clientId)), true);
        } else {
            config.ignore(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG);
            this.keySerializer = keySerializer;
        }
        if (valueSerializer == null) {
            this.valueSerializer = config.getConfiguredInstance(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                                                                                        Serializer.class);
            this.valueSerializer.configure(config.originals(Collections.singletonMap(ProducerConfig.CLIENT_ID_CONFIG, clientId)), false);
        } else {
            config.ignore(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG);
            this.valueSerializer = valueSerializer;
        }

        // 3. 拦截器 ProducerInterceptor
        List<ProducerInterceptor<K, V>> interceptorList = ClientUtils.configuredInterceptors(config,
                ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,
                ProducerInterceptor.class);
        if (interceptors != null)
            this.interceptors = interceptors;
        else
            this.interceptors = new ProducerInterceptors<>(interceptorList);
        ClusterResourceListeners clusterResourceListeners = ClientUtils.configureClusterResourceListeners(
                interceptorList,
                reporters,
                Arrays.asList(this.keySerializer, this.valueSerializer));
        // 一条消息的最大 size
        this.maxRequestSize = config.getInt(ProducerConfig.MAX_REQUEST_SIZE_CONFIG);
        // RecordAccumulator缓存大小
        this.totalMemorySize = config.getLong(ProducerConfig.BUFFER_MEMORY_CONFIG);
        // 压缩算法
        this.compression = configureCompression(config);

        this.maxBlockTimeMs = config.getLong(ProducerConfig.MAX_BLOCK_MS_CONFIG);
        int deliveryTimeoutMs = configureDeliveryTimeout(config, log);

        this.apiVersions = new ApiVersions();
        this.transactionManager = configureTransactionState(config, logContext);
        // There is no need to do work required for adaptive partitioning, if we use a custom partitioner.
        boolean enableAdaptivePartitioning = partitioner == null &&
            config.getBoolean(ProducerConfig.PARTITIONER_ADPATIVE_PARTITIONING_ENABLE_CONFIG);
        RecordAccumulator.PartitionerConfig partitionerConfig = new RecordAccumulator.PartitionerConfig(
            enableAdaptivePartitioning,
            config.getLong(ProducerConfig.PARTITIONER_AVAILABILITY_TIMEOUT_MS_CONFIG)
        );

        // 4. RecordAccumulator,用于缓存消息,并对消息进行分组
        int batchSize = Math.max(1, config.getInt(ProducerConfig.BATCH_SIZE_CONFIG));
        this.accumulator = new RecordAccumulator(logContext,
                batchSize,
                compression,
                lingerMs(config),
                retryBackoffMs,
                retryBackoffMaxMs,
                deliveryTimeoutMs,
                partitionerConfig,
                metrics,
                PRODUCER_METRIC_GROUP_NAME,
                time,
                apiVersions,
                transactionManager,
                new BufferPool(this.totalMemorySize, batchSize, metrics, time, PRODUCER_METRIC_GROUP_NAME));

        // 5. 元数据 Metadata
        List<InetSocketAddress> addresses = ClientUtils.parseAndValidateAddresses(config);
        if (metadata != null) {
            this.metadata = metadata;
        } else {
            this.metadata = new ProducerMetadata(retryBackoffMs,
                    retryBackoffMaxMs,
                    config.getLong(ProducerConfig.METADATA_MAX_AGE_CONFIG),
                    config.getLong(ProducerConfig.METADATA_MAX_IDLE_CONFIG),
                    logContext,
                    clusterResourceListeners,
                    Time.SYSTEM);
            
            // 初始化时设定了 bootstrap server 的 address
            this.metadata.bootstrap(addresses);
        }
        this.errors = this.metrics.sensor("errors");

        // 6. Sender用于发送消息,内部包含 NetworkClient 用于网络传输数据
        this.sender = newSender(logContext, kafkaClient, this.metadata);
        String ioThreadName = NETWORK_THREAD_PREFIX + " | " + clientId;
        // KafkaThread 内部将 sender 设定为后台线程并启动
        this.ioThread = new KafkaThread(ioThreadName, this.sender, true);
        this.ioThread.start();
        config.logUnused();
        AppInfoParser.registerAppInfo(JMX_PREFIX, clientId, metrics, time.milliseconds());
        log.debug("Kafka producer started");
    } catch (Throwable t) {
        // call close methods if internal objects are already constructed this is to prevent resource leak. see KAFKA-2121
        close(Duration.ofMillis(0), true);
        // now propagate the exception
        throw new KafkaException("Failed to construct kafka producer", t);
    }
}

3. send 发送消息

Kafka 生产者支持 asyncSend() 异步发送消息和 syncSend() 同步发送消息,其中异步发送带有一个回调函数callback。同步发送消息会阻塞当前线程等待消息返回响应,而异步发送消息不会阻塞当前线程,性能较好。

private void asyncSend(KafkaProducer<Integer, String> producer, int key, String value) {
    // send the record asynchronously, setting a callback to be notified of the result
    // note that, even if you set a small batch.size with linger.ms=0, the send operation
    // will still be blocked when buffer.memory is full or metadata are not available
    producer.send(new ProducerRecord<>(topic, key, value), new ProducerCallback(key, value));
}

private RecordMetadata syncSend(KafkaProducer<Integer, String> producer, int key, String value)
    throws ExecutionException, InterruptedException {
    try {
        // send the record and then call get, which blocks waiting for the ack from the broker
        RecordMetadata metadata = producer.send(new ProducerRecord<>(topic, key, value)).get();
        Utils.maybePrintRecord(numRecords, key, value, metadata);
        return metadata;
    } catch (AuthorizationException | UnsupportedVersionException | ProducerFencedException
                | FencedInstanceIdException | OutOfOrderSequenceException | SerializationException e) {
        Utils.printErr(e.getMessage());
        // we can't recover from these exceptions
        shutdown();
    } catch (KafkaException e) {
        Utils.printErr(e.getMessage());
    }
    return null;
}

4. Kafka 生产者发送消息流程

在这里插入图片描述

Kafka 中 Producer 生产者发送消息主要基于 send() 方法,而 send() 方法底层调用了 doSend() 方法,其流程主要包括以下几步:
(1)注册拦截器 ProducerInterceptors,然后通过 waitOnMetadata() 获取元数据
(2)Serializer 对消息的键值进行序列化
(3)Prititioioner 分区器计算消息分区
(4)将消息放入 RecordAccumulator 进行缓存并根据消息分区进行分组
(5)sender.wakeup() 唤醒 Sender 线程,由 Sender 线程发送消息
此时 doSend() 已经完成消息的发送。

接下来由 Sender 线程来实际进行网络数据发送,主要包括以下几步:
(6)Sender 线程将一个 batch 的数据封装成 ClientRequest
(7)将消息请求放入 InFlightRequests 等待发送
(8)Sender 内部的 NetworkClient 调用 Selector 对消息进行发送
(9)消息发送至 Kafka 集群
(10)Kafka 集群返回响应结果
(11)NetworkClient 收到响应,将请求从 InFlightRequests 移除,代表已完成消息发送
(12)将 ProducerBatch 从 RecordAccumulator 中移除,代表这个 batch 的消息已完成发送
(13)遍历调用这个 batch 所有消息的回调函数 callback

以下为 doSend() 方法的源代码:

/**
 * Implementation of asynchronously send a record to a topic.
 */
private Future<RecordMetadata> doSend(ProducerRecord<K, V> record, Callback callback) {
    // AppendCallbacks 的作用:
    // 1. 在 send 完成后调用拦截器 interceptor 和 callback 回调函数
    // 2. 在调用 RecordAccumulator.append() 后记录消息的分区信息
    AppendCallbacks appendCallbacks = new AppendCallbacks(callback, this.interceptors, record);

    try {
        throwIfProducerClosed();
        // first make sure the metadata for the topic is available
        long nowMs = time.milliseconds();
        ClusterAndWaitTime clusterAndWaitTime;
        try {
            // 同步获取元数据
            clusterAndWaitTime = waitOnMetadata(record.topic(), record.partition(), nowMs, maxBlockTimeMs);
        } catch (KafkaException e) {
            if (metadata.isClosed())
                throw new KafkaException("Producer closed while send in progress", e);
            throw e;
        }
        nowMs += clusterAndWaitTime.waitedOnMetadataMs;
        long remainingWaitMs = Math.max(0, maxBlockTimeMs - clusterAndWaitTime.waitedOnMetadataMs);

        // cluster 集群元数据
        Cluster cluster = clusterAndWaitTime.cluster;

        // 序列化 key 和 value
        byte[] serializedKey;
        try {
            serializedKey = keySerializer.serialize(record.topic(), record.headers(), record.key());
        } catch (ClassCastException cce) {
            throw new SerializationException("Can't convert key of class " + record.key().getClass().getName() +
                    " to class " + producerConfig.getClass(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG).getName() +
                    " specified in key.serializer", cce);
        }
        byte[] serializedValue;
        try {
            serializedValue = valueSerializer.serialize(record.topic(), record.headers(), record.value());
        } catch (ClassCastException cce) {
            throw new SerializationException("Can't convert value of class " + record.value().getClass().getName() +
                    " to class " + producerConfig.getClass(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG).getName() +
                    " specified in value.serializer", cce);
        }

        // 尝试计算消息的分区
        // 这里返回结果可能为 RecordMetadata.UNKNOWN_PARTITION,这时会由 RecordAccumulator 根据集群的负载情况等信息来决定实际的分区
        int partition = partition(record, serializedKey, serializedValue, cluster);

        setReadOnly(record.headers());
        Header[] headers = record.headers().toArray();

        int serializedSize = AbstractRecords.estimateSizeInBytesUpperBound(apiVersions.maxUsableProduceMagic(),
                compression.type(), serializedKey, serializedValue, headers);
        ensureValidRecordSize(serializedSize);
        long timestamp = record.timestamp() == null ? nowMs : record.timestamp();

        // A custom partitioner may take advantage on the onNewBatch callback.
        boolean abortOnNewBatch = partitioner != null;

        // 将消息加入 RecordAccumulator,如果 partition 为 RecordMetadata.UNKNOWN_PARTITION
        // 将会由 RecordAccumulator 根据集群的负载情况等信息来决定实际的分区
        // 这里入参传入了 appendCallbacks,消息实际的分区将写入 appendCallbacks.topicPartition
        RecordAccumulator.RecordAppendResult result = accumulator.append(record.topic(), partition, timestamp, serializedKey,
                serializedValue, headers, appendCallbacks, remainingWaitMs, abortOnNewBatch, nowMs, cluster);
        assert appendCallbacks.getPartition() != RecordMetadata.UNKNOWN_PARTITION;

        if (result.abortForNewBatch) {
            int prevPartition = partition;
            onNewBatch(record.topic(), cluster, prevPartition);
            partition = partition(record, serializedKey, serializedValue, cluster);
            if (log.isTraceEnabled()) {
                log.trace("Retrying append due to new batch creation for topic {} partition {}. The old partition was {}", record.topic(), partition, prevPartition);
            }
            result = accumulator.append(record.topic(), partition, timestamp, serializedKey,
                serializedValue, headers, appendCallbacks, remainingWaitMs, false, nowMs, cluster);
        }

        if (transactionManager != null) {
            transactionManager.maybeAddPartition(appendCallbacks.topicPartition());
        }

        // 唤醒 sender 发送消息
        if (result.batchIsFull || result.newBatchCreated) {
            log.trace("Waking up the sender since topic {} partition {} is either full or getting a new batch", record.topic(), appendCallbacks.getPartition());
            this.sender.wakeup();
        }
        return result.future;
        // handling exceptions and record the errors;
        // for API exceptions return them in the future,
        // for other exceptions throw directly
    } catch (ApiException e) {
        log.debug("Exception occurred during message send:", e);
        if (callback != null) {
            TopicPartition tp = appendCallbacks.topicPartition();
            RecordMetadata nullMetadata = new RecordMetadata(tp, -1, -1, RecordBatch.NO_TIMESTAMP, -1, -1);
            callback.onCompletion(nullMetadata, e);
        }
        this.errors.record();
        this.interceptors.onSendError(record, appendCallbacks.topicPartition(), e);
        if (transactionManager != null) {
            transactionManager.maybeTransitionToErrorState(e);
        }
        return new FutureFailure(e);
    } catch (InterruptedException e) {
        this.errors.record();
        this.interceptors.onSendError(record, appendCallbacks.topicPartition(), e);
        throw new InterruptException(e);
    } catch (KafkaException e) {
        this.errors.record();
        this.interceptors.onSendError(record, appendCallbacks.topicPartition(), e);
        throw e;
    } catch (Exception e) {
        // we notify interceptor about all exceptions, since onSend is called before anything else in this method
        this.interceptors.onSendError(record, appendCallbacks.topicPartition(), e);
        throw e;
    } catch (KafkaException e) {
        this.errors.record();
        this.interceptors.onSendError(record, appendCallbacks.topicPartition(), e);
        throw e;
    } catch (Exception e) {
        // we notify interceptor about all exceptions, since onSend is called before anything else in this method
        this.interceptors.onSendError(record, appendCallbacks.topicPartition(), e);
        throw e;
    }
}
查询Kafka生产者是否连接到Kafka服务 java领域优质创作者🌐。 阅读详情

相关推荐

OI 生涯回忆录 《Pilgrimage》

前言 于 NOI2020 后写下本文。 本文简单提及了在写作时尚能回忆起来的,在我的 OI 生涯中对我的影响重大的人、事、比赛等。 写作本文,旨在在回忆允许的范围内,对 OI 生涯进行一定程度上的梳理,总结。 开端 入门 我最早接触计算机程序设计,是在小学。 那时候,我的数学成绩不错,就被老师推荐去学习编程。 就这样,我在局前街小学的何静老师的指导下,走上了编程的道路。 小学时的编程,与其说是 “竞赛” ,不如说是 “兴趣班” 。 当时,包括我在内,很多小孩子天性是浮躁的。支撑我对着无聊的代码学下去的,并不

cz_xuyixuan的博客 1万+

kafka相关命令&&生产者基础

创建topic:bin/kafka-topics.sh -bootstrap-server 192.168.96.129:9092,192.168.96.130:9092,192.168.96.131:9092 --topic first --create --partitions 1 --replication-factor 3。2 不能通过命令的方式修改副本数(其他方式可以-->)Leader:3 (3节点为leader)1 分区数为啥只能增加?

qq_34914039的博客 665

本地部署静态网站托管平台 Netlify 并实现外部访问(Windows 版本)

Netlify 是一款基于云计算的网站部署和托管平台,专为开发者提供便捷的静态网站和 Jamstack 应用部署服务。它的能力在于将网站构建、部署、托管以及持续集成等流程高度集成,简化了开发和运维的复杂程度。用户无需关心服务器的配置、维护等工作。本文将详细介绍如何在本地安装 Netlify 以及结合路由侠内网穿透实现外网访问 Netlify。

lyxnwct的博客 532

Kafka生产者详解

Kafka生产者详解

日常分享数据分析开发、编程语言内容 2073

Coppelia Sim (v-REP)仿真 机器人3D相机手眼标定与实时视觉追踪 (一)

先把这连个都添加到场景中,然后把kinect的depth相机拖到vision sensor中,把kinect的script也拖到vision sensor中,同时要注意修改深度相机的坐标,及修改script,删掉/rgb部分。由于需要导入到仿真场景中PDF文件不能直接导入,所以需要生成图下文件,使用windows自带的画图工具,生成以厘米为单位的图像格式,大小和标定板的设置大小一直。可以生成需要用的标定板的文件,设置标定板的大小,棋盘格的大小,等相关的参数,之后可以保存PDF文件。设置plane的大小。

hong3731的专栏 1758

RV1126开发板性能实测:网络、温度与功耗全解析

本文对RV1126开发板进行了全面的性能实测,重点分析了网络性能、温度表现与功耗特性。测试发现UDP带宽可达500Mbps,但TCP性能受限于协议栈;散热设计对持续性能至关重要,大板子在AI推理和视频推流中表现更稳定。为嵌入式开发者提供了真实的选型参考和优化建议。

d3e4f的博客 275

kafka基础入门(2):kafka生产者(producer)

本文介绍了kafka生产者的相关内容,包括其数据发送的原理、相关API的操作、数据可靠性以及一些生产经验

WHY的博客 1896

A*搜索算法在三维路径规划(避障)中的MATLAB实现与Python实现

A star algorithmA*搜索算法简介A*搜索算法的Python简化代码MATLAB实现启发函数回溯轨迹RRT算法对比A\*算法在三维路径规划中的一些不足 A*搜索算法简介 A*搜索算法是Greedy Best-First算法的改进,因为Greedy Best-First算法只考虑将预估距离(当前节点到目标点的预估距离)作为遴选开节点集的条件。即: priority=heuristic(goal,next)priority=heuristic(goal, next)priority=heurist

ZYunfei的博客 2万+

Kafka(四)- Kafka 生产者

Kafka(四)- Kafka 生产者

及时当勉励,岁月不待人 1158

怎样让你的论文看起来“像人写的”?只用三招直接去除AI味(附提示词)

当然如果你在实际使用中还有其他需求,比如降重润色、改写翻译等,也可以结合七哥的专业写作平台来辅助,这个高级学术平台已经内置了ChatGPT4o、ChatGPT4.1、Claude3.7、满血版DeepSeek-R1等AI大模型,帮你写文献综述、干课题申报、写论文等学术任务绝对每一点问题。比如我自己的一套学术写作平台,其中的“降重与润色”模块整合了多种GPTs应用,除了能帮助调整语言风格、避免雷同表达,还可以顺带降个重,对于提升学术文本的整体质量还是非常有用的。一、为什么用AI写出来的文章会有AI味?

智能AI让学术科研更容易 1731

ubuntu linux虚拟机安装部署openclaw详细教程(安装、问题处理)

本文详细介绍了在Ubuntu系统下安装OpenClaw AI助手的完整流程及常见问题解决方案。主要内容包括:1) 通过GIT、Node.js等基础环境配置;2) 使用官方脚本或源码编译两种方式安装OpenClaw;3) 配置向导中的关键选项说明;4) 针对systemctl服务启动失败等常见错误的处理方法。文章特别强调了权限管理、网络依赖和访问配置等易错环节,提供了修改service文件等具体解决方案,帮助开发者顺利完成部署并实现Web UI访问。教程实操性强,适合本地和云服务器环境部署参考。

少说,多做 2048

kafka生产者

生产者调用方法。ProducerRecord 是 Kafka 中的一个核心类,它代表了一组 Kafka 需要发送的 key/value 键值对,它由记录要发送到的主题名称(Topic Name),可选的分区号(Partition Number)以及可选的键值对构成。然后经过拦截器 -》 序列化器(kafak自己的序列化器。。经过分区器。在分区器决定向那个分区里面发送。消息追加到收集器。

永远别让世俗淹没生活的热情和浪漫 2134

点云焊缝提取

本文介绍了一个基于PCL库的点云处理流程,包含三个核心模块:MLS平滑处理通过多项式拟合修正点云位置;差异提取通过双向匹配定位源/目标点云的非重叠区域;统计过滤剔除离群噪声点。该流程采用"平滑-筛选-净化"的通用思路,将复杂算法封装为可配置接口,实现了工业级点云预处理。文章重点分析了各模块的原理、PCL接口调用及参数设计逻辑,同时指出参数调优、算法扩展等深入探索方向,展现了PCL在点云处理中的模块化优势与实用价值。

weixin_45196569的博客 262

Apache Kafka - 重识Kafka生产者

Kafka 生产者是 Apache Kafka 中的一个重要组件,它负责将数据发送到 Kafka 集群中。在实时数据处理和流式处理应用程序中,Kafka 生产者扮演着非常重要的角色。这里我们将介绍 Kafka 生产者的概念、工作原理以及如何使用 Kafka 生产者。Kafka 生产者是 Apache Kafka 中的一个重要组件,它负责将数据发送到 Kafka 集群中。Kafka 生产者的工作原理是连接 Kafka 集群、发送数据、处理错误和关闭连接。

小工匠 1万+

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Kafka03 - Kafka生产者

Kafka03 - Kafka生产者

qq_43350524的博客 1221

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

【kafka】生产者

如果生产者发送消息的速度超过发送到服务器的速度,则会导致生产者空间不足,这个时候KafkaProducer的send(​)方法调用要么被阻塞,要么抛出异常,这个取决于参数max.block.ms的配置,此参数的默认值为60000,即60秒。增大这个参数的值会增加消息的延迟,但是同时能提升一定的吞吐量。方法的返回值是一个Future类型的对象,那么完全可以用Java语言层面的技巧来丰富应用的实现,比如使用Future中的 get(long timeout,TimeUnit unit)方法实现可超时的阻塞。

thinking-fish的博客 1263

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

Kafka生产者:写消息到Kafka

本章我们将会讨论Kafka生产者是如何发送消息到Kafka的。Kafka项目有一个生产者客户端,我们可以通过这个客户端的API来发送消息。 概要 当我们发送消息之前,先问几个问题:每条消息都是很关键且不能容忍丢失么?偶尔重复消息可以么?我们关注的是消息延迟还是写入消息的吞吐量? 举个例子,有一个信用卡交易处理系统,当交易发生时会发送一条消息到Kafka,另一个服务来读取消息并根据规则引擎来检...

zhangMY12138的博客 1852

【kafka实战】04 Kafka生产者发送消息过程源码剖析

kafka发送消息源码剖析

程序员笔记 3534

第3章 Kafka生产者【Kafka】

第3章 Kafka生产者【Kafka】

小心星的博客 1443

Kafka权威指南,Kafka生产者

Kafka生产者 Kafka 发送消息的主要步骤: ProducerRecord 对象包括目标主题和发送的内容,还可以制定键或分区。如果消息成功写入 Kafka,就返回一个 RecordMetaData 对象,它包含了主题和分区信息,以及记录在分区里的偏移量。如果写入失败,则会返回一个错误。 Propertites prop = new Propertites(); p...

qq_39662660的博客 397

kafka生产者API

java整合kafka生产者操作

weixin_46401545的博客 796
上一篇: Kafka简介
下一篇: Kafka元数据
SolitudeCoding
博客等级 码龄9年 110粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值