All Products
Search
Document Center

Platform For AI:Java SDK

Last Updated:May 30, 2026

This guide explains how to use the Java SDK to call Elastic Algorithm Service (EAS) model services, and provides input/output examples and a sample program.

Note

For the use cases and principles of the SDK, see service invocation SDK.

Prerequisites

To use the EAS Java SDK in your Maven project, add the eas-sdk dependency to the <dependencies> section of your pom.xml file. For the latest version, check the Maven repository.

<dependency>
  <groupId>com.aliyun.openservices.eas</groupId>
  <artifactId>eas-sdk</artifactId>
  <version>2.0.20</version>
</dependency>

EAS SDK 2.0.5 and later includes QueueService client functionality for the multi-priority asynchronous queue service. To use this feature and avoid dependency conflicts, add the following two dependencies and adjust their versions as necessary:

<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>

Quick start

To make a service call with the Java SDK, follow these three steps:

  1. Get call information: On the service details page in the EAS console, go to the Call Information tab to get the endpoint, service name, and token.

  2. Choose a request type and write code: Select the appropriate Request/Response class based on your model's input data format, and then write your code using the minimal example below.

    Note

    If you deployed your service with a built-in Processor, the SDK provides corresponding input and output classes. For example, the built-in TensorFlow Processor corresponds to TFRequest. For more information, see the documentation for each processor under Built-in Processors.

  3. Run and verify: Run the client program and verify the response. If an error occurs, refer to the Troubleshooting guide.

The following code is a minimal end-to-end example of a string request. For more examples, see 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();
    }
}

API reference

The Java SDK provides the following classes:

Group

Class description

Main Client Class

PredictClient: The main class for configuring service details like the endpoint and token, sending requests, and receiving responses.

Connection configuration

HttpConfig: Configures HTTP connection parameters, such as timeouts and the maximum number of connections.

Input/output

  • TFRequest: Encapsulates a request for a TensorFlow model.

  • TFResponse: Parses the response from a TensorFlow model.

  • For string-based scenarios, dedicated request or response classes are unnecessary. You can pass and receive data directly as String objects.

  • For details on other supported types, refer to the SDK.

Queue service

  • QueueClient: An asynchronous queue client for sending and subscribing to data. This class requires additional dependencies, as described in Prerequisites.

  • DataFrame: An object that encapsulates a data item from the queue service.

PredictClient class

The main client class. It configures service information, sends requests, and receives prediction results.

API

Description

PredictClient(HttpConfig httpConfig)

  • Constructs a PredictClient instance.

  • Parameter: httpConfig is an instance of the HttpConfig class.

void setToken(String token)

  • Sets the authentication token for HTTP requests.

  • Parameter: token is the authentication token for service access.

void setModelName(String modelName)

  • Sets the model name for the online prediction service.

  • Parameter: modelName is the name of the model to use.

void setEndpoint(String endpoint)

  • Function: Specifies the host and port of the requested service. The format is "host:port".

  • Parameter: endpoint is the service endpoint address in "host:port" format.

void setDirectEndpoint(String endpoint)

  • Sets the endpoint for accessing the service via a VPC direct connection.

  • Parameter: endpoint is the service endpoint address.

void setRequestPath(String requestPath)

  • Sets the request path as defined in the server-side code.

  • Parameter: requestPath is the server-side request path. Example: client.setRequestPath("/custom_path").

void setRetryCount(int retryCount)

  • Sets the retry count for failed requests.

  • Parameter: retryCount is the retry count.

void setRetryConditions(EnumSet retryConditions)

  • Sets the conditions for retrying a request. You can use this method with the setRetryCount method. By default, all request errors are retried. This method allows you to specify that only specific request errors are retried.

  • Parameter: retryConditions is an EnumSet containing one or more retry conditions. Supported conditions include:

    • RetryCondition.CONNECTION_FAILED: The request connection failed.

    • RetryCondition.CONNECTION_TIMEOUT: The request connection timed out.

    • RetryCondition.READ_TIMEOUT: The request timed out while waiting for a response.

    • RetryCondition.RESPONSE_5XX: The server returned a 5xx status code.

    • RetryCondition.RESPONSE_4XX: The server returned a 4xx status code.

  • Example:

    client.setRetryConditions(
        EnumSet.of(
            RetryCondition.READ_TIMEOUT,    // Retry on read timeout
            RetryCondition.RESPONSE_5XX     // Retry on 5xx error codes
        )
    );

    This example specifies that a request is retried only if it times out or if the server returns a 5xx status code.

