Los grupos de consumidores se encargan del balanceo de carga y la conmutación por error durante el consumo de datos de registros. De este modo, usted puede concentrarse en la lógica de negocio. Este tema proporciona código de ejemplo para crear, modificar, consultar y eliminar grupos de consumidores, así como sus puntos de control.
Requisitos previos
Simple Log Service está activado.
El SDK de Python para Simple Log Service es initialized.
El SDK de Java para Simple Log Service está instalado. Para obtener más información, consulte Install the Java SDK.
Se creó un proyecto y un logstore estándar, y ya se recopilan los registros. Para obtener más información, consulte Manage projects, Create a basic LogStore y Data collection.
Cree los índices antes de consultar los registros. Para obtener más información, consulte Create indexes.
Precauciones
En este ejemplo se utiliza el endpoint público de Simple Log Service correspondiente a la región China (Hangzhou). Endpoint: https://cn-hangzhou.log.aliyuncs.com.
Si necesita acceder a Simple Log Service desde otros servicios de Alibaba Cloud ubicados en la misma región que su proyecto, utilice el endpoint interno de Simple Log Service: https://cn-hangzhou-intranet.log.aliyuncs.com.
Para obtener más información sobre las regiones y los endpoints compatibles con Simple Log Service, consulte Endpoint.
Crear un grupo de consumidores
A continuación se muestra el código para crear un grupo de consumidores llamado ali-test-consumergroup.
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;
}
}
}
Resultado esperado:
ready to create consumergroup
create consumergroup ali-test-consumergroup success
Modificar un grupo de consumidores
A continuación se muestra el código para modificar el grupo de consumidores llamado ali-test-consumergroup.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.exception.LogException;
public class UpdateConsumerGroup {
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 {
String consumerGroupName = "ali-test-consumergroup";
System.out.println("ready to update consumergroup");
// Change the timeout period of the consumer group to 350 seconds.
client.UpdateConsumerGroup(projectName, logstoreName, consumerGroupName, false, 350);
System.out.println(String.format("update 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;
}
}
}
Resultado esperado:
ready to update consumergroup
update consumergroup ali-test-consumergroup success
Consultar todos los grupos de consumidores
A continuación se muestra el código para consultar todos los grupos de consumidores de un logstore.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.ConsumerGroup;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.ListConsumerGroupResponse;
public class ListConsumerGroup {
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 {
System.out.println("ready to list consumergroup");
// Query all consumer groups in the specified Logstore.
ListConsumerGroupResponse response = client.ListConsumerGroup(projectName,logstoreName);
for(ConsumerGroup consumerGroup : response.GetConsumerGroups()){
System.out.println("ConsumerName is : " + consumerGroup.getConsumerGroupName());
}
System.out.println(String.format("list consumergroup from %s success",projectName));
} 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;
}
}
}
Resultado esperado:
ready to list consumergroup
ConsumerName is : ali-test-consumergroup2
ConsumerName is : ali-test-consumergroup
list consumergroup from ali-test-project success
Eliminar un grupo de consumidores
A continuación se muestra el código para eliminar un grupo de consumidores específico.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.exception.LogException;
public class DeleteConsumerGroup {
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 {
String consumerGroupName = "ali-test-consumergroup";
System.out.println("ready to delete consumergroup");
// Delete a specified consumer group.
client.DeleteConsumerGroup(projectName,logstoreName,consumerGroupName);
System.out.println(String.format("delete 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;
}
}
}
Resultado esperado:
ready to delete consumergroup
delete consumergroup ali-test-consumergroup success
Obtener el punto de control de un grupo de consumidores
A continuación se muestra el código para obtener el punto de control de un grupo de consumidores.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.GetCheckPointResponse;
public class GetCheckPoint {
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 {
String consumerGroupName = "consumerGroupX";
System.out.println("ready to get consumergroup checkpoint");
// Obtain the checkpoint of a shard in the specified consumer group.
GetCheckPointResponse response1 = client.getCheckpoint(projectName,logstoreName,consumerGroupName,0);
GetCheckPointResponse response2 = client.getCheckpoint(projectName,logstoreName,consumerGroupName,1);
System.out.println("The checkpoint of Shard 0 is : " + response1.getCheckpoint());
System.out.println("The checkpoint of Shard 1 is : " + response2.getCheckpoint());
System.out.println(String.format("get consumergroup %s checkpoint 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;
}
}
}
Resultado esperado:
ready to get consumergroup checkpoint
The checkpoint of Shard 0 is : ConsumerGroupShardCheckPoint [shard=0, checkPoint=MTY2NzgxMDc0Nzk5MDk5MzAyMg==, updateTime=1668750821709044, consumer=consumer_1]
The checkpoint of Shard 1 is : ConsumerGroupShardCheckPoint [shard=1, checkPoint=MTY2NzgxMDc0Nzk5MTk0NTU0NQ==, updateTime=1668750828790425, consumer=consumer_1]
get consumergroup consumerGroupX checkpoint success
Actualizar el punto de control de un grupo de consumidores
A continuación se muestra el código para actualizar el punto de control de un grupo de consumidores.
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.ConsumerGroup;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.ListConsumerGroupResponse;
public class ConsumerGroupUpdateCheckpoint {
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 {
String consumerGroupName = "consumerGroupX";
System.out.println("ready to update checkpoint");
// Query all consumer groups in the specified Logstore.
ListConsumerGroupResponse response = client.ListConsumerGroup(projectName, logstoreName);
for(ConsumerGroup consumerGroup : response.GetConsumerGroups()){
System.out.println("ConsumerName is : " + consumerGroup.getConsumerGroupName());
System.out.println("Consumer order is : " + consumerGroup.isInOrder());
}
// Update the checkpoint of Shard 0. You can call the GetCursor operation to obtain the cursor for a specific time.
client.UpdateCheckPoint(projectName, logstoreName, consumerGroupName, 0, "MTY2NzgxMDc0Nzk5MTAwNjQ3Mg==");
System.out.println(String.format("update checkpoint of %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;
}
}
}
Resultado esperado:
ready to update checkpoint
ConsumerName is : consumerGroupX
Consumer order is : false
ConsumerName is : ali-test-consumergroup2
Consumer order is : true
ConsumerName is : ali-test-consumergroup
Consumer order is : false
update consumergroup checkpoint is:consumerGroupX
update checkpoint of consumerGroupX success
Referencias
Además de su SDK nativo, SLS también es compatible con los SDK comunes de Alibaba Cloud. Para obtener más información, consulte Simple Log Service_SDK Center_Alibaba Cloud OpenAPI Explorer.
-
Operaciones de API relacionadas:
SDK de Java para Alibaba Cloud Simple Log Service en GitHub.