Client es el cliente del SDK de Java para Simple Log Service. Proporciona métodos para crear proyectos y Logstores, así como para escribir y leer registros. Antes de enviar solicitudes mediante el SDK de Java, inicialice una instancia de Client y modifique las configuraciones predeterminadas según sea necesario.
Requisitos previos
Ha completado la Java SDK installation.
Procedimiento
Existen dos métodos de inicialización. Elija el que se ajuste a su escenario:
Inicialización con AK: Un par de AccessKey es una credencial de largo plazo que se usa directamente para llamadas a la API. Este método es adecuado para escenarios estables que no requieren rotación frecuente de credenciales.
Inicialización con STS: Security Token Service (STS) genera credenciales de acceso temporales. Esta opción está diseñada para escenarios que necesitan autorización dinámica y de corta duración.
Inicializar con un par de AccessKey
Inicializar el cliente
public Client(String endpoint, String accessKeyId, String accessKeySecret)
Parámetros de solicitud
|
Variable |
Tipo |
Obligatorio |
Descripción |
Valor de ejemplo |
|
endpoint |
String |
Sí |
El endpoint para acceder a Simple Log Service. Un endpoint es una URL que especifica el protocolo de acceso, el nombre de host, el puerto y la ruta para la comunicación entre el cliente y el servicio. Simple Log Service ofrece los siguientes tipos de endpoints:
|
|
|
accessKeyId |
String |
Sí |
|
LTAI |
|
accessKeySecret |
String |
Sí |
Si usa un par de AccessKey para configurar las credenciales de acceso, corresponde al AccessKey secret de una cuenta de Alibaba Cloud o de un usuario de RAM. El AccessKey secret autentica el AccessKey ID. Para más información, consulte Configure access credentials. |
yourAccessKeySecret |
Código de ejemplo
El algoritmo de firma V4 ofrece mayor seguridad mediante cifrado y firma más complejos. El algoritmo de firma V1 es más sencillo. Seleccione un algoritmo de firma según sus necesidades:
Firma V4
package com.test.controller;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.http.client.ClientConfiguration;
import com.aliyun.openservices.log.http.signer.SignVersion;
public class Sample {
public static void main(String[] args) throws Exception {
// The endpoint of Simple Log Service. This example uses the endpoint of the China (Beijing) region. Replace it with the actual endpoint.
String endpoint = "cn-beijing.log.aliyuncs.com";
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setRegion("cn-beijing");
clientConfiguration.setSignatureVersion(SignVersion.V4);
Client client = new Client(endpoint,
accessKeyId,
accessKeySecret,
clientConfiguration);
}
}
Firma V1
package com.test.controller;
import com.aliyun.openservices.log.Client;
public class Sample {
public static void main(String[] args) throws Exception {
// The endpoint of Simple Log Service. This example uses the endpoint of the China (Beijing) region. Replace it with the actual endpoint.
String endpoint = "cn-beijing.log.aliyuncs.com";
// This example obtains the AccessKey ID and AccessKey secret from environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
Client client = new Client(endpoint, accessKeyId, accessKeySecret);
}
}
Inicializar con STS
Inicializar el cliente
Client(String endpoint, CredentialsProvider credentialsProvider) ;
Parámetros de solicitud
|
Variable |
Tipo |
Obligatorio |
Descripción |
Ejemplo |
|
endpoint |
String |
Sí |
El endpoint para acceder a Simple Log Service. Un endpoint es una URL que especifica el protocolo de acceso, el nombre de host, el puerto y la ruta para la comunicación entre el cliente y el servicio. Simple Log Service ofrece los siguientes tipos de endpoints:
|
|
|
accessKeyId |
String |
Sí |
Si usa STS para configurar las credenciales de acceso, corresponde al AccessKeyId del parámetro Credentials devuelto por la operación de API AssumeRole. |
LTAI |
|
accessKeySecret |
String |
Sí |
Si usa STS para configurar las credenciales de acceso, corresponde al AccessKeySecret del parámetro Credentials devuelto por la operación de API AssumeRole. |
yourAccessKeySecret |
|
securityToken |
String |
Sí |
Si usa STS para configurar las credenciales de acceso, corresponde al SecurityToken del parámetro Credentials devuelto por la operación de API AssumeRole. |
|
Código de ejemplo
package com.test.controller;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.auth.DefaultCredentials;
import com.aliyun.openservices.log.common.auth.StaticCredentialsProvider;
public class Sample {
public static void main(String[] args) throws Exception {
// The endpoint of Simple Log Service. This example uses the endpoint of the China (Beijing) region. Replace it with the actual endpoint.
String endpoint = "cn-beijing.log.aliyuncs.com";
// This example obtains the AccessKeyId from the Credentials parameter returned by the AssumeRole operation from an environment variable.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
// This example obtains the AccessKeySecret from the Credentials parameter returned by the AssumeRole operation from an environment variable.
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// This example obtains the SecurityToken from the Credentials parameter returned by the AssumeRole operation from an environment variable.
String securityToken = System.getenv("ALIBABA_CLOUD_STS_TOKEN");
Client client = new Client(endpoint, new StaticCredentialsProvider(
new DefaultCredentials(accessKeyId, accessKeySecret, securityToken)
));
}
}
Referencias
Una vez inicializado el cliente, puede llamar a operaciones de la API para crear proyectos, escribir registros o realizar otras tareas. Para más información, consulte Quick Start for Java SDK.