Este tópico descreve como instale e usar o sdk Java do Realtime Compute for Apache Flink.
Observações de uso
Entre 19 de setembro e 27 de outubro de 2022, a Alibaba Cloud implementou uma atualização no sdk do Realtime Compute for Apache Flink em todas as regiões. Essa versão passou a ser o padrão.
Para obter informações sobre o impacto da atualização do sdk, consulte Avisos de serviço.
Este documento descreve a nova versão do sdk. Para visualize a documentação da versão anterior, clique em OpenAPI SDK (Descontinuado).
Pré-requisitos
-
Crie um AccessKey. Para mais informações, consulte Criar um AccessKey.
NotaPara mitigar riscos de segurança caso o AccessKey da sua conta Alibaba Cloud seja comprometido, recomendamos crie um usuário ram, conceder a ele permissões relacionadas ao Flink e usar seu AccessKey para chamar o sdk. Para mais informações, consulte os seguintes tópicos:
Para crie um usuário ram e seu AccessKey, consulte Criar um usuário RAM ou Criar um AccessKey.
Para conceder permissões a um usuário ram, consulte Autorização no Console de Gerenciamento da Alibaba Cloud.
Java 8 ou posterior instalado.
Sua conta possui as permissões necessárias. Para mais informações, consulte Gerenciamento de Permissões.
sdks Java do Realtime Compute for Apache Flink
Selling console
|
Método de instalação |
Código |
|
Apache Maven |
<dependency> <groupId>com.aliyun</groupId> <artifactId>foasconsole20211028</artifactId> <version>2.1.0</version> </dependency> |
|
Gradle Groovy DSL |
implementation 'com.aliyun:foasconsole20211028:2.1.0' |
|
Gradle Kotlin DSL |
implementation("com.aliyun:foasconsole20211028:2.1.0") |
|
Scala SBT |
libraryDependencies += "com.aliyun" % "foasconsole20211028" % "2.1.0" |
|
Apache Ivy |
<dependency org="com.aliyun" name="foasconsole20211028" rev="2.1.0" /> |
|
Groovy Grape |
@Grapes( @Grab(group='com.aliyun', module='foasconsole20211028', version='2.1.0') ) |
|
Leiningen |
[com.aliyun/foasconsole20211028 "2.1.0"] |
|
Apache Buildr |
'com.aliyun:foasconsole20211028:jar:2.1.0' |
Development console
|
Método de instalação |
Código |
|
Apache Maven |
<dependency> <groupId>com.aliyun</groupId> <artifactId>ververica20220718</artifactId> <version>1.7.0</version> </dependency> |
|
Gradle Groovy DSL |
implementation 'com.aliyun:ververica20220718:1.7.0' |
|
Gradle Kotlin DSL |
implementation("com.aliyun:ververica20220718:1.7.0") |
|
Scala SBT |
libraryDependencies += "com.aliyun" % "ververica20220718" % "1.7.0" |
|
Apache Ivy |
<dependency org="com.aliyun" name="ververica20220718" rev="1.7.0" /> |
|
Groovy Grape |
@Grapes( @Grab(group='com.aliyun', module='ververica20220718', version='1.7.0') ) |
|
Leiningen |
[com.aliyun/ververica20220718 "1.7.0"] |
|
Apache Buildr |
'com.aliyun:ververica20220718:jar:1.7.0' |
Depurar online e gerar exemplos de sdk
Use o OpenAPI Explorer para chamar operações de api online, gerar dinamicamente códigos de exemplo do sdk e pesquisar rapidamente por operações de api. Visualize e baixe códigos de exemplo do sdk para operações de api nas páginas do Realtime Compute for Apache Flink e do Realtime Compute Selling Console. Para mais informações, consulte Início Rápido.
Na aba SDK Example, selecione uma linguagem, como Java. Clique em Run Example para execute o código online ou em Download Complete Project para baixe o código de exemplo.
Exemplos
Workspaces adquiridos
Este exemplo demonstra como recuperar detalhes sobre workspaces do Realtime Compute for Apache Flink adquiridos em uma região específica.
Region: O ID da região . Para mais informações, consulte Endpoints. Por exemplo, cn-hangzhou.
package com.aliyun.sample;
import com.aliyun.foasconsole20211028.models.DescribeInstancesResponse;
import com.aliyun.tea.*;
import com.alibaba.fastjson2.JSON;
public class Sample {
/**
* <b>description</b> :
* <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.foasconsole20211028.Client createClient() throws Exception {
// Hard-coding the AccessKey pair in your code may cause the AccessKey pair to be leaked and threaten the security of all the resources in your account. The following sample code is for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "foasconsole.aliyuncs.com";
return new com.aliyun.foasconsole20211028.Client(config);
}
public static void main(String[] args_) throws Exception {
com.aliyun.foasconsole20211028.Client client = Sample.createClient();
com.aliyun.foasconsole20211028.models.DescribeInstancesRequest describeInstancesRequest = new com.aliyun.foasconsole20211028.models.DescribeInstancesRequest()
.setRegion("cn-beijing");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
DescribeInstancesResponse response = client.describeInstancesWithOptions(describeInstancesRequest, runtime);
System.out.println(response.statusCode);
// Query the region ID of an instance.
System.out.println(response.getBody().getInstances().get(0).zoneId);
// Query the ID of the resource group to which an instance belongs.
System.out.println(response.getBody().getInstances().get(0).resourceGroupId);
System.out.println(JSON.toJSON(response));
} catch (TeaException error) {
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Crie um deployment
SQL deployment
Este exemplo mostra como crie um deployment SQL.
workspace: O ID do workspace. Obtenha este ID a partir doResourceIdretornado ao visualize workspaces adquiridos. Por exemplo,adf9e514****.namespace: O nome do namespace. Por exemplo, test-default.body.name: O nome do job. Por exemplo, mysql_data_holo_test.body.engineVersion: A versão do mecanismo. Por exemplo, vvr-8.0.7-flink-1.17. Consulte as versões suportadas ao listar as versões de mecanismo suportadas.body.sqlArtifact.sqlScript: O conteúdo do script SQL. Exemplo:CREATE TEMPORARY TABLE datagen_source( name VARCHAR ) WITH ( 'connector' = 'datagen' ); CREATE TEMPORARY TABLE blackhole_sink( name VARCHAR ) with ( 'connector' = 'blackhole' ); INSERT INTO blackhole_sink SELECT name from datagen_source;.body.sqlArtifact.kind: O tipo do job. Por exemplo, SQLSCRIPT.body.deploymentTarget.mode: O modo de deployment. Apenas o modo PER_JOB é suportado.body.deploymentTarget.name: O nome da fila de deployment. Por exemplo, default-queue.body.executionMode: Modo de execução. Por exemplo, STREAMING (modo streaming).body.streamingResourceSetting.resourceSettingMode: O modo de recurso para o modo streaming. Por exemplo, BASIC.body.streamingResourceSetting.basicResourceSetting.jobmanagerResourceSettingSpec.cpu: O número de núcleos de CPU para o JobManager. Por exemplo, 2.body.streamingResourceSetting.basicResourceSetting.jobmanagerResourceSettingSpec.memory: Memória do JobManager. Por exemplo, 4.0 GiB.body.streamingResourceSetting.basicResourceSetting.taskmanagerResourceSettingSpec.cpu: O número de núcleos de CPU do TaskManager. Por exemplo, 2.body.streamingResourceSetting.basicResourceSetting.taskmanagerResourceSettingSpec.memory: Memória do TaskManager. Por exemplo, 4.0 GiB.
package com.aliyun.sample;
import com.aliyun.tea.*;
public class Sample {
/**
* <b>description</b> :
* <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.teaopenapi.Client createClient() throws Exception {
// Hard-coding the AccessKey pair in your code may cause the AccessKey pair to be leaked and threaten the security of all the resources in your account. The following sample code is for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ververica.cn-beijing.aliyuncs.com";
return new com.aliyun.teaopenapi.Client(config);
}
/**
* <b>description</b> :
* <p>API parameters</p>
*
* @param path params
* @return OpenApi.Params
*/
public static com.aliyun.teaopenapi.models.Params createApiInfo(String namespace) throws Exception {
com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
// The name of the API operation.
.setAction("CreateDeployment")
// The version of the API operation.
.setVersion("2022-07-18")
// The protocol of the API operation.
.setProtocol("HTTPS")
// The HTTP method of the API operation.
.setMethod("POST")
.setAuthType("AK")
.setStyle("ROA")
// The request path of the API operation.
.setPathname("/api/v2/namespaces/" + namespace + "/deployments")
// The format of the request body.
.setReqBodyType("json")
// The format of the response body.
.setBodyType("json");
return params;
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.teaopenapi.Client client = Sample.createClient();
com.aliyun.teaopenapi.models.Params params = Sample.createApiInfo("test-default");
// body params
java.util.Map<String, Object> body = TeaConverter.buildMap(
new TeaPair("name", "mysql_data_holo_test"),
new TeaPair("engineVersion", "vvr-8.0.7-flink-1.17"),
new TeaPair("artifact", TeaConverter.buildMap(
new TeaPair("sqlArtifact", TeaConverter.buildMap(
new TeaPair("sqlScript", "CREATE TEMPORARY TABLE datagen_source( name VARCHAR ) WITH ( 'connector' = 'datagen' ); CREATE TEMPORARY TABLE blackhole_sink( name VARCHAR ) with ( 'connector' = 'blackhole' ); INSERT INTO blackhole_sink SELECT name from datagen_source;")
)),
new TeaPair("kind", "SQLSCRIPT")
)),
new TeaPair("deploymentTarget", TeaConverter.buildMap(
new TeaPair("mode", "PER_JOB"),
new TeaPair("name", "default-queue")
)),
new TeaPair("executionMode", "STREAMING"),
new TeaPair("streamingResourceSetting", TeaConverter.buildMap(
new TeaPair("resourceSettingMode", "BASIC"),
new TeaPair("basicResourceSetting", TeaConverter.buildMap(
new TeaPair("jobmanagerResourceSettingSpec", TeaConverter.buildMap(
new TeaPair("cpu", 2),
new TeaPair("memory", "4")
)),
new TeaPair("taskmanagerResourceSettingSpec", TeaConverter.buildMap(
new TeaPair("cpu", 2),
new TeaPair("memory", "4")
))
))
))
);
// header params
java.util.Map<String, String> headers = new java.util.HashMap<>();
headers.put("workspace", "ab2*******884d");
// runtime options
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
.setHeaders(headers)
.setBody(body);
// The method returns a Map. You can obtain the response body, response headers, and HTTP status code from the map.
client.callApi(params, request, runtime);
java.util.Map<String, ?> response = client.callApi(params, request, runtime);
System.out.println(response);
}
}
JAR deployment
Este exemplo ilustra a criação de um deployment JAR.
Faça upload do pacote JAR para um bucket OSS e garanta que seu workspace do Realtime Compute for Apache Flink tenha permissão de acesso. Para mais informações, consulte Upload simples.
Após o upload do arquivo, a URL de download segue o formato https://<Bucket>.oss-<Region>.aliyuncs.com/<FileName>.
workspace: O ID do workspace. Obtenha este ID a partir doResourceIdretornado ao visualize workspaces adquiridos. Por exemplo, adf9e514****.namespace: O nome do namespace. Por exemplo, test-default.body.name: O nome do job. Por exemplo, my-test-jar.body.engineVersion: A versão do mecanismo. Por exemplo, vvr-8.0.7-flink-1.17. É possível obter uma lista das versões de mecanismo suportadas.body.jarArtifact.kind: O tipo de artefato do job. Por exemplo, JAR.body.jarArtifact.jarUri: O caminho completo da URL do deployment JAR. Por exemplo, https://myBucket/oss-cn-hangzhou/test.jar.body.jarArtifact.entryClass: A classe de ponto de entrada. Especifique o nome totalmente qualificado da classe. Por exemplo, org.apache.flink.test.body.deploymentTarget.mode: Modo de deployment. Apenas o modo PER_JOB é suportado.body.deploymentTarget.name: O nome da fila de deployment. Por exemplo, default-queue.body.executionMode: Modo de execução. Por exemplo, STREAMING (modo streaming).body.streamingResourceSetting.resourceSettingMode: O modo de recurso para o modo streaming. Por exemplo, BASIC.body.streamingResourceSetting.basicResourceSetting.jobmanagerResourceSettingSpec.cpu: O número de núcleos de CPU para o JobManager. Por exemplo, 2.body.streamingResourceSetting.basicResourceSetting.jobmanagerResourceSettingSpec.memory: Memória do JobManager. Por exemplo, 4.0 GiB.body.streamingResourceSetting.basicResourceSetting.taskmanagerResourceSettingSpec.cpu: O número de núcleos de CPU para o TM. Por exemplo, 2.body.streamingResourceSetting.basicResourceSetting.taskmanagerResourceSettingSpec.memory: A memória do TaskManager. Por exemplo, 4.0 GiB.
package com.aliyun.sample;
import com.aliyun.tea.*;
public class Sample {
/**
* <b>description</b> :
* <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.teaopenapi.Client createClient() throws Exception {
// Hard-coding the AccessKey pair in your code may cause the AccessKey pair to be leaked and threaten the security of all the resources in your account. The following sample code is for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ververica.cn-hangzhou.aliyuncs.com";
return new com.aliyun.teaopenapi.Client(config);
}
/**
* <b>description</b> :
* <p>API parameters</p>
*
* @param path params
* @return OpenApi.Params
*/
public static com.aliyun.teaopenapi.models.Params createApiInfo(String namespace) throws Exception {
com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
// The name of the API operation.
.setAction("CreateDeployment")
// The version of the API operation.
.setVersion("2022-07-18")
// The protocol of the API operation.
.setProtocol("HTTPS")
// The HTTP method of the API operation.
.setMethod("POST")
.setAuthType("AK")
.setStyle("ROA")
// The request path of the API operation.
.setPathname("/api/v2/namespaces/" + namespace + "/deployments")
// The format of the request body.
.setReqBodyType("json")
// The format of the response body.
.setBodyType("json");
return params;
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.teaopenapi.Client client = Sample.createClient();
com.aliyun.teaopenapi.models.Params params = Sample.createApiInfo("flink-default");
// body params
java.util.Map<String, Object> body = TeaConverter.buildMap(
new TeaPair("name", "my-test-jar"),
new TeaPair("engineVersion", "vvr-8.0.7-flink-1.17"),
new TeaPair("artifact", TeaConverter.buildMap(
new TeaPair("kind", "JAR"),
new TeaPair("jarArtifact", TeaConverter.buildMap(
new TeaPair("jarUri", "https://flink-test.oss-cn-hangzhou.aliyuncs.com/flinkDemo.jar?*****"),
new TeaPair("entryClass", "com.aliyun.FlinkDemo")
))
)),
new TeaPair("deploymentTarget", TeaConverter.buildMap(
new TeaPair("mode", "PER_JOB"),
new TeaPair("name", "default-queue")
)),
new TeaPair("executionMode", "STREAMING"),
new TeaPair("streamingResourceSetting", TeaConverter.buildMap(
new TeaPair("resourceSettingMode", "BASIC"),
new TeaPair("basicResourceSetting", TeaConverter.buildMap(
new TeaPair("jobmanagerResourceSettingSpec", TeaConverter.buildMap(
new TeaPair("cpu", 2),
new TeaPair("memory", "4")
)),
new TeaPair("taskmanagerResourceSettingSpec", TeaConverter.buildMap(
new TeaPair("cpu", 2),
new TeaPair("memory", "4")
))
))
))
);
// header params
java.util.Map<String, String> headers = new java.util.HashMap<>();
headers.put("workspace", "d05a*****e44");
// runtime options
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
.setHeaders(headers)
.setBody(body);
// The method returns a Map. You can obtain the response body, response headers, and HTTP status code from the map.
java.util.Map<String, ?> response = client.callApi(params, request, runtime);
System.out.println(response);
}
}
Listar deployments
Este exemplo demonstra como listar todos os deployments em um namespace.
workspace: O ID do workspace. Obtenha o ID a partir doResourceIdretornado pela operação em Visualize workspaces adquiridos. Por exemplo, adf9e514****.namespace: O nome do namespace. Por exemplo, test-default.
package com.sample;
import com.aliyun.tea.*;
import com.alibaba.fastjson2.JSON;
import com.aliyun.ververica20220718.models.ListDeploymentsResponse;
public class Sample {
/**
* <b>description</b> :
* <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.ververica20220718.Client createClient() throws Exception {
// Hard-coding the AccessKey pair in your code may cause the AccessKey pair to be leaked and threaten the security of all the resources in your account. The following sample code is for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ververica.cn-hangzhou.aliyuncs.com";
return new com.aliyun.ververica20220718.Client(config);
}
public static void main(String[] args_) throws Exception {
com.aliyun.ververica20220718.Client client = Sample.createClient();
com.aliyun.ververica20220718.models.ListDeploymentsHeaders listDeploymentsHeaders = new com.aliyun.ververica20220718.models.ListDeploymentsHeaders()
.setWorkspace("ab2a******884d");
com.aliyun.ververica20220718.models.ListDeploymentsRequest listDeploymentsRequest = new com.aliyun.ververica20220718.models.ListDeploymentsRequest();
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
ListDeploymentsResponse response=client.listDeploymentsWithOptions("test-default", listDeploymentsRequest, listDeploymentsHeaders, runtime);
System.out.println(response.body.data.get(0).name);
System.out.println(response.body.data.get(0).deploymentId);
System.out.println(JSON.toJSON(response));
} catch (TeaException error) {
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Iniciar um job
Este exemplo mostra como iniciar um job a partir de um deployment em um namespace.
workspace: O ID do workspace. Por exemplo, adf9e5147a****.namespace: O nome do namespace, como test-default.deploymentId: O ID do deployment. Obtenha este ID chamando a operação Listar deployments. Por exemplo, 10283a02-c6a6-4f3e-9f93-8dab****.kind: O tipo de estratégia de restauração. Os valores suportados são NONE (início sem estado), LATEST_SAVEPOINT (início a partir do savepoint mais recente), FROM_SAVEPOINT (início a partir de um savepoint especificado) e LATEST_STATE (início a partir do estado mais recente).
package com.aliyun.sample;
import com.aliyun.tea.*;
import com.aliyun.ververica20220718.models.StartJobWithParamsResponse;
import com.alibaba.fastjson2.JSON;
public class Sample {
/**
* <b>description</b> :
* <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.ververica20220718.Client createClient() throws Exception {
// Hard-coding the AccessKey pair in your code may cause the AccessKey pair to be leaked and threaten the security of all the resources in your account. The following sample code is for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ververica.cn-hangzhou.aliyuncs.com";
return new com.aliyun.ververica20220718.Client(config);
}
public static void main(String[] args_) throws Exception {
com.aliyun.ververica20220718.Client client = Sample.createClient();
com.aliyun.ververica20220718.models.StartJobWithParamsHeaders startJobWithParamsHeaders = new com.aliyun.ververica20220718.models.StartJobWithParamsHeaders()
.setWorkspace("ab2a******884d");
com.aliyun.ververica20220718.models.DeploymentRestoreStrategy jobStartParametersDeploymentRestoreStrategy = new com.aliyun.ververica20220718.models.DeploymentRestoreStrategy()
.setKind("NONE");
com.aliyun.ververica20220718.models.JobStartParameters jobStartParameters = new com.aliyun.ververica20220718.models.JobStartParameters()
.setRestoreStrategy(jobStartParametersDeploymentRestoreStrategy)
.setDeploymentId("10283a02-**--**-8dabf617d52f");
com.aliyun.ververica20220718.models.StartJobWithParamsRequest startJobWithParamsRequest = new com.aliyun.ververica20220718.models.StartJobWithParamsRequest()
.setBody(jobStartParameters);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
StartJobWithParamsResponse response = client.startJobWithParamsWithOptions("test-default", startJobWithParamsRequest, startJobWithParamsHeaders, runtime);
System.out.println(JSON.toJSON(response.body));
} catch (TeaException error) {
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Listar jobs
Este exemplo demonstra como consultar todos os jobs de um deployment específico.
workspace: O ID do workspace. Por exemplo, adf9e5147****.namespace: O nome do namespace, por exemplo, test-default.deploymentId: O ID do deployment. Para obter este ID, consulte Obter a lista de deployments. Por exemplo, 8489b7ec-**--**-cc4c17fa12b0.
package com.aliyun.sample;
import com.aliyun.tea.*;
import com.aliyun.ververica20220718.models.ListJobsResponse;
import com.alibaba.fastjson2.JSON;
public class Sample {
/**
* <b>description</b> :
* <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.ververica20220718.Client createClient() throws Exception {
// Hard-coding the AccessKey pair in your code may cause the AccessKey pair to be leaked and threaten the security of all the resources in your account. The following sample code is for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ververica.cn-beijing.aliyuncs.com";
return new com.aliyun.ververica20220718.Client(config);
}
public static void main(String[] args_) throws Exception {
com.aliyun.ververica20220718.Client client = Sample.createClient();
com.aliyun.ververica20220718.models.ListJobsHeaders listJobsHeaders = new com.aliyun.ververica20220718.models.ListJobsHeaders()
.setWorkspace("ab2a******884d");
com.aliyun.ververica20220718.models.ListJobsRequest listJobsRequest = new com.aliyun.ververica20220718.models.ListJobsRequest()
.setDeploymentId("8489b7ec-****-****-****-cc4c17fa12b0");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
ListJobsResponse response = client.listJobsWithOptions("test-default", listJobsRequest, listJobsHeaders, runtime);
// View the execution result of the job.
System.out.println("Execution result is: "+response.body.success);
// Obtain the job ID. This ID is used to cancel the job.
System.out.println(response.body.getData().get(0).jobId);
System.out.println(JSON.toJSON(response));
} catch (TeaException error) {
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Parar um job
Este exemplo mostra como parar um job.
workspace: O ID do workspace. Por exemplo, adf9e5147****.namespace: O nome do namespace, por exemplo, test-default.jobId: O ID do job. Para mais informações, consulte Obter informações sobre um deployment específico. Por exemplo, 3171d4d1-**--**-e762493b7765.stopStrategy: A estratégia de parada do job. Os valores suportados são NONE (para o job diretamente), STOP_WITH_SAVEPOINT (para o job após a criação de um savepoint) e STOP_WITH_DRAIN (para o job no modo drain).
package com.aliyun.sample;
import com.alibaba.fastjson2.JSON;
import com.aliyun.tea.*;
import com.aliyun.ververica20220718.models.StopJobResponse;
public class Sample {
/**
* <b>description</b> :
* <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.ververica20220718.Client createClient() throws Exception {
// Hard-coding the AccessKey pair in your code may cause the AccessKey pair to be leaked and threaten the security of all the resources in your account. The following sample code is for reference only.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "ververica.cn-hangzhou.aliyuncs.com";
return new com.aliyun.ververica20220718.Client(config);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.ververica20220718.Client client = Sample.createClient();
com.aliyun.ververica20220718.models.StopJobHeaders stopJobHeaders = new com.aliyun.ververica20220718.models.StopJobHeaders()
.setWorkspace("ab2a******884d");
com.aliyun.ververica20220718.models.StopJobRequestBody stopJobRequestBody = new com.aliyun.ververica20220718.models.StopJobRequestBody()
.setStopStrategy("NONE");
com.aliyun.ververica20220718.models.StopJobRequest stopJobRequest = new com.aliyun.ververica20220718.models.StopJobRequest()
.setBody(stopJobRequestBody);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
StopJobResponse response = client.stopJobWithOptions("test-default", "7970e881-****-****-****-1a3746710878", stopJobRequest, stopJobHeaders, runtime);
System.out.println(JSON.toJSON(response.getBody().getData()));
} catch (TeaException error) {
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// In this example, the error message is printed for reference only. We recommend that you handle exceptions with caution in your project and do not ignore them.
// Error message
System.out.println(error.getMessage());
// Diagnostic address
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Referências
Para mais informações sobre o sdk Python, consulte a referência do sdk Python.