Todos os produtos
Search
Central de documentação

Simple Log Service:Consumo de logs com um consumer group

Última atualização: Jul 03, 2026

O consumo de dados do Log Service em tempo real via SDK exige o gerenciamento de detalhes de implementação, como balanceamento de carga e failover entre consumidores. Um consumer group gerencia essas complexidades automaticamente, permitindo o consumo de dados quase em tempo real, geralmente em questão de segundos.

Visão geral

Um Logstore contém múltiplos shards. Um consumer group consome dados atribuindo esses shards aos seus consumidores conforme as seguintes regras:

  • Cada shard é atribuído a apenas um consumidor por vez.

  • Um único consumidor pode receber múltiplos shards.

Quando um novo consumidor entra em um consumer group, ocorre um rebalanceamento dos shards entre todos os consumidores para garantir o equilíbrio de carga. As mesmas regras se aplicam.

image

Conceitos principais

Termo

Descrição

consumer group

Conjunto formado por vários consumidores que consomem dados do mesmo Logstore simultaneamente, sem duplicidade.

Importante

É possível criar até 30 consumer groups para cada Logstore.

consumer

Unidade básica de um consumer group responsável pelo consumo efetivo de dados.

Importante

Os consumidores dentro do mesmo consumer group devem ter nomes exclusivos.

Logstore

Unidade destinada à coleta, armazenamento e consulta de dados. Para mais informações, consulte Logstore.

shard

Unidade que controla a capacidade de leitura e gravação de um Logstore. Os dados são sempre armazenados em um shard. Para mais informações, consulte shard.

checkpoint

Posição no fluxo de dados que marca o último dado processado pelo consumidor. Isso permite que o consumidor retome o processamento desse ponto após uma reinicialização.

Nota

Ao consumir dados com um consumer group, os checkpoints são salvos automaticamente em caso de falha do programa. Após a recuperação, o programa continua o consumo a partir do último checkpoint, evitando o consumo duplicado.

Pré-requisitos

Etapa 1: Criar um consumer group

É possível criar um consumer group utilizando o SDK, a API ou a CLI.

SDK

O código abaixo cria um consumer group:

CreateConsumerGroup.java

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.ConsumerGroup;
import com.aliyun.openservices.log.exception.LogException;

public class CreateConsumerGroup {
    public static void main(String[] args) throws LogException {
         // This example obtains the AccessKey ID and AccessKey secret from environment variables.
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Enter the project name.
        String projectName = "ali-test-project";
        // Enter the Logstore name.
        String logstoreName = "ali-test-logstore";
        // Set the endpoint for Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace it with the actual endpoint.
        String host = "https://cn-hangzhou.log.aliyuncs.com";

        // Create a Simple Log Service client.
        Client client = new Client(host, accessId, accessKey);

        try {
            // Set the consumer group name.
            String consumerGroupName = "ali-test-consumergroup2";
            System.out.println("ready to create consumergroup");

            ConsumerGroup consumerGroup = new ConsumerGroup(consumerGroupName, 300, true);

            client.CreateConsumerGroup(projectName, logstoreName, consumerGroup);

            System.out.println(String.format("create consumergroup %s success", consumerGroupName));

        } catch (LogException e) {
            System.out.println("LogException e :" + e.toString());
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            throw e;
        }
    }
}

Para exemplos de código sobre como gerenciar consumer groups, consulte Usar o Java SDK para gerenciar consumer groups e Usar o Simple Log Service SDK for Python para gerenciar consumer groups.

API

Para criar um consumer group usando a API, consulte CreateConsumerGroup.

Para verificar se o consumer group foi criado, consulte ListConsumerGroup.

CLI

Para criar um consumer group usando a CLI, consulte create_consumer_group.

Para verificar se o consumer group foi criado, consulte list_consumer_group.

Etapa 2: Consumir dados de log

Funcionamento

Quando um consumidor que utiliza o SDK de consumer group é iniciado pela primeira vez, o SDK cria o consumer group caso ele ainda não exista. O checkpoint inicial define a posição de começo do consumo, sendo utilizado apenas na criação do consumer group. Nas reinicializações seguintes, o consumidor retoma a partir do último checkpoint salvo no servidor. Por exemplo:

  • LogHubConfig.ConsumePosition.BEGIN_CURSOR: O consumer group inicia o consumo a partir do primeiro log existente no Logstore.

  • LogHubConfig.ConsumePosition.END_CURSOR: O consumer group inicia o consumo após o último log existente no Logstore.