void setContentType(String contentType)

  • Sets the Content-Type for the HTTP request. The default is "application/octet-stream".

  • Parameter: contentType is the content type of the data stream being sent.

void setUrl(String url)

Sets a custom request URL.

void setCompressor(Compressor compressor)

  • Sets the compression method for the request data.

  • Parameter: compressor is the compression method. Supported values are Compressor.Gzip and Compressor.Zlib.

  • For more information, see Request Data Compression Example.

void addExtraHeaders(Map<String, String> extraHeaders)

  • Adds custom HTTP headers to the request.

  • Parameter: extraHeaders is a Map<String, String> of HTTP headers to add.

void createChildClient(String token, String endpoint, String modelName)

  • Creates a child client that shares the thread pool of the parent client. This is useful for multi-threaded predictions.

  • Parameters:

    • token: The authentication token for the service.

    • endpoint: The endpoint of the service.

    • modelName: The name of the model.

void predict(TFRequest runRequest)

  • Sends a TensorFlow request to the online prediction service.

  • Parameter: runRequest is an instance of a TFRequest object.

void predict(String requestContent)

  • Sends a string-based request to the online prediction service.

  • Parameter: requestContent is the content of the request as a string.

void predict(byte[] requestContent)

  • Sends a byte array request to the online prediction service.

  • Parameter: requestContent is the content of the request as a byte array.

HttpConfig class

Configures underlying HTTP connection parameters, such as timeouts, thread count, and the connection pool.

API

Description

void setIoThreadNum(int ioThreadNum)

  • Sets the number of I/O threads for HTTP requests. The default is 2.

  • Parameter: ioThreadNum is the number of I/O threads.

void setReadTimeout(int readTimeout)

  • The maximum time to wait for a data packet from the server after a connection is established. The default value is 5000 (5 seconds).

  • Parameter: readTimeout is the read timeout in milliseconds.

Important

This timeout applies only after a connection is established. It is different from the request timeout set by the setRequestTimeout method.

void setRequestTimeout(int requestTimeout)

  • The total time allowed for a request, from sending to receiving the full response. The default value is 5000 (5 seconds).

  • Parameter: requestTimeout is the request timeout in milliseconds.

Important

This timeout covers the entire request lifecycle, including connection establishment, data transfer, and server processing. It is different from the read timeout set by the setReadTimeout method.

void setConnectTimeout(int connectTimeout)

  • The maximum time to wait when establishing a connection. The default value is 5000 (5 seconds).

  • Parameter: connectTimeout is the connection timeout in milliseconds.

void setMaxConnectionCount(int maxConnectionCount)

  • Sets the maximum total number of connections in the connection pool. The default is 1000.

  • Parameter: maxConnectionCount is the maximum number of connections.

void setMaxConnectionPerRoute(int maxConnectionPerRoute)

  • Sets the maximum number of connections per route. The default is 1000.

  • Parameter: maxConnectionPerRoute is the maximum number of connections for each route.

void setKeepAlive(boolean keepAlive)

  • Function: Configures the keep-alive for the HTTP service.

  • Parameter: keepAlive. Specifies whether to enable the keep-alive mechanism for the connection. The default value is true.

int getErrorCode()

Returns the status code of the last API call.

String getErrorMessage()

Returns the status message of the last API call.

TFRequest class

Builds the input data for a TensorFlow model.

API

Description

void setSignatureName(String value)

  • Function: Specifies the name of the signatureDef for the requested model when the model is in the TensorFlow SavedModel format.

  • Parameter: The name of the signatureDef for the request model.

void addFetch(String value)

  • Specifies an output tensor to fetch from the model.

  • Parameter: value is the alias of the output tensor to fetch.

void addFeed(String inputName, TFDataType dataType, long[]shape, ?[]content)

  • Adds an input tensor to the request.

  • Parameters:

    • inputName: The alias of the input tensor.

    • dataType: The data type of the input tensor.

    • shape: The shape of the input tensor.

    • content: The tensor content, provided as a flattened one-dimensional array. The element type in the array depends on the dataType:

      If the DataType of the input Tensor is DT_FLOAT, DT_COMPLEX64, DT_BFLOAT16, or DT_HALF, the element type in content is FLOAT. When the DataType is DT_COMPLEX64, two adjacent FLOAT elements in content represent the real and imaginary parts of a complex number, respectively.

      If the DataType of the input Tensor is DT_DOUBLE or DT_COMPLEX128, the elements in content are of the DOUBLE type. When the DataType is DT_COMPLEX128, two adjacent DOUBLE elements in content represent the real and imaginary parts of a complex number, respectively.

      If the DataType of the input Tensor is DT_INT32, DT_UINT8, DT_INT16, DT_INT8, DT_QINT8, DT_QUINT8, DT_QINT32, DT_QINT16, DT_QUINT16, or DT_UINT16, the element type in content is INT.

      If the DataType of the input Tensor is DT_INT64, the element type in content is LONG.

      If the DataType of the input Tensor is DT_STRING, the element type in content is STRING.

      If the DataType of the input Tensor is DT_BOOL, the element type in content is BOOLEAN.

