Tous les produits
Search
Centre de documentation

ApsaraMQ for Kafka:Envoyer et recevoir des messages via un endpoint d'instance

Dernière mise à jour :Aug 11, 2026

Connectez votre application à une instance ApsaraMQ for Kafka via un endpoint par défaut, SSL ou SASL pour envoyer et recevoir des messages.

Prérequis

  • Installez JDK 1.8 ou une version ultérieure. Pour plus d'informations, consultez la page Install JDK.

  • Installez Maven 2.5 ou une version ultérieure. Pour plus d'informations, consultez la page Install Maven.

  • Installez un outil de build.

    Cette rubrique utilise IntelliJ IDEA Ultimate à titre d'exemple.

  • Achetez et déployez une instance ApsaraMQ for Kafka.

    • Instance VPC : fournit uniquement un endpoint par défaut accessible depuis le même VPC.

    • Instance Internet/VPC : fournit un endpoint par défaut et un endpoint SSL. Accessible via Internet ou depuis un VPC.

    Remarque
    • Vous pouvez convertir une instance VPC en instance Internet/VPC, et vice versa. Pour plus d'informations, consultez la rubrique Upgrade or downgrade instance configurations.

    • L'endpoint SASL est désactivé par défaut et n'apparaît pas dans la console. Pour utiliser un endpoint SASL, activez-le manuellement. Pour plus d'informations, consultez la rubrique Grant permissions to a SASL user.

    • Pour en savoir plus sur les cas d'utilisation de chaque endpoint, consultez la rubrique Endpoint comparison.

Installer les dépendances Java

Les dépendances suivantes sont requises. Elles sont déjà incluses dans le fichier pom.xml du dossier kafka-java-demo ; vous n'avez donc pas besoin de les ajouter manuellement.

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>2.6.0</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.6</version>
</dependency>
Remarque

Nous vous recommandons de maintenir la cohérence entre la version majeure de la bibliothèque cliente et celle de votre instance ApsaraMQ for Kafka. Vous trouverez la version majeure de votre instance ApsaraMQ for Kafka sur la page Instance Details de la console ApsaraMQ for Kafka.