Exemplos

É possível consumir dados com um consumer group usando os SDKs para Java, C++, Python e Go. Os exemplos a seguir utilizam Java.

Exemplo 1: Consumo via SDK

  1. Adicione as dependências do Maven.

    No arquivo pom.xml, adicione as seguintes dependências:

    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>2.5.0</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun.openservices</groupId>
      <artifactId>loghub-client-lib</artifactId>
      <version>0.6.50</version>
    </dependency>
  2. Crie uma classe para definir a lógica de processamento dos logs.

    SampleLogHubProcessor.java

    import com.aliyun.openservices.log.common.FastLog;
    import com.aliyun.openservices.log.common.FastLogContent;
    import com.aliyun.openservices.log.common.FastLogGroup;
    import com.aliyun.openservices.log.common.FastLogTag;
    import com.aliyun.openservices.log.common.LogGroupData;
    import com.aliyun.openservices.loghub.client.ILogHubCheckPointTracker;
    import com.aliyun.openservices.loghub.client.exceptions.LogHubCheckPointException;
    import com.aliyun.openservices.loghub.client.interfaces.ILogHubProcessor;
    import java.util.List;
    public class SampleLogHubProcessor implements ILogHubProcessor {
        private int shardId;
        // Tracks the last time a checkpoint was saved.
        private long mLastSaveTime = 0;
        // Called once upon processor initialization.
        public void initialize(int shardId) {
            this.shardId = shardId;
        }
        // The main logic for consuming data. All exceptions must be handled within this method. Do not throw exceptions directly.
        public String process(List<LogGroupData> logGroups, ILogHubCheckPointTracker checkPointTracker) {
            // Print the fetched data.
            for (LogGroupData logGroup : logGroups) {
                FastLogGroup fastLogGroup = logGroup.GetFastLogGroup();
                System.out.println("Tags");
                for (int i = 0; i < fastLogGroup.getLogTagsCount(); ++i) {
                    FastLogTag logTag = fastLogGroup.getLogTags(i);
                    System.out.printf("%s : %s\n", logTag.getKey(), logTag.getValue());
                }
                for (int i = 0; i < fastLogGroup.getLogsCount(); ++i) {
                    FastLog log = fastLogGroup.getLogs(i);
                    System.out.println("--------\nLog: " + i + ", time: " + log.getTime() + ", GetContentCount: " + log.getContentsCount());
                    for (int j = 0; j < log.getContentsCount(); ++j) {
                        FastLogContent content = log.getContents(j);
                        System.out.println(content.getKey() + "\t:\t" + content.getValue());
                    }
                }
            }
            long curTime = System.currentTimeMillis();
            // Save a checkpoint to the server every 30 seconds. If the worker terminates unexpectedly, the new worker resumes from the last checkpoint, potentially reprocessing a small amount of data.
            try {
                if (curTime - mLastSaveTime > 30 * 1000) {
                    // A 'true' parameter flushes the checkpoint to the server immediately. By default, the in-memory checkpoint is automatically flushed to the server every 60 seconds.
                    checkPointTracker.saveCheckPoint(true);
                    mLastSaveTime = curTime;
                } else {
                    // A 'false' parameter caches the checkpoint locally. It will be flushed to the server by the auto-update mechanism.
                    checkPointTracker.saveCheckPoint(false);
                }
            } catch (LogHubCheckPointException e) {
                e.printStackTrace();
            }
            return null;
        }
        // This method is called when the worker is shutting down. You can perform cleanup tasks here.
        public void shutdown(ILogHubCheckPointTracker checkPointTracker) {
            // Save the checkpoint to the server immediately.
            try {
                checkPointTracker.saveCheckPoint(true);
            } catch (LogHubCheckPointException e) {
                e.printStackTrace();
            }
        }
    }

    Para mais exemplos de código, consulte os repositórios aliyun-log-consumer-java e Aliyun LOG Go Consumer.

  3. Crie uma factory para gerar instâncias do seu processador de logs.

    SampleLogHubProcessorFactory.java

    import com.aliyun.openservices.loghub.client.interfaces.ILogHubProcessor;
    import com.aliyun.openservices.loghub.client.interfaces.ILogHubProcessorFactory;
    class SampleLogHubProcessorFactory implements ILogHubProcessorFactory {
        public ILogHubProcessor generatorProcessor() {
            // Generate a consumer instance. Note: Each call to the generatorProcessor method should return a new SampleLogHubProcessor object.
            return new SampleLogHubProcessor();
        }
    }
  4. Crie uma classe principal para configurar e iniciar a thread worker.

    Main.java

    import com.aliyun.openservices.loghub.client.ClientWorker;
    import com.aliyun.openservices.loghub.client.config.LogHubConfig;
    import com.aliyun.openservices.loghub.client.exceptions.LogHubClientWorkerException;
    public class Main {
        // The endpoint of Simple Log Service. Replace with your actual endpoint.
        private static String Endpoint = "cn-hangzhou.log.aliyuncs.com";
        // The project name. Replace with the name of an existing project.
        private static String Project = "ali-test-project";
        // The Logstore name. Replace with the name of an existing Logstore.
        private static String Logstore = "ali-test-logstore";
        // You do not need to create the consumer group beforehand; the program automatically creates it on the first run.
        private static String ConsumerGroup = "ali-test-consumergroup2";
        // This example retrieves the AccessKey ID and AccessKey Secret from environment variables.
        private static String AccessKeyId= System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        private static String AccessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        public static void main(String[] args) throws LogHubClientWorkerException, InterruptedException {
            // "consumer_1" is the consumer name, which must be unique within a consumer group. To balance consumption across multiple machines, you can use unique identifiers like the machine's IP address as the consumer name.
            // maxFetchLogGroupSize sets the maximum number of LogGroups to fetch per request. The default value is usually sufficient. You can adjust it by using config.setMaxFetchLogGroupSize(100). The valid range is (0, 1000].
            LogHubConfig config = new LogHubConfig(ConsumerGroup, "consumer_1", Endpoint, Project, Logstore, AccessKeyId, AccessKeySecret, LogHubConfig.ConsumePosition.BEGIN_CURSOR,1000);
            ClientWorker worker = new ClientWorker(new SampleLogHubProcessorFactory(), config);
            Thread thread = new Thread(worker);
            // After the thread starts, the ClientWorker runs automatically. ClientWorker implements the Runnable interface.
            thread.start();
            Thread.sleep(60 * 60 * 1000);
            // Call the worker's shutdown() method to stop the consumer instance and its associated thread.
            worker.shutdown();
            // The ClientWorker creates asynchronous tasks. After shutdown(), wait for these tasks to complete gracefully. A 30-second sleep is recommended.
            Thread.sleep(30 * 1000);
        }
    }
  5. Execute o arquivo Main.java.

    Abaixo está um exemplo da saída ao consumir logs do NGINX:

    :    GET
    request_uri    :    /request/path-3/file-7
    status    :    200
    body_bytes_sent    :    3820
    host    :    www.example.com
    request_time    :    43
    request_length    :    1987
    http_user_agent    :    Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36
    http_referer    :    www.example.com
    http_x_forwarded_for    :    192.168.10.196
    upstream_response_time    :    0.02
    --------
    Log: 158, time: 1635629778, GetContentCount: 14
    ......
        category    :    null
        source    :    127.0.0.1
        topic    :    nginx_access_log
        machineUUID    :    null
    Tags
        __receive_time__    :    1635629815
    --------
    Log: 0, time: 1635629788, GetContentCount: 14
    ......
        category    :    null
        source    :    127.0.0.1
        topic    :    nginx_access_log
        machineUUID    :    null
    Tags
        __receive_time__    :    1635629877
    --------
    ......

