Connect to an engine service with Go and Java SDKs

Updated at:

Use the Go or Java SDK to connect to an engine service deployed on Elastic Algorithm Service (EAS).

Prerequisites

A PAI-Rec engine service is deployed on EAS.

Obtain service information

Click View invocation information.

On the Overview tab, in the Basic Information section, find the invocation information field.

Obtain the invocation URL and token.

In the dialog box, the public gateway tab displays the public invocation URL, VPC invocation URL, and token. Each field has a copy button. You can switch to the VPC direct connection tab to view the corresponding information.

Connect by using the Go SDK

SDK repository: pai-eas/eas-golang-sdk

go get github.com/pai-eas/eas-golang-sdk

Public request

Replace the invocation URL and token with those of your engine service.

In eas.NewPredictClient, pass the invocation URL as the first parameter and the service name as the second.

Pass your token to SetToken.

Sample recommendation request

If you use a custom processor, call the PAI-Rec engine service by sending a string request. Example:

package main
import (
	"fmt"
	"github.com/pai-eas/eas-golang-sdk/eas"
)
func main() {
        // NewPredictClient(invocationURL, serviceName) Both parameters are required.
	client := eas.NewPredictClient("1730760139076263.cn-shanghai.pai-eas.aliyuncs.com", "lizhuo_prepub")
	// SetRequestPath(requestPath) Specify the path based on your requirements.
	client.SetRequestPath("/api/rec/feed")
	// SetToken(token) Specify the token.
	client.SetToken("**********************")
	err := client.Init()
	if err != nil {
		fmt.Println(err)
		return
	}
	// Specify the request parameters.
	req := "{\"scene_id\":\"home_feed\",\"size\":10,\"uid\":\"1234\"}"
	for i := 0; i < 10; i++ {
		resp, err := client.StringPredict(req)
		if err != nil {
			fmt.Printf("failed to predict: %v \n", err)
		} else {
			fmt.Println(resp)
		}
	}
}

Direct VPC connection

Important

Direct VPC connections are only supported for services in a dedicated resource group purchased from the EAS console. You must also connect the resource group to a specified vSwitch. To use this connection type, call the client.SetEndpointType(eas.EndpointTypeDirect) method. This approach is ideal for high-traffic, high-concurrency services.

package main
import (
	"fmt"
	"github.com/pai-eas/eas-golang-sdk/eas"
)
func main() {
        // NewPredictClient(invocationURL, serviceName) Both parameters are required.
	client := eas.NewPredictClient("pai-eas-vpc.cn-shanghai.aliyuncs.com", "lizhuo_prepub")
	// SetRequestPath(requestPath) Specify the path based on your requirements.
	client.SetRequestPath("/api/rec/feed")
	// SetToken(token) Specify the token.
	client.SetToken("**********************")
	// Set the client to use a direct network request.
	client.SetEndpointType(eas.EndpointTypeDirect)
	err := client.Init()
	if err != nil {
		fmt.Println(err)
		return
	}
	// Specify the request parameters.
	req := "{\"scene_id\":\"home_feed\",\"size\":10,\"uid\":\"1234\"}"
	for i := 0; i < 10; i++ {
		resp, err := client.StringPredict(req)
		if err != nil {
			fmt.Printf("failed to predict: %v \n", err)
		} else {
			fmt.Println(resp)
		}
	}
}

Connect by using the Java SDK

SDK repository: pai-eas/eas-java-sdk

Add the dependency

If you use Maven, add the eas-sdk dependency to your pom.xml file. Latest release version:

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

Sample recommendation request

If you use a custom processor, call the PAI-Rec engine service by sending a string request. Example:

package org.example;
import com.aliyun.openservices.eas.predict.http.PredictClient;
import com.aliyun.openservices.eas.predict.http.HttpConfig;
public class Main {
    public static void main(String[] args) throws Exception {
        // Initialize the client. Share this object across requests. Do not create a new client for each request.
        PredictClient client = new PredictClient(new HttpConfig());
        client.setToken("**************************");
        // To use a direct VPC connection, call the setDirectEndpoint method.
        // For example: client.setDirectEndpoint("pai-eas-vpc.cn-shanghai.aliyuncs.com");
        // A direct VPC connection must be enabled in the EAS console. You need to provide the source VSwitch that is used to access the EAS service. After the connection is established, you can bypass the gateway and access service instances directly through software load balancing for improved stability and performance.
        // Note: For public gateway access, use the endpoint that starts with your user ID, which can be found in the invocation information of your service in the EAS console. For direct connection access, use a domain name in the format of pai-eas-vpc.{region_id}.aliyuncs.com.
        client.setEndpoint("1730760139076263.cn-shanghai.pai-eas.aliyuncs.com");
        // Set the service name.
        client.setModelName("lizhuo_prepub");
        // Set the request path.
        client.setRequestPath("/api/rec/feed");
        // Define the input string.
        String request = "{\"scene_id\":\"home_feed\",\"size\":10,\"uid\":\"1214\"}";
        System.out.println(request);
        // Send the request and get a string response from EAS.
        try {
            String response = client.predict(request);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Shut down the client.
        client.shutdown();
        return;
    }
}
Note
  • Create a client object with PredictClient. If your application accesses multiple services, create a separate client object for each.