Configurer les paramètres

  1. Facultatif : Download the SSL root certificate. Si vous utilisez un endpoint SSL, téléchargez ce certificat.

  2. Accédez à Aliware-kafka-demos, cliquez sur download, puis téléchargez et décompressez le projet de démonstration.

  3. Importez le dossier kafka-java-demo du projet décompressé dans IntelliJ IDEA.

  4. Facultatif :Si vous utilisez un endpoint SSL ou un endpoint SASL pour vous connecter à l'instance, modifiez le fichier kafka_client_jaas.conf. Pour plus d'informations sur les endpoints d'instance, consultez la rubrique Endpoint comparison.

    KafkaClient {
      org.apache.kafka.common.security.plain.PlainLoginModule required
      username="xxxx"
      password="xxxx";
    }; 

    Pour une instance VPC, seules les ressources situées dans le même VPC peuvent accéder à l'instance Kafka, ce qui garantit une transmission des données sécurisée et privée. Pour renforcer la sécurité, activez la fonctionnalité ACL afin que les messages ne soient transmis qu'après authentification SASL. Utilisez le mécanisme PLAIN ou SCRAM selon vos exigences de sécurité. Pour plus d'informations, consultez la rubrique Enable the ACL feature.

    Pour une instance Internet/VPC, les messages transmis via Internet doivent être authentifiés et chiffrés. Utilisez SASL avec le mécanisme PLAIN sur une couche de transport SSL. Le protocole SASL_SSL empêche la transmission en texte clair sur Internet.

    Les paramètres username et password de l'exemple correspondent au nom d'utilisateur et au mot de passe SASL de l'instance.

    • Si la fonctionnalité ACL est désactivée pour une instance accessible via Internet, récupérez le nom d'utilisateur et le mot de passe de l'utilisateur par défaut dans la section Configuration Information de la page Instance Details de la console ApsaraMQ for Kafka console.

    • Si la fonctionnalité ACL est activée pour l'instance, assurez-vous que l'utilisateur SASL est de type PLAIN et dispose des autorisations nécessaires pour envoyer et recevoir des messages. Pour plus d'informations, consultez la rubrique Grant permissions to a SASL user.

  5. Modifiez le fichier de configuration kafka.properties.

    ##==============================Common parameters==============================
    bootstrap.servers=xxxxxxxxxxxxxxxxxxxxx
    topic=xxx
    group.id=xxx
    ##=======================Configure the following parameters based on your requirements========================
    ##SSL endpoint configuration
    ssl.truststore.location=/xxxx/only.4096.client.truststore.jks
    ##The value of ssl.truststore.password must be KafkaOnsClient and cannot be changed. 
    ssl.truststore.password=KafkaOnsClient
    ##Hostname verification algorithm. Keep this parameter empty. Do not change the setting.
    ssl.endpoint.identification.algorithm=
    java.security.auth.login.config=/xxxx/kafka_client_jaas.conf
    ##SASL endpoint with the PLAIN mechanism
    java.security.auth.login.config.plain=/xxxx/kafka_client_jaas_plain.conf
    ##SASL endpoint with the SCRAM mechanism
    java.security.auth.login.config.scram=/xxxx/kafka_client_jaas_scram.conf

    Parameter

    Description

    bootstrap.servers

    L'endpoint. Récupérez l'endpoint depuis la section Endpoint Information de la page Instance Details de la console ApsaraMQ for Kafka.

    topic

    Le nom du topic. Récupérez le nom du topic sur la page Topics de la console ApsaraMQ for Kafka.

    group.id

    Le Group de l'instance. Récupérez-le sur la page Groups de la console ApsaraMQ for Kafka.

    Remarque

    Ce paramètre est facultatif pour les producteurs mais obligatoire pour les consommateurs.

    ssl.truststore.location

    Le chemin local du certificat racine SSL téléchargé. Remplacez xxxx par votre chemin réel. Exemple : /home/ssl/only.4096.client.truststore.jks.

    Important

    Ce paramètre n'est pas requis si vous utilisez un endpoint par défaut ou un endpoint SASL. Il est obligatoire si vous utilisez un endpoint SSL.

    ssl.truststore.password

    Le mot de passe du truststore. La valeur est fixée à KafkaOnsClient. Ne la modifiez pas.

    ssl.endpoint.identification.algorithm

    L'algorithme de vérification du nom d'hôte. Laissez ce champ vide pour désactiver la vérification du nom d'hôte.

    java.security.auth.login.config

    Le chemin du fichier de configuration JAAS. Enregistrez le fichier kafka_client_jaas.conf du projet de démonstration dans un répertoire local et remplacez xxxx par le chemin réel. Exemple : /home/ssl/kafka_client_jaas.conf.

    Important

    Ce paramètre n'est pas requis si vous utilisez un endpoint par défaut. Il est obligatoire si vous utilisez un endpoint SSL ou un endpoint SASL.

Envoyer des messages

Compilez et exécutez le fichier KafkaProducerDemo.java pour envoyer des messages.

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Future;
// If you use an SSL or SASL endpoint, comment out the following line.
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
/*
* If you use an SSL or SASL endpoint, uncomment the following two lines.
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.config.SslConfigs;
*/

public class KafkaProducerDemo {

    public static void main(String args[]) {
          
       /*
        * If you use an SSL endpoint, uncomment the following line.
        * Set the path of the JAAS configuration file.
        JavaKafkaConfigurer.configureSasl();
        */
         
       /*
        * If you use a SASL endpoint with the PLAIN mechanism, uncomment the following line.
        * Set the path of the JAAS configuration file.
        JavaKafkaConfigurer.configureSaslPlain();
        */
       
       /*
        * If you use a SASL endpoint with the SCRAM mechanism, uncomment the following line.
        * Set the path of the JAAS configuration file.
        JavaKafkaConfigurer.configureSaslScram();
        */

        // Load kafka.properties.
        Properties kafkaProperties =  JavaKafkaConfigurer.getKafkaProperties();

        Properties props = new Properties();
        // Set the endpoint. Obtain the instance endpoint from the console.
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getProperty("bootstrap.servers"));
         
       /*
        * If you use an SSL endpoint, uncomment the following four lines.
        * Similar to the SASL path, this file cannot be packaged into a JAR file.
        props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, kafkaProperties.getProperty("ssl.truststore.location"));
        * The password for the truststore. Do not change this value.
        props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "KafkaOnsClient");
        * The security protocol. For SSL connections, this must be SASL_SSL.
        props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_SSL");
        * The SASL authentication method. Do not change this value.
        props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
        */

