Esta guía explica cómo utilizar el SDK de Java para invocar servicios de modelos de Elastic Algorithm Service (EAS), y proporciona ejemplos de entrada y salida, así como un programa de muestra.
Para conocer los casos de uso y los principios del SDK, consulte service invocation SDK.
Requisitos previos
Para usar el SDK de Java de EAS en su proyecto Maven, agregue la dependencia eas-sdk en la sección <dependencies> de su archivo pom.xml. Para obtener la versión más reciente, consulte el repositorio de Maven.
<dependency>
<groupId>com.aliyun.openservices.eas</groupId>
<artifactId>eas-sdk</artifactId>
<version>2.0.20</version>
</dependency>
El SDK de EAS versión 2.0.5 y posteriores incluye la funcionalidad de cliente QueueService para el servicio de cola asíncrona con prioridades múltiples. Para utilizar esta función y evitar conflictos de dependencias, agregue las dos dependencias siguientes y ajuste sus versiones según sea necesario:
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
Inicio rápido
Para realizar una llamada de servicio con el SDK de Java, siga estos tres pasos:
Obtenga la información de llamada: En la página de detalles del servicio dentro de la consola de EAS, vaya a la pestaña Call Information para obtener el endpoint, el nombre del servicio y el token.
-
Elija un tipo de solicitud y escriba el código: Seleccione la clase Request/Response adecuada según el formato de datos de entrada de su modelo y, a continuación, escriba su código con base en el ejemplo mínimo que se presenta a continuación.
NotaSi desplegó su servicio con un Processor integrado, el SDK proporciona las clases de entrada y salida correspondientes. Por ejemplo, al TensorFlow Processor integrado le corresponde
TFRequest. Para más información, consulte la documentación de cada processor en Built-in Processors. Ejecute y compruebe: Ejecute el programa cliente y compruebe la respuesta. Si ocurre un error, consulte la guía Troubleshooting.
El siguiente código es un ejemplo integral mínimo de una solicitud de cadena. Para ver más ejemplos, consulte Program Examples:
import com.aliyun.openservices.eas.predict.http.PredictClient;
import com.aliyun.openservices.eas.predict.http.HttpConfig;
public class TestString {
public static void main(String[] args) throws Exception {
PredictClient client = new PredictClient(new HttpConfig());
// To use a VPC direct connection, call the setDirectEndpoint method. The format is typically {uid}.vpc.{region-id}.pai-eas.aliyuncs.com.
client.setDirectEndpoint("182848887922****.vpc.cn-shanghai.aliyuncs.com");
// The public endpoint for the EAS service. The format is typically {uid}.{region-id}.pai-eas.aliyuncs.com.
// client.setEndpoint("182848887922****.cn-shanghai.pai-eas.aliyuncs.com");
// The name of the EAS service.
client.setModelName("your_service_name");
client.setToken("YOUR_SERVICE_TOKEN");
// The request path. The complete request URL is http://<endpoint>/api/direct/<modelName>/<requestPath>.
client.setRequestPath("your_custom_path");
// Construct the request body. The supported input classes depend on the SDK. This example uses a String.
String request = "[{}]";
String response = client.predict(request);
System.out.println(response);
client.shutdown();
}
}
Referencia de la API
El SDK de Java proporciona las siguientes clases:
|
Grupo |
Descripción de la clase |
|
Clase cliente principal |
|
|
Configuración de conexión |
|
|
Entrada/salida |
|
|
Servicio de cola |
|
Clase PredictClient
Clase cliente principal. Configura la información del servicio, envía solicitudes y recibe resultados de predicción.
|
API |
Descripción |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Establece una URL de solicitud personalizada. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Clase HttpConfig
Configura los parámetros subyacentes de conexión HTTP, como los tiempos de espera, el recuento de hilos y el pool de conexiones.
|
API |
Descripción |
|
|
|
|
|
Importante
Este tiempo de espera aplica únicamente después de establecer la conexión. Es diferente del tiempo de espera de solicitud configurado mediante el método |
|
|
Importante
Este tiempo de espera abarca todo el ciclo de vida de la solicitud, incluido el establecimiento de la conexión, la transferencia de datos y el procesamiento en el servidor. Es diferente del tiempo de espera de lectura configurado mediante el método |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Devuelve el código de estado de la última llamada a la API. |
|
|
Devuelve el mensaje de estado de la última llamada a la API. |
Clase TFRequest
Construye los datos de entrada para un modelo de TensorFlow.
|
API |
Descripción |
|
|
|
|
|
|
|
|
|
Clase TFResponse
Analiza y accede a los datos de salida de una predicción de modelo de TensorFlow.
|
API |
Descripción |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Clase QueueClient
Interactúa con el servicio de cola de EAS para producir, consumir y gestionar datos.
|
API |
Descripción |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Importante
Al llamar a
|
|
|
|
|
|
|
|
|
Cierra la conexión con el servicio de cola. |
Clase DataFrame
Contenedor para un elemento de datos del servicio de cola.
|
API |
Descripción |
|
|
|
|
|
|
|
|
|
Ejemplos de código
Ejemplos de inference síncrona
Elija el ejemplo que coincida con el formato de entrada y salida de su servicio.
String
Si desplegó un servicio con un procesador personalizado, normalmente se usan cadenas de texto para invocarlo. Esta práctica es común en servicios de modelos PMML, como se muestra en el siguiente ejemplo.
import com.aliyun.openservices.eas.predict.http.PredictClient;
import com.aliyun.openservices.eas.predict.http.HttpConfig;
public class TestString {
public static void main(String[] args) throws Exception {
// Initialize the client. The client object should be shared. Do not create a new client object for each request.
PredictClient client = new PredictClient(new HttpConfig());
client.setToken("YWFlMDYyZDNmNTc3M2I3MzMwYmY0MmYwM2Y2MTYxMTY4NzBkNzdj****");
// To use a direct network connection, call the setDirectEndpoint method.
// Example: client.setDirectEndpoint("182848887922****.vpc.cn-shanghai.aliyuncs.com");
// To enable a direct network connection, you must enable it in the EAS console and provide the source vSwitch used to access the EAS service. This bypasses the gateway, allowing you to directly access service instances via software load balancing for improved stability and performance.
// Note: For standard gateway access, use the endpoint that starts with your user ID. You can find this endpoint in the "Call Information" of the service in the EAS console. For direct network connections, use a domain name in the format 182848887922****.vpc.{region_id}.aliyuncs.com.
client.setEndpoint("182848887922****.vpc.cn-shanghai.pai-eas.aliyuncs.com");
client.setModelName("scorecard_pmml_example");
// Define the input string.
String request = "[{\"money_credit\": 3000000}, {\"money_credit\": 10000}]";
System.out.println(request);
// Get the response string from EAS.
try {
String response = client.predict(request);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
// Shut down the client.
client.shutdown();
return;
}
}
TensorFlow
Si utiliza un modelo de TensorFlow, emplee las clases TFRequest y TFResponse para la entrada y la salida, tal como se demuestra en el siguiente ejemplo.
import java.util.List;
import com.aliyun.openservices.eas.predict.http.PredictClient;
import com.aliyun.openservices.eas.predict.http.HttpConfig;
import com.aliyun.openservices.eas.predict.request.TFDataType;
import com.aliyun.openservices.eas.predict.request.TFRequest;
import com.aliyun.openservices.eas.predict.response.TFResponse;
public class TestTF {
public static TFRequest buildPredictRequest() {
TFRequest request = new TFRequest();
request.setSignatureName("predict_images");
float[] content = new float[784];
for (int i = 0; i < content.length; i++) {
content[i] = (float) 0.0;
}
request.addFeed("images", TFDataType.DT_FLOAT, new long[]{1, 784}, content);
request.addFetch("scores");
return request;
}
public static void main(String[] args) throws Exception {
PredictClient client = new PredictClient(new HttpConfig());
// To use a direct network connection, call the setDirectEndpoint method. The endpoint format is {uid}.vpc.{region_id}.aliyuncs.com.
// client.setDirectEndpoint("182848887922****.vpc.cn-shanghai.aliyuncs.com");
// For standard gateway access, use the endpoint that starts with your user ID. You can find this endpoint in the "Call Information" of the service in the EAS console.
client.setEndpoint("182848887922****.vpc.cn-shanghai.pai-eas.aliyuncs.com");
client.setModelName("mnist_saved_model_example");
client.setToken("YTg2ZjE0ZjM4ZmE3OTc0NzYxZDMyNmYzMTJjZTQ1YmU0N2FjMTAy****");
long startTime = System.currentTimeMillis();
int count = 1000;
for (int i = 0; i < count; i++) {
try {
TFResponse response = client.predict(buildPredictRequest());
List<Float> result = response.getFloatVals("scores");
System.out.print("Predict Result: [");
for (int j = 0; j < result.size(); j++) {
System.out.print(result.get(j).floatValue());
if (j != result.size() - 1) {
System.out.print(", ");
}
}
System.out.print("]\n");
} catch (Exception e) {
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
System.out.println("Spend Time: " + (endTime - startTime) + "ms");
client.shutdown();
}
}
Ejemplo de servicio de cola
Para acceder al servicio de cola, utilice la interfaz QueueClient. A continuación se muestra cómo hacerlo.
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.eas.predict.http.HttpConfig;
import com.aliyun.openservices.eas.predict.http.QueueClient;
import com.aliyun.openservices.eas.predict.queue_client.QueueUser;
import com.aliyun.openservices.eas.predict.queue_client.WebSocketWatcher;
public class DemoWatch {
public static void main(String[] args) throws Exception {
/** Create a queue service client. */
String queueEndpoint = "18*******.cn-hangzhou.pai-eas.aliyuncs.com";
String inputQueueName = "test_queue_service";
String sinkQueueName = "test_queue_service/sink";
String queueToken = "test-token";
/** The input queue. The inference service automatically reads request data from this queue. */
QueueClient inputQueue =
new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), new QueueUser());
/** The output queue. After the inference service processes the input data, it writes the results to this queue. */
QueueClient sinkQueue =
new QueueClient(queueEndpoint, sinkQueueName, queueToken, new HttpConfig(), new QueueUser());
/** Clear queue data. Use with caution. */
inputQueue.clear();
sinkQueue.clear();
/** Add data to the input queue. */
int count = 10;
for (int i = 0; i < count; ++i) {
String data = Integer.toString(i);
inputQueue.put(data.getBytes(), null);
/** The queue service supports multiple priorities. You can use the put method to set the data priority. The default priority is 0. */
// inputQueue.put(data.getBytes(), 0L, null);
}
/** Use the watch method to subscribe to data from the output queue. The window size is 5. */
WebSocketWatcher watcher = sinkQueue.watch(0L, 5L, false, true, null);
/** Use the WatchConfig parameter to customize the number of retries, retry interval (in seconds), and whether to retry indefinitely. If you do not configure WatchConfig, the system defaults to 3 retries with a 5-second interval. */
// WebSocketWatcher watcher = sink_queue.watch(0L, 5L, false, true, null, new WatchConfig(3, 1));
// WebSocketWatcher watcher = sink_queue.watch(0L, 5L, false, true, null, new WatchConfig(true, 10));
/** Get the output data. */
for (int i = 0; i < count; ++i) {
try {
/** The getDataFrame() method retrieves DataFrame data. This call blocks until data is available. */
byte[] data = watcher.getDataFrame().getData();
System.out.println("[watch] data = " + new String(data));
} catch (RuntimeException ex) {
System.out.println("[watch] error = " + ex.getMessage());
break;
}
}
/** Close the watcher object. Each client instance supports only one watcher object. If you do not close the watcher, an error occurs on the next run. */
watcher.close();
Thread.sleep(2000);
JSONObject attrs = sinkQueue.attributes();
System.out.println(attrs.toString());
/** Shut down the clients. */
inputQueue.shutdown();
sinkQueue.shutdown();
}
}
La invocación de un servicio mediante el SDK de Java implica los siguientes pasos:
Utilice la interfaz
QueueClientpara crear un objeto cliente del servicio de cola. Si crea un servicio de inference, también debe crear objetos de cola de entrada y de salida.-
Use la función
put()para enviar datos a la cola de entrada y la funciónwatch()para suscribirse a los datos de la cola de salida.NotaEn un entorno de producción, se recomienda usar hilos separados para el envío y la suscripción de datos. Con fines demostrativos, este ejemplo realiza ambas operaciones en el mismo hilo.
Compresión de datos de solicitud
Para solicitudes que contienen una gran cantidad de datos, EAS admite la compresión mediante los formatos Zlib o Gzip antes de enviarlos al servidor. Para habilitar esta función, debe especificar rpc.decompressor en la configuración del servicio.
La configuración del servicio es la siguiente:
"metadata": {
"rpc": {
"decompressor": "zlib"
}
}
A continuación se presenta un ejemplo de código:
package com.aliyun.openservices.eas.predict;
import com.aliyun.openservices.eas.predict.http.Compressor;
import com.aliyun.openservices.eas.predict.http.PredictClient;
import com.aliyun.openservices.eas.predict.http.HttpConfig;
public class TestString {
public static void main(String[] args) throws Exception{
// Initialize the client.
PredictClient client = new PredictClient(new HttpConfig());
client.setEndpoint("18*******.cn-hangzhou.pai-eas.aliyuncs.com");
client.setModelName("echo_compress");
client.setToken("YzZjZjQwN2E4NGRkMDMxNDk5NzhhZDcwZDBjOTZjOGYwZDYxZGM2****");
// You can also use Compressor.Gzip.
client.setCompressor(Compressor.Zlib);
// Define the input string.
String request = "[{\"money_credit\": 3000000}, {\"money_credit\": 10000}]";
System.out.println(request);
// Get the response string from EAS.
String response = client.predict(request);
System.out.println(response);
// Shut down the client.
client.shutdown();
return;
}
}
Solución de problemas
Para resolver problemas relacionados con excepciones de invocación del SDK de Java, incluidos inconvenientes comunes de autenticación, enrutamiento, conexión y errores del servidor, consulte la sección "Solución de problemas de excepciones de invocación" en Service Invocation SDK.
Para obtener una lista completa de los códigos de estado del servicio, el significado de los mensajes de error y las acciones recomendadas, consulte Appendix: Service Status Codes and Common Errors.