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 Simple Log Service para Python está inicializado.
El SDK de Simple Log Service para Python ya está instalado. Para obtener más información, consulte Install Simple Log Service SDK for Python.
Se crearon un proyecto y un logstore en Simple Log Service, y los registros ya se recopilan. Para obtener más información, consulte Manage projects, Create a basic LogStore y Data collection.
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 conocer las regiones y los endpoints compatibles con Simple Log Service, consulte Endpoint.
Código de ejemplo para crear un grupo de consumidores
A continuación se muestra un ejemplo de cómo crear un grupo de consumidores llamado ali-test-consumergroup:
from aliyun.log import LogClient
import os
# This example obtains the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace it with the actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
# The consumer group name.
consumergroup_name = "ali-test-consumergroup"
if __name__ == '__main__':
print("ready to create consumergroup")
res = client.create_consumer_group(project_name, logstore_name, consumergroup_name, 300, in_order=False)
print("create consumergroup success ")
res2 = client.list_consumer_group(project_name, logstore_name)
for r in res2.get_consumer_groups():
print("The consumergroup name is:" + r.get_consumer_group_name())
Resultados esperados:
ready to create consumergroup
create consumergroup success
The consumergroup name is:ali-test-consumergroup
Código de ejemplo para modificar un grupo de consumidores
A continuación se muestra un ejemplo de cómo modificar el grupo de consumidores ali-test-consumergroup:
from aliyun.log import LogClient
import os
# This example obtains the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace it with the actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
# The consumer group name.
consumergroup_name = "ali-test-consumergroup"
if __name__ == '__main__':
print("ready to update consumergroup")
# Change the timeout period of the consumer group to 350 seconds.
res = client.update_consumer_group(project_name, logstore_name, consumergroup_name, 350, in_order=False)
print("update consumergroup success ")
res2 = client.list_consumer_group(project_name, logstore_name)
for r in res2.get_consumer_groups():
print("The consumergroup name is:" + r.get_consumer_group_name())
print("The consumergroup timeout is:%s" % r.get_timeout())
Resultados esperados:
ready to update consumergroup
update consumergroup success
The consumergroup name is:ali-test-consumergroup
The consumergroup timeout is:350
Código de ejemplo para consultar todos los grupos de consumidores
El siguiente código muestra cómo consultar todos los grupos de consumidores de un logstore específico.
from aliyun.log import LogClient
import os
# This example obtains the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace it with the actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
if __name__ == '__main__':
print("ready to list consumergroup")
# Query all consumer groups in the specified Logstore.
res = client.list_consumer_group(project_name, logstore_name)
for r in res.get_consumer_groups():
print("The consumergroup name is:" + r.get_consumer_group_name())
print("The consumergroup timeout is:%s" % r.get_timeout())
print("The consumergroup order is:%s" % r.is_in_order())
print("list consumergroup success ")
Resultados esperados:
ready to list consumergroup
The consumergroup name is:ali-test-consumergroup
The consumergroup timeout is:350
The consumergroup order is:False
list consumergroup success
Código de ejemplo para eliminar un grupo de consumidores
A continuación se muestra un ejemplo de cómo eliminar un grupo de consumidores dentro de un proyecto determinado:
from aliyun.log import LogClient
import os
# This example obtains the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace it with the actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
# The consumer group name.
consumergroup_name = "ali-test-consumergroup2"
if __name__ == '__main__':
print("ready to delete consumergroup")
# Delete the specified consumer group.
res = client.delete_consumer_group(project_name, logstore_name, consumergroup_name)
print("delete consumergroup success ")
Resultados esperados:
ready to delete consumergroup
delete consumergroup success
Código de ejemplo para obtener el punto de control de un grupo de consumidores
A continuación se muestra un ejemplo de cómo obtener el punto de control de un grupo de consumidores específico:
from aliyun.log import LogClient, ListConsumerGroupResponse
import os
# This example obtains the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace it with the actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
# The consumer group name.
consumergroup_name = "ali-test-consumergroup"
if __name__ == '__main__':
print("ready to get CheckPoint")
# Get the checkpoint of a shard in the specified consumer group.
res = client.get_check_point(project_name, logstore_name, consumergroup_name, shard=0)
print("The consumergroup checkpoints info is:%s" % res.get_consumer_group_check_points())
print("list CheckPoint success in shard_0")
Resultados esperados:
ready to get CheckPoint
The consumergroup checkpoints info is:[{'shard': 0, 'checkpoint': 'MTY3MDk5OTY3NzEzMzQzODg2NQ==', 'updateTime': 1671607210514072, 'consumer': 'consumer_1'}]
list CheckPoint success in shard_0
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, Simple Log Service_SDK Center_Alibaba Cloud OpenAPI Explorer.
-
Operaciones de API relacionadas:
SDK de Alibaba Cloud Simple Log Service para Python en GitHub.