       /*
        * If you use a SASL endpoint with the PLAIN mechanism, uncomment the following two lines.
        * The security protocol.
        props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
        * The PLAIN mechanism.
        props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
        */

       /*
        * If you use a SASL endpoint with the SCRAM mechanism, uncomment the following two lines.
        * The security protocol.
        props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
        * The SCRAM mechanism.
        props.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-256");
        */

        // The serializers for message keys and values.
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        // The maximum wait time for a request.
        props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 30 * 1000);
        // The number of client-side retries.
        props.put(ProducerConfig.RETRIES_CONFIG, 5);
        // The client-side retry interval.
        props.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 3000);
         
       /*
        * If you use an SSL endpoint, uncomment the following line.
        * An empty value disables hostname verification.
        props.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
        */

        // Create a producer instance. The producer is thread-safe. A single producer instance is generally sufficient for one process.
        // To improve performance, you can create more producer instances, but no more than five is recommended.
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);

        // Create a Kafka message.
        String topic = kafkaProperties.getProperty("topic"); // The topic to send messages to. You must create this topic in the console first.
        String value = "this is the message's value"; // The content of the message.

        try {
            // Sending messages in a batch and collecting the futures can improve performance, but do not make the batch size too large.
            List<Future<RecordMetadata>> futures = new ArrayList<Future<RecordMetadata>>(128);
            for (int i =0; i < 100; i++) {
                // Send the message and obtain a Future object.
                ProducerRecord<String, String> kafkaMessage =  new ProducerRecord<String, String>(topic, value + ": " + i);
                Future<RecordMetadata> metadataFuture = producer.send(kafkaMessage);
                futures.add(metadataFuture);

            }
            producer.flush();
            for (Future<RecordMetadata> future: futures) {
                // Synchronously obtain the result of the Future object.
                try {
                    RecordMetadata recordMetadata = future.get();
                    System.out.println("Produce ok:" + recordMetadata.toString());
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        } catch (Exception e) {
            // If the message fails to be sent after client-side retries, your application must handle this error.
            System.out.println("error occurred");
            e.printStackTrace();
        }
    }
}

S'abonner aux messages

Choisissez l'une des méthodes suivantes pour vous abonner aux messages.

Abonnement mono-consommateur

Compilez et exécutez le fichier KafkaConsumerDemo.java pour recevoir des messages.

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
/*
* If you use an SSL endpoint, uncomment the following three lines. If you use a SASL endpoint, uncomment the first two lines.
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.config.SslConfigs;
*/

public class KafkaConsumerDemo {

    public static void main(String args[]) {

        // Set the path of the JAAS configuration file.
        /*
         * If you use an SSL endpoint, uncomment the following line.
        JavaKafkaConfigurer.configureSasl();
         */
                        
        /*
         * If you use a SASL endpoint with the PLAIN mechanism, uncomment the following line.
        JavaKafkaConfigurer.configureSaslPlain();
         */
                        
        /*
        * If you use a SASL endpoint with the SCRAM mechanism, uncomment the following line.
        JavaKafkaConfigurer.configureSaslScram();
        */

        // Load kafka.properties.
        Properties kafkaProperties =  JavaKafkaConfigurer.getKafkaProperties();

        Properties props = new Properties();
        // Set the endpoint. Obtain the instance endpoint from the console.
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getProperty("bootstrap.servers"));