Exemplo 2: Consumo via SDK com SPL

  1. Adicione as dependências do Maven.

    No arquivo pom.xml, adicione as seguintes dependências:

    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>2.5.0</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun.openservices</groupId>
      <artifactId>loghub-client-lib</artifactId>
      <version>0.6.50</version>
    </dependency>
  2. Crie uma classe para definir a lógica de processamento dos logs.

    SPLLogHubProcessor.java

    import com.aliyun.openservices.log.common.FastLog;
    import com.aliyun.openservices.log.common.FastLogContent;
    import com.aliyun.openservices.log.common.FastLogGroup;
    import com.aliyun.openservices.log.common.FastLogTag;
    import com.aliyun.openservices.log.common.LogGroupData;
    import com.aliyun.openservices.loghub.client.ILogHubCheckPointTracker;
    import com.aliyun.openservices.loghub.client.exceptions.LogHubCheckPointException;
    import com.aliyun.openservices.loghub.client.interfaces.ILogHubProcessor;
    import java.util.List;
    public class SPLLogHubProcessor implements ILogHubProcessor {
        private int shardId;
        // Tracks the last time a checkpoint was saved.
        private long mLastSaveTime = 0;
        // Called once upon processor initialization.
        public void initialize(int shardId) {
            this.shardId = shardId;
        }
        // The main logic for consuming data. All exceptions must be handled within this method. Do not throw exceptions directly.
        public String process(List<LogGroupData> logGroups, ILogHubCheckPointTracker checkPointTracker) {
            // Print the fetched data.
            for (LogGroupData logGroup : logGroups) {
                FastLogGroup fastLogGroup = logGroup.GetFastLogGroup();
                System.out.println("Tags");
                for (int i = 0; i < fastLogGroup.getLogTagsCount(); ++i) {
                    FastLogTag logTag = fastLogGroup.getLogTags(i);
                    System.out.printf("%s : %s\n", logTag.getKey(), logTag.getValue());
                }
                for (int i = 0; i < fastLogGroup.getLogsCount(); ++i) {
                    FastLog log = fastLogGroup.getLogs(i);
                    System.out.println("--------\nLog: " + i + ", time: " + log.getTime() + ", GetContentCount: " + log.getContentsCount());
                    for (int j = 0; j < log.getContentsCount(); ++j) {
                        FastLogContent content = log.getContents(j);
                        System.out.println(content.getKey() + "\t:\t" + content.getValue());
                    }
                }
            }
            long curTime = System.currentTimeMillis();
            // Save a checkpoint to the server every 30 seconds. If the worker terminates unexpectedly, the new worker resumes from the last checkpoint, potentially reprocessing a small amount of data.
            try {
                if (curTime - mLastSaveTime > 30 * 1000) {
                    // A 'true' parameter flushes the checkpoint to the server immediately. By default, the in-memory checkpoint is automatically flushed to the server every 60 seconds.
                    checkPointTracker.saveCheckPoint(true);
                    mLastSaveTime = curTime;
                } else {
                    // A 'false' parameter caches the checkpoint locally. It will be flushed to the server by the auto-update mechanism.
                    checkPointTracker.saveCheckPoint(false);
                }
            } catch (LogHubCheckPointException e) {
                e.printStackTrace();
            }
            return null;
        }
        // This method is called when the worker is shutting down. You can perform cleanup tasks here.
        public void shutdown(ILogHubCheckPointTracker checkPointTracker) {
            // Save the checkpoint to the server immediately.
            try {
                checkPointTracker.saveCheckPoint(true);
            } catch (LogHubCheckPointException e) {
                e.printStackTrace();
            }
        }
    }
  3. Crie uma factory para gerar instâncias do seu processador de logs.

    SPLLogHubProcessorFactory.java

    import com.aliyun.openservices.loghub.client.interfaces.ILogHubProcessor;
    import com.aliyun.openservices.loghub.client.interfaces.ILogHubProcessorFactory;
    class SPLLogHubProcessorFactory implements ILogHubProcessorFactory {
        public ILogHubProcessor generatorProcessor() {
            // Generate a consumer instance. Note: Each call to the generatorProcessor method should return a new SPLLogHubProcessor object.
            return new SPLLogHubProcessor();
        }
    }
  4. Crie uma classe principal para configurar e iniciar a thread worker.

    Main.java

    import com.aliyun.openservices.loghub.client.ClientWorker;
    import com.aliyun.openservices.loghub.client.config.LogHubConfig;
    import com.aliyun.openservices.loghub.client.exceptions.LogHubClientWorkerException;
    public class Main {
        // The endpoint of Simple Log Service. Replace with your actual endpoint.
        private static String Endpoint = "cn-hangzhou.log.aliyuncs.com";
        // The project name. Replace with the name of an existing project.
        private static String Project = "ali-test-project";
        // The Logstore name. Replace with the name of an existing Logstore.
        private static String Logstore = "ali-test-logstore";
        // You do not need to create the consumer group beforehand; the program automatically creates it on the first run.
        private static String ConsumerGroup = "ali-test-consumergroup2";
        // This example retrieves the AccessKey ID and AccessKey Secret from environment variables.
        private static String AccessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        private static String AccessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        public static void main(String[] args) throws LogHubClientWorkerException, InterruptedException {
            // "consumer_1" is the consumer name, which must be unique within a consumer group. To balance consumption across multiple machines, you can use unique identifiers like the machine's IP address as the consumer name.
            // maxFetchLogGroupSize sets the maximum number of LogGroups to fetch per request. The default value is usually sufficient. You can adjust it by using config.setMaxFetchLogGroupSize(100). The valid range is (0, 1000].
            LogHubConfig config = new LogHubConfig(ConsumerGroup, "consumer_1", Endpoint, Project, Logstore, AccessKeyId, AccessKeySecret, LogHubConfig.ConsumePosition.BEGIN_CURSOR, 1000);
            // Use setQuery to specify an SPL statement to filter logs during consumption.
            config.setQuery("* | where cast(body_bytes_sent as bigint) > 14000");
            ClientWorker worker = new ClientWorker(new SPLLogHubProcessorFactory(), config);
            Thread thread = new Thread(worker);
            // After the thread starts, the ClientWorker runs automatically. ClientWorker implements the Runnable interface.
            thread.start();
            Thread.sleep(60 * 60 * 1000);
            // Call the worker's shutdown() method to stop the consumer instance and its associated thread.
            worker.shutdown();
            // The ClientWorker creates asynchronous tasks. After shutdown(), wait for these tasks to complete gracefully. A 30-second sleep is recommended.
            Thread.sleep(30 * 1000);
        }
    }
  5. Execute o arquivo Main.java.

    Abaixo está um exemplo da saída ao consumir logs do NGINX:

    :    GET
    request_uri    :    /request/path-3/file-7
    status    :    200
    body_bytes_sent    :    3820
    host    :    www.example.com
    request_time    :    43
    request_length    :    1987
    http_user_agent    :    Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36
    http_referer    :    www.example.com
    http_x_forwarded_for    :    192.168.10.196
    upstream_response_time    :    0.02
    --------
    Log: 158, time: 1635629778, GetContentCount: 14
    ......
        category    :    null
        source    :    127.0.0.1
        topic    :    nginx_access_log
        machineUUID    :    null
    Tags
        __receive_time__    :    1635629815
    --------
    Log: 0, time: 1635629788, GetContentCount: 14
    ......
        category    :    null
        source    :    127.0.0.1
        topic    :    nginx_access_log
        machineUUID    :    null
    Tags
        __receive_time__    :    1635629877
    --------
    ......