  • After you create a PredictClient object, set its token, endpoint, and model name.

  • Send an HTTP request by calling client.predict with the request string, then process the response.

  • Call the shutdown() method to close the client.

Direct VPC connection

package org.example;
import com.aliyun.openservices.eas.predict.http.PredictClient;
import com.aliyun.openservices.eas.predict.http.HttpConfig;
public class Main {
    public static void main(String[] args) throws Exception {
        // Initialize the client. Share this object across requests. Do not create a new client for each request.
        PredictClient client = new PredictClient(new HttpConfig());
        client.setToken("**************************");
        // To use a direct VPC connection, call the setDirectEndpoint method.
        // For example: client.setDirectEndpoint("pai-eas-vpc.cn-shanghai.aliyuncs.com");
        // A direct VPC connection must be enabled in the EAS console. You need to provide the source VSwitch that is used to access the EAS service. After the connection is established, you can bypass the gateway and access service instances directly through software load balancing for improved stability and performance.
        // Note: For public gateway access, use the endpoint that starts with your user ID, which can be found in the invocation information of your service in the EAS console. For direct connection access, use a domain name in the format of pai-eas-vpc.{region_id}.aliyuncs.com.
        // To use a direct VPC connection, call setDirectEndpoint() with the VPC address.
        client.setDirectEndpoint("pai-eas-vpc.cn-shanghai.aliyuncs.com");
        // Set the service name.
        client.setModelName("lizhuo_prepub");
        // Set the request path.
        client.setRequestPath("/api/rec/feed");
        // Define the input string.
        String request = "{\"scene_id\":\"home_feed\",\"size\":10,\"uid\":\"1214\"}";
        System.out.println(request);
        // Send the request and get a string response from EAS.
        try {
            String response = client.predict(request);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Shut down the client.
        client.shutdown();
        return;
    }
}

Request compression

Compress requests with the zstd, lz4, or gzip algorithm. The engine API decompresses them automatically.

Warning

You must use eas-sdk version 2.0.26 or later.

  1. zstd request compression example

In addition to the previous client settings, add the following configurations:

  • setCompressor: Specifies the compression algorithm for the EAS SDK.

  • Content-Encoding: Tells the engine which algorithm to use to decompress the request.

client.setCompressor(Compressor.Zstd);
Map<String, String> header = new HashMap<String, String>();
header.put("Content-Encoding", "zstd");
client.addExtraHeaders(header);
  1. lz4 request compression example

 client.setCompressor(Compressor.LZ4Frame);
 Map<String, String> header = new HashMap<String, String>();
 header.put("Content-Encoding", "lz4");
 client.addExtraHeaders(header);
  1. gzip request compression example

  client.setCompressor(Compressor.Gzip);
  Map<String, String> header = new HashMap<String, String>();
  header.put("Content-Encoding", "gzip");
  client.addExtraHeaders(header);

Response compression

When the recommendation API returns a large payload, instruct the engine to compress the response. The engine supports zstd, lz4, and gzip compression.

Warning

You must use eas-sdk version 2.0.26 or later.

  1. zstd decompression example

In addition to the previous client settings, add the following configurations:

  • setDecompressor: Specifies the algorithm that the EAS SDK uses to decompress response data.

  • Accept-Encoding: Tells the engine which algorithm to use to compress the response.

  client.setDecompressor(Compressor.Zstd);
  Map<String, String> header = new HashMap<String, String>();
  header.put("Accept-Encoding", "zstd");
  client.addExtraHeaders(header);
  1. lz4 decompression example

 client.setDecompressor(Compressor.LZ4Frame);
 Map<String, String> header = new HashMap<String, String>();
 header.put("Accept-Encoding", "lz4");
 client.addExtraHeaders(header);
  1. gzip decompression example

  client.setDecompressor(Compressor.Gzip);
  Map<String, String> header = new HashMap<String, String>();
  header.put("Accept-Encoding", "gzip");
  client.addExtraHeaders(header);