        // If you use an SSL endpoint, comment out the following line.
        // Adjust this value based on the amount of data to pull and the client version. Default value: 30s.
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000);
        /*
         * If you use an SSL endpoint, uncomment the following six lines.
         * The path to the SSL truststore file. Ensure this path is correctly configured in your kafka.properties file.
         * Similar to the SASL path, this file cannot be packaged into a JAR file.
         props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, kafkaProperties.getProperty("ssl.truststore.location"));
         * The password for the truststore. Do not change this value.
         props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "KafkaOnsClient");
         * The security protocol. For SSL connections, this must be SASL_SSL.
         props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_SSL");
         * The SASL authentication method. Do not change this value.
         props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
         * The maximum interval allowed between two polls.
         * If a consumer fails to send a heartbeat within this interval, the broker considers the consumer inactive, removes it from the consumer group, and triggers a rebalance. Default value: 30s.
         props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000);
         * The amount of data to fetch per request. This parameter can significantly affect performance when accessing the instance over the Internet.
         props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 32000);
         props.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, 32000);
         */

        // If you use a SASL endpoint with the PLAIN mechanism, comment out the following line.
        // Adjust this value based on the amount of data to pull and the client version. Default value: 30s.
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000);
        /*
         * If you use a SASL endpoint with the PLAIN mechanism, uncomment the following three lines.
         * The security protocol.
         props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
         * The PLAIN mechanism.
         props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
         * The maximum interval allowed between two polls.
         * If a consumer fails to send a heartbeat within this interval, the broker considers the consumer inactive, removes it from the consumer group, and triggers a rebalance. Default value: 30s.
         props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000);
         */

        // If you use a SASL endpoint with the SCRAM mechanism, comment out the following line.
        // Adjust this value based on the amount of data to pull and the client version. Default value: 30s
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000);
        /*
         * If you use a SASL endpoint with the SCRAM mechanism, uncomment the following four lines.
         * The security protocol.
         props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
         * The SCRAM mechanism.
         props.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-256");
         * The maximum interval allowed between two polls.
         * If a consumer fails to send a heartbeat within this interval, the broker considers the consumer inactive, removes it from the consumer group, and triggers a rebalance. Default value: 30s.
         props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000);
         */

        // The maximum number of records to return in a single call to poll().
        // Do not set this value to a large number. If you poll a large amount of data but cannot consume the data before the next poll, a rebalance is triggered, which may cause lags.
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 30);
        // The deserializers for message keys and values.
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        // The consumer group to which the current consumer instance belongs. You must create the consumer group in the console first.
        // Consumer instances in the same group consume messages in a load-balanced manner.
        props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaProperties.getProperty("group.id"));
        
        // If you use an SSL endpoint, uncomment the following line.
        // An empty value disables hostname verification.
        //props.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");

        // Create a consumer instance.
        KafkaConsumer<String, String> consumer = new org.apache.kafka.clients.consumer.KafkaConsumer<String, String>(props);
        // Subscribe to topics. You can subscribe to multiple topics.
        // If the consumer instances have the same GROUP_ID_CONFIG value, we recommend that you configure them to subscribe to the same topics.
        List<String> subscribedTopics =  new ArrayList<String>();
        
        // If you use an SSL endpoint, comment out the first five lines and uncomment the sixth line.
        // If you want to subscribe to multiple topics, add them here.
        // You must create each topic in the console first.
        String topicStr = kafkaProperties.getProperty("topic");
        String[] topics = topicStr.split(",");
        for (String topic: topics) {
            subscribedTopics.add(topic.trim());
        }
        //subscribedTopics.add(kafkaProperties.getProperty("topic"));
        consumer.subscribe(subscribedTopics);

        // Consume messages in a loop.
        while (true){
            try {
                ConsumerRecords<String, String> records = consumer.poll(1000);
                // The polled data must be consumed before the next poll. The total time cannot exceed the value of SESSION_TIMEOUT_MS_CONFIG.
                // We recommend that you create a separate thread pool to consume messages and asynchronously return the results.
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println(String.format("Consume partition:%d offset:%d", record.partition(), record.offset()));
                }
            } catch (Exception e) {
                try {
                    Thread.sleep(1000);
                } catch (Throwable ignore) {

                }
          
                e.printStackTrace();
            }
        }
    }
}

Abonnement multi-consommateurs

Compilez et exécutez le fichier KafkaMultiConsumerDemo.java pour consommer des messages.

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
// If you use an SSL or SASL endpoint, uncomment the following line.

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
/*
* If you use an SSL endpoint, uncomment the following three lines. If you use a SASL endpoint, uncomment the first two lines.
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.config.SslConfigs;
*/
import org.apache.kafka.common.errors.WakeupException;

/**
 * This demo shows how to start multiple consumers in a single process to consume messages from a topic at the same time.
 * Make sure that the total number of consumers does not exceed the total number of partitions for the subscribed topic.
 */
public class KafkaMultiConsumerDemo {

    public static void main(String args[]) throws InterruptedException {
        
        // Set the path of the JAAS configuration file.
        /* 
         * If you use an SSL endpoint, uncomment the following line.
         JavaKafkaConfigurer.configureSasl();
         */
                            
        /* 
         * If you use a SASL endpoint with the PLAIN mechanism, uncomment the following line.
         JavaKafkaConfigurer.configureSaslPlain(); 
         */
                            
        /* 
         * If you use a SASL endpoint with the SCRAM mechanism, uncomment the following line.
         JavaKafkaConfigurer.configureSaslScram();
         */

        // Load kafka.properties.
        Properties kafkaProperties = JavaKafkaConfigurer.getKafkaProperties();

        Properties props = new Properties();
        // Set the endpoint. Obtain the instance endpoint from the console.
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getProperty("bootstrap.servers"));
        