Etapa 3: Visualizar o status do consumer group

Visualize o status de um consumer group usando um dos métodos a seguir:

Java SDK

  1. Visualize o checkpoint de consumo de cada shard. O código abaixo serve como exemplo:

    ConsumerGroupTest.java

    import java.util.List;
    import com.aliyun.openservices.log.Client;
    import com.aliyun.openservices.log.common.Consts.CursorMode;
    import com.aliyun.openservices.log.common.ConsumerGroup;
    import com.aliyun.openservices.log.common.ConsumerGroupShardCheckPoint;
    import com.aliyun.openservices.log.exception.LogException;
    public class ConsumerGroupTest {
        static String endpoint = "cn-hangzhou.log.aliyuncs.com";
        static String project = "ali-test-project";
        static String logstore = "ali-test-logstore";
        static String accesskeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        static String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        public static void main(String[] args) throws LogException {
            Client client = new Client(endpoint, accesskeyId, accesskey);
            // Get all consumer groups in the Logstore. The list is empty if no consumer groups exist.
            List<ConsumerGroup> consumerGroups = client.ListConsumerGroup(project, logstore).GetConsumerGroups();
            for(ConsumerGroup c: consumerGroups){
                // Print the consumer group properties: name, heartbeat timeout, and ordered consumption status.
                System.out.println("Name: " + c.getConsumerGroupName());
                System.out.println("heartbeat timeout: " + c.getTimeout());
                System.out.println("ordered consumption: " + c.isInOrder());
                for(ConsumerGroupShardCheckPoint cp: client.GetCheckPoint(project, logstore, c.getConsumerGroupName()).GetCheckPoints()){
                    System.out.println("shard: " + cp.getShard());
                    // The time is a long integer, accurate to the microsecond.
                    System.out.println("Last checkpoint update time: " + cp.getUpdateTime());
                    System.out.println("Consumer name: " + cp.getConsumer());
                    String consumerPrg = "";
                    if(cp.getCheckPoint().isEmpty())
                        consumerPrg = "Consumption has not started";
                    else{
                        // A UNIX timestamp in seconds. Format the output as needed.
                        try{
                            int prg = client.GetPrevCursorTime(project, logstore, cp.getShard(), cp.getCheckPoint()).GetCursorTime();
                            consumerPrg = "" + prg;
                        }
                        catch(LogException e){
                            if(e.GetErrorCode() == "InvalidCursor")
                                consumerPrg = "Invalid. The consumption checkpoint is older than the data retention period.";
                            else{
                                // internal server error
                                throw e;
                            }
                        }
                    }
                    System.out.println("consumption checkpoint: " + consumerPrg);
                    String endCursor = client.GetCursor(project, logstore, cp.getShard(), CursorMode.END).GetCursor();
                    int endPrg = 0;
                    try{
                        endPrg = client.GetPrevCursorTime(project, logstore, cp.getShard(), endCursor).GetCursorTime();
                    }
                    catch(LogException e){
                        // do nothing
                    }
                    // A UNIX timestamp in seconds. Format the output as needed.
                    System.out.println("Arrival time of the last record: " + endPrg);
                }
            }
        }
    }
  2. Confira abaixo um exemplo de saída:

    Name: ali-test-consumergroup2
    heartbeat timeout: 60
    ordered consumption: false
    shard: 0
    Last checkpoint update time: 0
    Consumer name: consumer_1
    consumption checkpoint: Consumption has not started
    Arrival time of the last record: 1729583617
    shard: 1
    Last checkpoint update time: 0
    Consumer name: consumer_1
    consumption checkpoint: Consumption has not started
    Arrival time of the last record: 1729583738
    Process finished with exit code 0