TFResponse class

Parses and accesses the output data from a TensorFlow model prediction.

API

Description

List<Long> getTensorShape(String outputName)

  • Gets the shape of a specified output tensor.

  • Parameter: outputName is the alias of the output tensor.

  • Returns: A list of longs representing the tensor's shape.

List<Float> getFloatVals(String outputName)

  • Function: If the DataType of the output Tensor is DT_FLOAT, DT_COMPLEX64, DT_BFLOAT16, or DT_HALF, you can call this interface to retrieve the data of the specified output Tensor.

  • Parameter: outputName is the alias of the output tensor.

  • Return value: A one-dimensional array flattened from the TensorData output of the model.

List<Double> getDoubleVals(String outputName)

  • Function: Obtains the data of the specified output Tensor if the DataType of the output Tensor is DT_DOUBLE or DT_COMPLEX128.

  • Parameter: outputName is the alias of the output tensor.

  • Return value: A one-dimensional array that is the result of flattening the TensorData output from the model.

List<Integer> getIntVals(String outputName)

  • Function: Obtains the data of the specified output Tensor if its DataType is DT_INT32, DT_UINT8, DT_INT16, DT_INT8, DT_QINT8, DT_QUINT8, DT_QINT32, DT_QINT16, DT_QUINT16, or DT_UINT16.

  • Parameter: outputName is the alias of the output tensor.

  • Return value: The TensorData output by the model, flattened into a one-dimensional array.

List<String> getStringVals(String outputName)

  • Function: If the DataType of an output Tensor is DT_STRING, you can call this interface to obtain the data of that Tensor.

  • Parameter: outputName is the alias of the output tensor.

  • Return value: A one-dimensional array created by flattening the TensorData output from the model.

List<Long> getInt64Vals(String outputName)

  • Function: If the DataType of the output Tensor is DT_INT64, you can call this interface to obtain the data of the specified output Tensor.

  • Parameter: outputName is the alias of the output tensor.

  • Return value: A one-dimensional array obtained by flattening the TensorData output from the model.

List<Boolean> getBoolVals(String outputName)

  • Function: Retrieves the data of the specified output Tensor if its DataType is DT_BOOL.

  • Parameter: outputName is the alias of the output tensor.

  • Return value: The one-dimensional array resulting from flattening the TensorData output from the model.

QueueClient class

Interacts with the EAS queue service to produce, consume, and manage data.

API

Description

QueueClient(String endpoint, String queueName, String token, HttpConfig httpConfig, QueueUser user)

  • Constructs a QueueClient instance.

  • Parameters:

    • endpoint: The endpoint address of the queue service.

    • queueName: The name of the queue service.

    • token: The token for service access.

    • httpConfig: The HTTP request configuration.

    • user: The user configuration. Specifies UserId (a random UUID by default) and GroupName (eas by default).

JSONObject attributes()

  • Gets detailed attributes of the queue service.

  • Returns: A JSONObject with queue information, including the following fields:

    • meta.maxPayloadBytes: The maximum allowed size (in bytes) for a single data item.

    • meta.name: The queue name.

    • stream.approxMaxLength: The approximate maximum number of items the queue can store.

    • stream.firstEntry: The index of the first item in the queue.

    • stream.lastEntry: The index of the last item in the queue.

    • stream.length: The current number of items in the queue.

Pair<Long, String> put(byte[] data, long priority, Map<String, String> tags)

  • Writes a data item to the queue.

  • Parameters:

    • data: The data to write, as a byte array.

    • priority: The data priority. 1 for high priority, 0 for normal priority (default).

    • tags: A map of custom key-value tags.

  • Returns: A Pair<Long, String> containing the index of the new data item and the request ID.

DataFrame[] get(long index, long length, long timeout, boolean autoDelete, Map<String, String> tags)

  • Retrieves data items from the queue.

  • Parameters:

    • index: The starting index from which to retrieve data. Use -1 to read the latest data.

    • length: The number of data items to retrieve.

    • timeout: The timeout period in seconds.

    • autoDelete: If true, the data is automatically deleted from the queue after being retrieved.

    • tags: A map of custom key-value tags, such as a RequestID.

  • Returns: An array of DataFrame objects.