        /*
         * If you use an SSL endpoint, uncomment the following four lines.
         * Similar to the SASL path, this file cannot be packaged into a JAR file.
         props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, kafkaProperties.getProperty("ssl.truststore.location"));
         * The password for the truststore. Do not change this value.
         props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "KafkaOnsClient");
         * The security protocol. For SSL connections, this must be SASL_SSL.
         props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_SSL");
         * The SASL authentication method. Do not change this value.
         props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
         */
        
        /*
         * If you use a SASL endpoint with the PLAIN mechanism, uncomment the following two lines.
         * The security protocol.
         props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
         * The PLAIN mechanism.
         props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
         */

        /* 
         * If you use a SASL endpoint with the SCRAM mechanism, uncomment the following two lines.
         * The security protocol.
         props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
         * The SCRAM mechanism.
         props.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-256");
         */

        // The maximum interval allowed between two polls.
        // If a consumer fails to send a heartbeat within this interval, the broker considers the consumer inactive, removes it from the consumer group, and triggers a rebalance. Default value: 30s.
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 30000);
        // The maximum number of records to return in a single call to poll().
        // Do not set this value to a large number. If you poll a large amount of data but cannot consume the data before the next poll, a rebalance is triggered, which may cause lags.
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 30);
        // The deserializers for message keys and values.
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        // The consumer group to which the current consumer instance belongs. You must create the consumer group in the console first.
        // Consumer instances in the same group consume messages in a load-balanced manner.
        props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaProperties.getProperty("group.id"));

        /* 
         * If you use an SSL endpoint, uncomment the following line.
         * An empty value disables hostname verification.
         props.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
         */

        int consumerNum = 2;
        Thread[] consumerThreads = new Thread[consumerNum];
        for (int i = 0; i < consumerNum; i++) {
            KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

            List<String> subscribedTopics = new ArrayList<String>();
            subscribedTopics.add(kafkaProperties.getProperty("topic"));
            consumer.subscribe(subscribedTopics);

            KafkaConsumerRunner kafkaConsumerRunner = new KafkaConsumerRunner(consumer);
            consumerThreads[i] = new Thread(kafkaConsumerRunner);
        }

        for (int i = 0; i < consumerNum; i++) {
            consumerThreads[i].start();
        }

        for (int i = 0; i < consumerNum; i++) {
            consumerThreads[i].join();
        }
    }

    static class KafkaConsumerRunner implements Runnable {
        private final AtomicBoolean closed = new AtomicBoolean(false);
        private final KafkaConsumer consumer;

        KafkaConsumerRunner(KafkaConsumer consumer) {
            this.consumer = consumer;
        }

        @Override
        public void run() {
            try {
                while (!closed.get()) {
                    try {
                        ConsumerRecords<String, String> records = consumer.poll(1000);
                        // The polled data must be consumed before the next poll. The total time cannot exceed the value of SESSION_TIMEOUT_MS_CONFIG.
                        for (ConsumerRecord<String, String> record : records) {
                            System.out.println(String.format("Thread:%s Consume partition:%d offset:%d", Thread.currentThread().getName(), record.partition(), record.offset()));
                        }
                    } catch (Exception e) {
                        try {
                            Thread.sleep(1000);
                        } catch (Throwable ignore) {

                        }
                        e.printStackTrace();
                    }
                }
            } catch (WakeupException e) {
                // Ignore the exception if the consumer is closed.
                if (!closed.get()) {
                    throw e;
                }
            } finally {
                consumer.close();
            }
        }
        // A shutdown hook that can be called by another thread.
        public void shutdown() {
            closed.set(true);
            consumer.wakeup();
        }
    }
}

FAQ

Configurer le certificat SASL_SSL

Téléchargez le certificat SSL à partir de l'URL indiquée à l'étape 1 de la section « Configurer les paramètres ». Ensuite, dans votre fichier kafka.properties, définissez ssl.truststore.location sur le chemin local du certificat.

Utiliser un certificat SSL personnalisé

Non. Vous devez utiliser le certificat SSL fourni par ApsaraMQ for Kafka.

Références