Console

  1. Faça login no console do Simple Log Service.

  2. Na seção Projects, clique em no projeto desejado.

    image

  3. Na aba Log Storage > Logstores, clique em no ícone 展开节点 à esquerda do Logstore alvo e, em seguida, clique em no ícone 展开节点 à esquerda de Data Consumption.

  4. Na lista de consumer groups, clique em no grupo desejado.

  5. Na página Consumer Group Status, visualize o checkpoint de consumo de cada shard. Esta página exibe detalhes individuais de cada shard, incluindo seu ID (shard), Last Consumed Time e o Client responsável pelo consumo. Também estão disponíveis os botões Refresh e Reset Checkpoint.

Operações relacionadas

  • Autorização de usuário RAM

    Para gerenciar consumer groups com um usuário RAM, conceda as permissões necessárias a esse usuário. Para mais informações, consulte Criar e autorizar um usuário RAM.

    A tabela a seguir lista as Actions necessárias.

    Action

    Descrição

    Resource

    log:GetCursorOrData(GetCursor)

    Obtém um cursor com base em um horário especificado.

    acs:log:${regionName}:${projectOwnerAliUid}:project/${projectName}/logstore/${LogStoreName}

    log:CreateConsumerGroup(CreateConsumerGroup)

    Cria um consumer group em um Logstore específico.

    acs:log:${regionName}:${projectOwnerAliUid}:project/${projectName}/logstore/${LogStoreName}/consumergroup/${consumerGroupName}

    log:ListConsumerGroup(ListConsumerGroup)

    Lista todos os consumer groups em um Logstore específico.

    acs:log:${regionName}:${projectOwnerAliUid}:project/${projectName}/logstore/${LogStoreName}/consumergroup/*

    log:ConsumerGroupUpdateCheckPoint(UpdateCheckPoint)

    Atualiza o checkpoint em um shard para um consumer group específico.

    acs:log:${regionName}:${projectOwnerAliUid}:project/${projectName}/logstore/${LogStoreName}/consumergroup/${consumerGroupName}

    log:ConsumerGroupHeartBeat(ConsumerGroupHeartBeat)

    Envia um heartbeat de um consumidor específico para o servidor.

    acs:log:${regionName}:${projectOwnerAliUid}:project/${projectName}/logstore/${LogStoreName}/consumergroup/${consumerGroupName}

    log:UpdateConsumerGroup(UpdateConsumerGroup)

    Modifica as propriedades de um consumer group específico.

    acs:log:${regionName}:${projectOwnerAliUid}:project/${projectName}/logstore/${LogStoreName}/consumergroup/${consumerGroupName}

    log:GetConsumerGroupCheckPoint(GetConsumerGroupCheckPoint)

    Obtém o checkpoint de um ou de todos os shards de um consumer group específico.

    acs:log:${regionName}:${projectOwnerAliUid}:project/${projectName}/logstore/${LogStoreName}/consumergroup/${consumerGroupName}

    Para conceder as permissões listadas abaixo a um usuário RAM, utilize a política de exemplo a seguir.

    • ID da conta Alibaba Cloud: 174649****602745

    • ID da região: cn-hangzhou

    • Nome do projeto: project-test

    • Nome do Logstore: logstore-test

    • Nome do consumer group: consumergroup-test

    Política de exemplo:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "log:GetCursorOrData"
          ],
          "Resource": "acs:log:cn-hangzhou:174649****602745:project/project-test/logstore/logstore-test"
        },
        {
          "Effect": "Allow",
          "Action": [
            "log:CreateConsumerGroup",
            "log:ListConsumerGroup"
          ],
          "Resource": "acs:log:cn-hangzhou:174649****602745:project/project-test/logstore/logstore-test/consumergroup/*"
        },
        {
          "Effect": "Allow",
          "Action": [
            "log:ConsumerGroupUpdateCheckPoint",
            "log:ConsumerGroupHeartBeat",
            "log:UpdateConsumerGroup",
            "log:GetConsumerGroupCheckPoint"
          ],
          "Resource": "acs:log:cn-hangzhou:174649****602745:project/project-test/logstore/logstore-test/consumergroup/consumergroup-test"
        }
      ]
    }
  • Solução de problemas

    Para facilitar a solução de problemas, configure o Log4j na sua aplicação consumidora para registrar exceções do consumer group. Abaixo está um exemplo de configuração do log4j.properties:

    log4j.rootLogger = info,stdout
    log4j.appender.stdout = org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target = System.out
    log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

    Após configurar o Log4j, a aplicação consumidora emitirá informações de exceção semelhantes às seguintes:

    [WARN ] 2018-03-14 12:01:52,747 method:com.aliyun.openservices.loghub.client.LogHubConsumer.sampleLogError(LogHubConsumer.java:159)
    com.aliyun.openservices.log.exception.LogException: Invalid loggroup count, (0,1000]
  • Consumir dados a partir de um horário específico

    // consumerStartTimeInSeconds indicates the time from which to start consuming data.
    public LogHubConfig(String consumerGroupName, 
                          String consumerName, 
                          String loghubEndPoint,
                          String project, String logStore,
                          String accessId, String accessKey,
                          int consumerStartTimeInSeconds);
    // position is an enumeration. LogHubConfig.ConsumePosition.BEGIN_CURSOR starts consumption from the oldest data. LogHubConfig.ConsumePosition.END_CURSOR starts consumption from the latest data.
    public LogHubConfig(String consumerGroupName, 
                          String consumerName, 
                          String loghubEndPoint,
                          String project, String logStore,
                          String accessId, String accessKey,
                          ConsumePosition position);
    Nota
    • Escolha um construtor de acordo com suas necessidades.

    • Caso já exista um checkpoint salvo no servidor, o consumo será retomado a partir desse ponto.

    • O Simple Log Service prioriza um checkpoint salvo para o consumo. Se você especificar um horário de início, certifique-se de que o valor de consumerStartTimeInSeconds esteja dentro do período de retenção de dados (TTL). Caso contrário, o horário de início especificado será ignorado.

  • Redefinir um checkpoint

    public static void updateCheckpoint() throws Exception {
            Client client = new Client(host, accessId, accessKey);
            // The timestamp must be a UNIX timestamp in seconds. If your timestamp is in milliseconds, divide it by 1000.
            long timestamp = Timestamp.valueOf("2017-11-15 00:00:00").getTime() / 1000;
            ListShardResponse response = client.ListShard(new ListShardRequest(project, logStore));
            for (Shard shard : response.GetShards()) {
                int shardId = shard.GetShardId();
                String cursor = client.GetCursor(project, logStore, shardId, timestamp).GetCursor();
                client.UpdateCheckPoint(project, logStore, consumerGroup, shardId, cursor);
            }
        }

Referências