void truncate(Long index)

  • Deletes all data items in the queue with an index less than the specified index.

String delete(Long index)

  • Deletes a specific data item from the queue.

  • Parameter: index is the index of the data item to delete.

  • Returns: "OK" on successful deletion.

JSONObject search(long index)

  • Queries the status of a specific data item in the queue.

  • Parameter: index is the index of the data item to query.

  • Returns: A JSONObject with queuing information, including:

    • ConsumerId: The ID of the instance processing the item.

    • IsPending: true if the item is being processed; false if it is waiting in the queue.

      • True means it is being processed.

      • False means it is queued.

    • WaitCount: The number of items ahead in the queue. This is valid only if IsPending is false. If IsPending is true, this value is 0.

    Example Responses:

    • The service returns {'ConsumerId': 'eas.****', 'IsPending': False, 'WaitCount':2}, which indicates that the request is being queued.

    • The log shows no data in stream and returns {}. This indicates that the data was not found in the queue. This may be because the data has been successfully processed by the server-side and a result has been returned, or the index parameter is incorrectly configured. Please check and confirm.

Important

When calling search, you must set the group ID in the QueueUser object to the service name. Otherwise, IsPending in the search result is always false.

  • Set group ID to the service name:

    QueueUser u = new QueueUser(UUID.randomUUID().toString(), "<service_name>");
    QueueClient input_queue = new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), u);
  • Query the status for the specified index:

    System.out.println(input_queue.search(index));

WebSocketWatcher watch(long index, long window, boolean indexOnly, boolean autoCommit, Map<String, String> tags)

  • Subscribes to the queue service to receive data items as they become available.

  • Parameters:

    • index: The starting index. Use -1 to ignore all pending data and start with the newest items.

    • window: The size of the sending window (the maximum number of uncommitted items). The service will pause sending if the number of uncommitted items reaches this window size.

    • indexOnly: If true, returned DataFrame objects contain only the index and tags, not the data payload, to save bandwidth.

    • autoCommit: If true, items are automatically committed upon receipt, and the commit() call is not needed. When autoCommit is set to true, the window parameter is ignored.

    • tags: A map of custom parameters for the subscription request.

  • Returns: A WebSocketWatcher object for receiving the subscribed data. See the queue service example for usage details.

String commit(Long index) orString commit(Long[] index)

  • Confirms that one or more data items have been consumed, which deletes them from the queue.

  • Returns: "OK" on successful commit.

void end(boolean force)

Closes the connection to the queue service.

DataFrame class

A wrapper for a data item from the queue service.

API

Description

byte[] getData()

  • Gets the data payload.

  • Returns: The data as a byte array.

long getIndex()

  • Gets the data item's index.

  • Returns: The data index as a long.

Map<String, String> getTags()

  • Gets the tags associated with the data item.

  • Return value: A Map<String,String> object named Tags, which can be used to obtain the RequestID. For example, df.getTags().get("requestId").

Code examples

Synchronous inference examples

Choose the example that matches the input and output format of your service.

String

If you deployed a service with a custom processor, you typically use strings to call it. This practice is common for PMML model services, as the following example shows.

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

If you use a TensorFlow model, use the TFRequest and TFResponse classes for input and output, as the following example demonstrates.

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();
    }
}

Queue service example

To access the queue service, use the QueueClient interface. The following example shows how.

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();
    }
}

Calling a service with the Java SDK involves the following steps:

  1. Use the QueueClient interface to create a queue service client object. If you create an inference service, you must also create input queue and output queue objects.

  2. Use the put() function to send data to the input queue, and use the watch() function to subscribe to data from the output queue.

    Note

    In a production environment, you should use separate threads for sending data and subscribing to data. For demonstration purposes, this example performs these operations in the same thread.

Request data compression

For requests that contain a large amount of data, EAS supports compressing the data by using the Zlib or Gzip format before sending it to the server-side. To enable this feature, you must specify rpc.decompressor in the service configuration.

The service configuration is as follows:

"metadata": {
  "rpc": {
    "decompressor": "zlib"
  }
}

The following is a code example:

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;
    }
}

Troubleshooting

To troubleshoot Java SDK invocation exceptions, including common issues with authentication, routing, connection, and server-side errors, see the "Troubleshooting Invocation Exceptions" section in Service Invocation SDK.

For a complete list of service status codes, error message meanings, and recommended actions, see Appendix: Service Status Codes and Common Errors.