### Manage Aliyun FC Services using Java SDK Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Demonstrates creating, getting, updating, listing, and deleting services. Ensure the `fcClient` is initialized and necessary permissions are configured. ```java import com.aliyuncs.fc.model.LogConfig; import com.aliyuncs.fc.model.VpcConfig; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // --- Create --- LogConfig logConfig = new LogConfig(); logConfig.setProject("my-log-project"); logConfig.setLogstore("my-logstore"); logConfig.setEnableRequestMetrics(true); CreateServiceRequest createReq = new CreateServiceRequest(); createReq.setServiceName("my-service"); createReq.setDescription("Production service"); createReq.setRole("acs:ram::123456789:role/fc-execution-role"); createReq.setLogConfig(logConfig); createReq.setInternetAccess(true); CreateServiceResponse createResp = fcClient.createService(createReq); System.out.println("Created service, requestId=" + createResp.getRequestId()); // --- Get --- GetServiceRequest getReq = new GetServiceRequest("my-service"); GetServiceResponse getResp = fcClient.getService(getReq); System.out.println("Service: " + getResp.getServiceMetadata().getServiceName()); // --- Update --- UpdateServiceRequest updateReq = new UpdateServiceRequest("my-service"); updateReq.setDescription("Updated description"); UpdateServiceResponse updateResp = fcClient.updateService(updateReq); // --- List (paginated) --- ListServicesRequest listReq = new ListServicesRequest(); listReq.setLimit(20); ListServicesResponse listResp = fcClient.listServices(listReq); for (var svc : listResp.getServices()) { System.out.println(svc.getServiceName()); } // --- Delete --- DeleteServiceRequest delReq = new DeleteServiceRequest("my-service"); fcClient.deleteService(delReq); ``` -------------------------------- ### Manage Aliyun FC Functions using Java SDK Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Provides examples for creating, getting, updating, listing, and deleting functions. Supports creating functions from local directories or custom containers. Ensure `fcClient` is initialized. ```java import com.aliyuncs.fc.model.Code; import com.aliyuncs.fc.model.CustomContainerConfig; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; import java.util.HashMap; import java.util.Map; // --- Create from a local code directory --- Code code = new Code().setDir("/tmp/my_function_code"); Map envVars = new HashMap<>(); envVars.put("ENV", "production"); envVars.put("LOG_LEVEL", "INFO"); CreateFunctionRequest createReq = new CreateFunctionRequest("my-service"); createReq.setFunctionName("my-function"); createReq.setDescription("Example Node.js function"); createReq.setRuntime("nodejs14"); createReq.setHandler("index.handler"); createReq.setInitializer("index.initializer"); createReq.setMemorySize(256); // MB createReq.setTimeout(30); // seconds createReq.setInitializationTimeout(10); createReq.setInstanceConcurrency(5); createReq.setCode(code); createReq.setEnvironmentVariables(envVars); CreateFunctionResponse createResp = fcClient.createFunction(createReq); System.out.println("Created function, requestId=" + createResp.getRequestId()); // --- Create a Custom Container function --- CustomContainerConfig containerConfig = new CustomContainerConfig(); containerConfig.setImage("registry.cn-shanghai.aliyuncs.com/myrepo/myimage:latest"); containerConfig.setCommand("[\"node\"]"); containerConfig.setArgs("[\"server.js\"]"); CreateFunctionRequest containerReq = new CreateFunctionRequest("my-service"); containerReq.setFunctionName("my-container-function"); containerReq.setRuntime("custom-container"); containerReq.setHandler("not-used"); containerReq.setMemorySize(512); containerReq.setCAPort(9000); containerReq.setCustomContainerConfig(containerConfig); containerReq.setCode(new Code().setOssBucketName("my-bucket").setOssObjectName("placeholder.zip")); fcClient.createFunction(containerReq); // --- Get --- GetFunctionRequest getReq = new GetFunctionRequest("my-service", "my-function"); GetFunctionResponse getResp = fcClient.getFunction(getReq); System.out.println("Runtime: " + getResp.getFunctionMetadata().getRuntime()); // --- List --- ListFunctionsRequest listReq = new ListFunctionsRequest("my-service"); listReq.setLimit(10); ListFunctionsResponse listResp = fcClient.listFunctions(listReq); for (var fn : listResp.getFunctions()) { System.out.println(fn.getFunctionName() + " - " + fn.getRuntime()); } // --- Delete --- fcClient.deleteFunction(new DeleteFunctionRequest("my-service", "my-function")); ``` -------------------------------- ### Trigger Management Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Provides examples for creating, retrieving, updating, deleting, and listing triggers. Covers Timer, OSS, and HTTP trigger configurations. ```APIDOC ## Trigger Management — `createTrigger` / `getTrigger` / `updateTrigger` / `deleteTrigger` / `listTriggers` Triggers connect external event sources (OSS, Timer, HTTP, Log, CDN, RDS) to functions. ```java import com.aliyuncs.fc.model.*; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // --- Create a Timer trigger --- TimeTriggerConfig timerConfig = new TimeTriggerConfig(); timerConfig.setCronExpression("@every 5m"); timerConfig.setEnable(true); timerConfig.setPayload("{\"scheduled\":true}"); CreateTriggerRequest timerReq = new CreateTriggerRequest("my-service", "my-function"); timerReq.setTriggerName("every-5-minutes"); timerReq.setTriggerType("timer"); timerReq.setTriggerConfig(timerConfig); CreateTriggerResponse timerResp = fcClient.createTrigger(timerReq); System.out.println("Trigger created: " + timerResp.getTriggerMetadata().getTriggerName()); // --- Create an OSS trigger --- OSSTriggerConfig ossConfig = new OSSTriggerConfig(); OSSTriggerFilter filter = new OSSTriggerFilter(); OSSTriggerKey key = new OSSTriggerKey(); key.setPrefix("uploads/"); key.setSuffix(".jpg"); filter.setKey(key); ossConfig.setFilter(filter); ossConfig.setEvents(new String[]{"oss:ObjectCreated:*"}); CreateTriggerRequest ossReq = new CreateTriggerRequest("my-service", "image-processor"); ossReq.setTriggerName("oss-image-upload"); ossReq.setTriggerType("oss"); ossReq.setSourceArn("acs:oss:cn-shanghai:123456789:my-bucket"); ossReq.setInvocationRole("acs:ram::123456789:role/oss-invoke-fc"); ossReq.setTriggerConfig(ossConfig); fcClient.createTrigger(ossReq); // --- Create an HTTP trigger --- HttpTriggerConfig httpConfig = new HttpTriggerConfig(); httpConfig.setMethods(new String[]{"GET", "POST"}); httpConfig.setAuthType(HttpAuthType.ANONYMOUS); CreateTriggerRequest httpReq = new CreateTriggerRequest("my-service", "my-http-function"); httpReq.setTriggerName("http-trigger"); httpReq.setTriggerType("http"); httpReq.setTriggerConfig(httpConfig); fcClient.createTrigger(httpReq); // --- List triggers --- ListTriggersRequest listReq = new ListTriggersRequest("my-service", "my-function"); ListTriggersResponse listResp = fcClient.listTriggers(listReq); for (var t : listResp.getTriggers()) { System.out.println(t.getTriggerName() + " (" + t.getTriggerType() + ")"); } // --- Delete --- fcClient.deleteTrigger(new DeleteTriggerRequest("my-service", "my-function", "every-5-minutes")); ``` ``` -------------------------------- ### Full Aliyun FC Java SDK Example Source: https://github.com/aliyun/fc-java-sdk/blob/master/README.md Demonstrates the complete lifecycle of a Function Compute function using the Java SDK, including service and function creation, synchronous and asynchronous invocation, and deletion. Ensure environment variables ACCESS_KEY, SECRET_KEY, ACCOUNT_ID, and ROLE are set. ```Java import com.aliyuncs.fc.client.FunctionComputeClient; import com.aliyuncs.fc.constants.Const; import com.aliyuncs.fc.model.Code; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; import java.io.IOException; import java.net.HttpURLConnection; public class FcSample { private static final String CODE_DIR = "/tmp/fc_code"; private static final String REGION = "cn-shanghai"; private static final String SERVICE_NAME = "test_service"; private static final String FUNCTION_NAME = "test_function"; public static void main(final String[] args) throws IOException { String accessKey = System.getenv("ACCESS_KEY"); String accessSecretKey = System.getenv("SECRET_KEY"); String accountId = System.getenv("ACCOUNT_ID"); String role = System.getenv("ROLE"); // Initialize FC client FunctionComputeClient fcClient = new FunctionComputeClient(REGION, accountId, accessKey, accessSecretKey); // Set to a specific endpoint in case needed, endpoint sample: http://123456.cn-hangzhou.fc.aliyuncs.com // fcClient.setEndpoint("http://{accountId}.{regionId}.fc.aliyuncs.com."); // Create a service CreateServiceRequest csReq = new CreateServiceRequest(); csReq.setServiceName(SERVICE_NAME); csReq.setDescription("FC test service"); csReq.setRole(role); CreateServiceResponse csResp = fcClient.createService(csReq); System.out.println("Created service, request ID " + csResp.getRequestId()); // Create a function CreateFunctionRequest cfReq = new CreateFunctionRequest(SERVICE_NAME); cfReq.setFunctionName(FUNCTION_NAME); cfReq.setDescription("Function for test"); cfReq.setMemorySize(128); cfReq.setRuntime("nodejs4.4"); cfReq.setHandler("counter.handler"); // Used in initializer situations. cfReq.setInitializer("counter.initializer"); Code code = new Code().setDir(CODE_DIR); cfReq.setCode(code); cfReq.setTimeout(10); CreateFunctionResponse cfResp = fcClient.createFunction(cfReq); System.out.println("Created function, request ID " + cfResp.getRequestId()); // Invoke the function with a string as function event parameter, Sync mode InvokeFunctionRequest invkReq = new InvokeFunctionRequest(SERVICE_NAME, FUNCTION_NAME); String payload = "Hello FunctionCompute!"; invkReq.setPayload(payload.getBytes()); InvokeFunctionResponse invkResp = fcClient.invokeFunction(invkReq); System.out.println(new String(invkResp.getContent())); // Invoke the function, Async mode invkReq.setInvocationType(Const.INVOCATION_TYPE_ASYNC); invkResp = fcClient.invokeFunction(invkReq); if (HttpURLConnection.HTTP_ACCEPTED == invkResp.getStatus()) { System.out.println("Async invocation has been queued for execution, request ID: " + invkResp.getRequestId()); } else { System.out.println("Async invocation was not accepted"); } // Delete the function DeleteFunctionRequest dfReq = new DeleteFunctionRequest(SERVICE_NAME, FUNCTION_NAME); DeleteFunctionResponse dfResp = fcClient.deleteFunction(dfReq); System.out.println("Deleted function, request ID " + dfResp.getRequestId()); // Delete the service DeleteServiceRequest dsReq = new DeleteServiceRequest(SERVICE_NAME); DeleteServiceResponse dsResp = fcClient.deleteService(dsReq); System.out.println("Deleted service, request ID " + dsResp.getRequestId()); } } ``` -------------------------------- ### Manage Function Provision Config Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Use `putProvisionConfig` to keep a fixed number of function instances warm, eliminating cold starts. `getProvisionConfig` retrieves the current settings, and `listProvisionConfigs` shows all configured provision settings. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // Keep 5 instances always warm for the PROD alias PutProvisionConfigRequest putReq = new PutProvisionConfigRequest( "my-service", "PROD", "my-function"); putReq.setTarget(5); PutProvisionConfigResponse putResp = fcClient.putProvisionConfig(putReq); System.out.println("Provisioned target: " + putResp.getProvisionTarget().getTarget()); // --- Get current provision config --- GetProvisionConfigRequest getReq = new GetProvisionConfigRequest( "my-service", "PROD", "my-function"); GetProvisionConfigResponse getResp = fcClient.getProvisionConfig(getReq); System.out.println("Current: " + getResp.getProvisionConfig().getCurrent() + " / Target: " + getResp.getProvisionConfig().getTarget()); // --- List all provision configs --- ListProvisionConfigsResponse listResp = fcClient.listProvisionConfigs( new ListProvisionConfigsRequest()); for (var pc : listResp.getProvisionConfigs()) { System.out.println(pc.getResource() + " target=" + pc.getTarget()); } ``` -------------------------------- ### Provision Config Management Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Configure pre-warmed function instances to reduce cold start latency. This includes setting a target number of instances to keep warm, retrieving the current provision configuration, and listing all provision configurations. ```APIDOC ## Provision Config — `putProvisionConfig` / `getProvisionConfig` / `listProvisionConfigs` Pre-warm a fixed number of function instances to eliminate cold starts. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // Keep 5 instances always warm for the PROD alias PutProvisionConfigRequest putReq = new PutProvisionConfigRequest( "my-service", "PROD", "my-function"); putReq.setTarget(5); PutProvisionConfigResponse putResp = fcClient.putProvisionConfig(putReq); System.out.println("Provisioned target: " + putResp.getProvisionTarget().getTarget()); // --- Get current provision config --- GetProvisionConfigRequest getReq = new GetProvisionConfigRequest( "my-service", "PROD", "my-function"); GetProvisionConfigResponse getResp = fcClient.getProvisionConfig(getReq); System.out.println("Current: " + getResp.getProvisionConfig().getCurrent() + " / Target: " + getResp.getProvisionConfig().getTarget()); // --- List all provision configs --- ListProvisionConfigsResponse listResp = fcClient.listProvisionConfigs( new ListProvisionConfigsRequest()); for (var pc : listResp.getProvisionConfigs()) { System.out.println(pc.getResource() + " target=" + pc.getTarget()); } ``` ``` -------------------------------- ### On-Demand Config Management Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Configure the maximum number of on-demand (burst) instances for a function qualifier. This allows for handling sudden traffic spikes by scaling beyond the provisioned instances. Operations include setting, getting, deleting, and listing these configurations. ```APIDOC ## On-Demand Config — `putOnDemandConfig` / `getOnDemandConfig` / `deleteOnDemandConfig` / `listOnDemandConfigs` Set the maximum number of on-demand (burst) instances for a function qualifier. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; PutOnDemandConfigRequest putReq = new PutOnDemandConfigRequest( "my-service", "PROD", "my-function"); putReq.setMaximumInstanceCount(100); PutOnDemandConfigResponse putResp = fcClient.putOnDemandConfig(putReq); System.out.println("Max instances: " + putResp.getOnDemandConfigMetadata().getMaximumInstanceCount()); // --- Get --- GetOnDemandConfigResponse getResp = fcClient.getOnDemandConfig( new GetOnDemandConfigRequest("my-service", "PROD", "my-function")); System.out.println("Current max: " + getResp.getOnDemandConfigMetadata().getMaximumInstanceCount()); // --- Delete --- fcClient.deleteOnDemandConfig( new DeleteOnDemandConfigRequest("my-service", "PROD", "my-function")); ``` ``` -------------------------------- ### Async Invocation Config Management Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Configure retry behavior and destinations for asynchronous function invocations. This allows for handling failed invocations by retrying them or routing them to specified destinations (e.g., dead-letter queues). Operations include setting, getting, listing, and deleting these configurations. ```APIDOC ## Async Invocation Config — `putFunctionAsyncConfig` / `getFunctionAsyncConfig` / `listFunctionAsyncConfigs` / `deleteFunctionAsyncConfig` Configure retry behavior and on-success/on-failure destinations for asynchronous function invocations. ```java import com.aliyuncs.fc.model.*; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // Route failed async calls to an MQ topic for dead-letter handling Destination onFailure = new Destination(); onFailure.setDestination("acs:mns:cn-shanghai:123456789:/queues/fc-dlq"); DestinationConfig destConfig = new DestinationConfig(); destConfig.setOnFailure(onFailure); AsyncConfig asyncConfig = new AsyncConfig(); asyncConfig.setMaxAsyncEventAgeInSeconds(86400); // 24 hours TTL asyncConfig.setMaxAsyncRetryAttempts(3); asyncConfig.setStatefulInvocation(true); asyncConfig.setDestinationConfig(destConfig); PutFunctionAsyncConfigRequest putReq = new PutFunctionAsyncConfigRequest( "my-service", "PROD", "my-function"); putReq.setAsyncConfig(asyncConfig); PutFunctionAsyncConfigResponse putResp = fcClient.putFunctionAsyncConfig(putReq); System.out.println("Async config created at: " + putResp.getAsyncConfig().getCreatedTime()); // --- Get --- GetFunctionAsyncConfigResponse getResp = fcClient.getFunctionAsyncConfig( new GetFunctionAsyncConfigRequest("my-service", "PROD", "my-function")); System.out.println("Max retries: " + getResp.getAsyncConfig().getMaxAsyncRetryAttempts()); ``` ``` -------------------------------- ### AsyncClient Initialization and Usage Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Illustrates how to initialize and use the non-blocking `AsyncClient` with custom configurations and callbacks. ```APIDOC ## AsyncClient Initialization Non-blocking client backed by a fixed thread pool; returns `Future` and accepts optional callbacks. ```java import com.aliyuncs.fc.client.AsyncClient; import com.aliyuncs.fc.client.FcCallback; import com.aliyuncs.fc.config.Config; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; import java.util.concurrent.Future; Config config = new Config("cn-shanghai", accountId, accessKey, secretKey, null, true); config.setThreadCount(4); // async thread pool size config.setMaxConnectCount(20); // HTTP connection pool max total config.setMaxPerRoute(4); // HTTP connection pool max per route try (AsyncClient asyncClient = new AsyncClient(config)) { InvokeFunctionRequest req = new InvokeFunctionRequest("my-service", "my-function"); req.setPayload("{\"key\":\"value\"}".getBytes()); Future future = asyncClient.invokeFunction(req, new FcCallback() { @Override public void onSuccess(InvokeFunctionRequest request, InvokeFunctionResponse response) { System.out.println("Result: " + new String(response.getContent())); } @Override public void onFailure(InvokeFunctionRequest request, Exception e) { e.printStackTrace(); } }); InvokeFunctionResponse response = future.get(); // block for result System.out.println("Status: " + response.getStatus()); } ``` ``` -------------------------------- ### FunctionComputeClient Initialization Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Demonstrates how to initialize the synchronous `FunctionComputeClient` using basic or advanced configuration options. ```APIDOC ## FunctionComputeClient Initialization The primary synchronous client; constructed with region, account ID, and access credentials or a full `Config` object. ```java import com.aliyuncs.fc.client.FunctionComputeClient; import com.aliyuncs.fc.config.Config; // Simple constructor (HTTP by default) FunctionComputeClient fcClient = new FunctionComputeClient( "cn-shanghai", // region System.getenv("ACCOUNT_ID"), // Alibaba Cloud account UID System.getenv("ACCESS_KEY"), // access key ID System.getenv("SECRET_KEY") // access key secret ); // Advanced constructor with HTTPS, STS token, and tuned timeouts Config config = new Config( "cn-shanghai", System.getenv("ACCOUNT_ID"), System.getenv("ACCESS_KEY"), System.getenv("SECRET_KEY"), System.getenv("STS_TOKEN"), // nullable security token for STS true // isHttps ); config.setConnectTimeoutMillis(5000); config.setReadTimeoutMillis(30000); config.setEndpoint("https://123456789.cn-shanghai.fc.aliyuncs.com"); // optional override FunctionComputeClient fcClient = new FunctionComputeClient(config); ``` ``` -------------------------------- ### Create and Manage Custom Domains with Routing and HTTPS Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Use this to map hostnames to Function Compute HTTP functions, configure routing rules, and enable HTTPS with custom certificates. Ensure the certificate and private key are correctly formatted. ```java import com.aliyuncs.fc.model.*; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // Route /api/* → my-service/api-function, everything else → my-service/default-function PathConfig routeA = new PathConfig(); routeA.setPath("/api/*"); routeA.setServiceName("my-service"); routeA.setFunctionName("api-function"); routeA.setQualifier("PROD"); PathConfig routeB = new PathConfig(); routeB.setPath("/*"); routeB.setServiceName("my-service"); routeB.setFunctionName("default-function"); RouteConfig routeConfig = new RouteConfig(); routeConfig.setRoutes(new PathConfig[]{routeA, routeB}); // HTTPS with a custom certificate CertConfig certConfig = new CertConfig(); certConfig.setCertName("my-cert"); certConfig.setCertificate("-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"); certConfig.setPrivateKey("-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"); TLSConfig tlsConfig = new TLSConfig(); tlsConfig.setMinVersion("TLSv1.2"); CreateCustomDomainRequest req = new CreateCustomDomainRequest(); req.setDomainName("api.example.com"); req.setProtocol("HTTPS"); req.setRouteConfig(routeConfig); req.setCertConfig(certConfig); req.setTlsConfig(tlsConfig); CreateCustomDomainResponse resp = fcClient.createCustomDomain(req); System.out.println("Domain created: " + resp.getCustomDomainMetadata().getDomainName()); // --- List --- ListCustomDomainsResponse listResp = fcClient.listCustomDomains(new ListCustomDomainsRequest()); for (var domain : listResp.getCustomDomains()) { System.out.println(domain.getDomainName() + " - " + domain.getProtocol()); } ``` -------------------------------- ### Publish Service Versions and Manage Aliases for Deployments Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Use this to create immutable snapshots of your service and manage aliases for phased rollouts or canary deployments. Ensure you have the correct service name and version IDs. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; import java.util.HashMap; import java.util.Map; // --- Publish a version --- PublishVersionRequest pubReq = new PublishVersionRequest("my-service"); pubReq.setDescription("Release 2.0"); PublishVersionResponse pubResp = fcClient.publishVersion(pubReq); String versionId = pubResp.getVersionMetaData().getVersionId(); System.out.println("Published version: " + versionId); // e.g. "3" // --- Create a stable alias pointing to the new version --- CreateAliasRequest aliasReq = new CreateAliasRequest("my-service", "PROD", versionId); aliasReq.setDescription("Production alias"); CreateAliasResponse aliasResp = fcClient.createAlias(aliasReq); System.out.println("Alias: " + aliasResp.getAliasMetaData().getAliasName()); // --- Canary: route 10% traffic to the new version, 90% to the previous one --- Map weights = new HashMap<>(); weights.put(versionId, 0.1f); // 10% to new version UpdateAliasRequest updateReq = new UpdateAliasRequest("my-service", "PROD"); updateReq.setVersionId("2"); // 90% to version 2 updateReq.setAdditionalVersionWeight(weights); fcClient.updateAlias(updateReq); // --- List versions --- ListVersionsRequest listVersionsReq = new ListVersionsRequest("my-service"); ListVersionsResponse listVersionsResp = fcClient.listVersions(listVersionsReq); for (var v : listVersionsResp.getVersions()) { System.out.println("v" + v.getVersionId() + ": " + v.getDescription()); } // --- List aliases --- ListAliasesResponse listAliasesResp = fcClient.listAliases(new ListAliasesRequest("my-service")); for (var a : listAliasesResp.getAliases()) { System.out.println(a.getAliasName() + " → v" + a.getVersionId()); } ``` -------------------------------- ### Initialize Synchronous FunctionComputeClient Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Initialize the primary synchronous client. Supports simple constructor with region and credentials, or an advanced constructor with a Config object for HTTPS, STS tokens, and custom timeouts. ```java import com.aliyuncs.fc.client.FunctionComputeClient; import com.aliyuncs.fc.config.Config; // Simple constructor (HTTP by default) FunctionComputeClient fcClient = new FunctionComputeClient( "cn-shanghai", // region System.getenv("ACCOUNT_ID"), // Alibaba Cloud account UID System.getenv("ACCESS_KEY"), // access key ID System.getenv("SECRET_KEY") // access key secret ); // Advanced constructor with HTTPS, STS token, and tuned timeouts Config config = new Config( "cn-shanghai", System.getenv("ACCOUNT_ID"), System.getenv("ACCESS_KEY"), System.getenv("SECRET_KEY"), System.getenv("STS_TOKEN"), // nullable security token for STS true // isHttps ); config.setConnectTimeoutMillis(5000); config.setReadTimeoutMillis(30000); config.setEndpoint("https://123456789.cn-shanghai.fc.aliyuncs.com"); // optional override FunctionComputeClient fcClient = new FunctionComputeClient(config); ``` -------------------------------- ### Create, List, and Delete VPC Bindings Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Manage VPC bindings for a service to allow functions to access private VPC resources. Ensure the service name and VPC ID are correctly specified. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // --- Create binding --- CreateVpcBindingRequest createReq = new CreateVpcBindingRequest("my-service"); createReq.setVpcId("vpc-uf6cxxxxxxxxxxxxxxxxx"); CreateVpcBindingResponse createResp = fcClient.createVpcBinding(createReq); System.out.println("Binding created, requestId=" + createResp.getRequestId()); // --- List bindings --- ListVpcBindingsRequest listReq = new ListVpcBindingsRequest("my-service"); ListVpcBindingsResponse listResp = fcClient.listVpcBindings(listReq); for (String vpcId : listResp.getVpcIds()) { System.out.println("Bound VPC: " + vpcId); } // --- Delete --- DeleteVpcBindingRequest delReq = new DeleteVpcBindingRequest("my-service", "vpc-uf6cxxxxxxxxxxxxxxxxx"); fcClient.deleteVpcBinding(delReq); ``` -------------------------------- ### Function Invocation Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Demonstrates how to invoke a function synchronously or asynchronously using the `invokeFunction` method. It also shows how to invoke a specific version or alias, and how to perform HTTP-style invocations. ```APIDOC ## Function Invocation — `invokeFunction` Invoke a function synchronously or asynchronously; supports payload, log capture, qualifiers, and HTTP-style invocation. ```java import com.aliyuncs.fc.constants.Const; import com.aliyuncs.fc.request.InvokeFunctionRequest; import com.aliyuncs.fc.request.HttpInvokeFunctionRequest; import com.aliyuncs.fc.response.InvokeFunctionResponse; import com.aliyuncs.fc.model.HttpMethod; import java.net.HttpURLConnection; // --- Sync invocation --- InvokeFunctionRequest syncReq = new InvokeFunctionRequest("my-service", "my-function"); syncReq.setPayload("{\"userId\":42}".getBytes()); syncReq.setLogType("Tail"); // return last 4KB of logs in response header InvokeFunctionResponse syncResp = fcClient.invokeFunction(syncReq); System.out.println("Output: " + new String(syncResp.getContent())); System.out.println("Status: " + syncResp.getStatus()); // 200 // --- Async invocation (fire-and-forget) --- InvokeFunctionRequest asyncReq = new InvokeFunctionRequest("my-service", "my-function"); asyncReq.setPayload("{\"task\":\"background-job\"}".getBytes()); asyncReq.setInvocationType(Const.INVOCATION_TYPE_ASYNC); InvokeFunctionResponse asyncResp = fcClient.invokeFunction(asyncReq); if (HttpURLConnection.HTTP_ACCEPTED == asyncResp.getStatus()) { System.out.println("Queued async job, requestId=" + asyncResp.getRequestId()); } // --- Invoke a specific version or alias --- InvokeFunctionRequest qualifiedReq = new InvokeFunctionRequest("my-service", "my-function"); qualifiedReq.setQualifier("PROD"); // alias or version number qualifiedReq.setPayload("hello".getBytes()); fcClient.invokeFunction(qualifiedReq); // --- HTTP trigger invocation --- HttpInvokeFunctionRequest httpReq = new HttpInvokeFunctionRequest( "my-service", "my-http-function", HttpMethod.POST, "/api/users"); httpReq.setHeader("Content-Type", "application/json"); httpReq.setPayload("{\"name\":\"Alice\"}".getBytes()); InvokeFunctionResponse httpResp = fcClient.invokeFunction(httpReq); System.out.println("HTTP response body: " + new String(httpResp.getContent())); ``` ``` -------------------------------- ### Manage Aliyun FC Triggers with Java SDK Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Create, list, and delete triggers for various event sources like Timer, OSS, and HTTP. For OSS triggers, configure filters based on object prefixes and suffixes. HTTP triggers support specifying allowed HTTP methods and authentication types. ```java import com.aliyuncs.fc.model.*; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // --- Create a Timer trigger --- TimeTriggerConfig timerConfig = new TimeTriggerConfig(); timerConfig.setCronExpression("@every 5m"); timerConfig.setEnable(true); timerConfig.setPayload("{\"scheduled\":true}"); CreateTriggerRequest timerReq = new CreateTriggerRequest("my-service", "my-function"); timerReq.setTriggerName("every-5-minutes"); timerReq.setTriggerType("timer"); timerReq.setTriggerConfig(timerConfig); CreateTriggerResponse timerResp = fcClient.createTrigger(timerReq); System.out.println("Trigger created: " + timerResp.getTriggerMetadata().getTriggerName()); // --- Create an OSS trigger --- OSSTriggerConfig ossConfig = new OSSTriggerConfig(); OSSTriggerFilter filter = new OSSTriggerFilter(); OSSTriggerKey key = new OSSTriggerKey(); key.setPrefix("uploads/"); key.setSuffix(".jpg"); filter.setKey(key); ossConfig.setFilter(filter); ossConfig.setEvents(new String[]{"oss:ObjectCreated:*"}); CreateTriggerRequest ossReq = new CreateTriggerRequest("my-service", "image-processor"); ossReq.setTriggerName("oss-image-upload"); ossReq.setTriggerType("oss"); ossReq.setSourceArn("acs:oss:cn-shanghai:123456789:my-bucket"); ossReq.setInvocationRole("acs:ram::123456789:role/oss-invoke-fc"); ossReq.setTriggerConfig(ossConfig); fcClient.createTrigger(ossReq); // --- Create an HTTP trigger --- HttpTriggerConfig httpConfig = new HttpTriggerConfig(); httpConfig.setMethods(new String[]{"GET", "POST"}); httpConfig.setAuthType(HttpAuthType.ANONYMOUS); CreateTriggerRequest httpReq = new CreateTriggerRequest("my-service", "my-http-function"); httpReq.setTriggerName("http-trigger"); httpReq.setTriggerType("http"); httpReq.setTriggerConfig(httpConfig); fcClient.createTrigger(httpReq); // --- List triggers --- ListTriggersRequest listReq = new ListTriggersRequest("my-service", "my-function"); ListTriggersResponse listResp = fcClient.listTriggers(listReq); for (var t : listResp.getTriggers()) { System.out.println(t.getTriggerName() + " (" + t.getTriggerType() + ")"); } // --- Delete --- fcClient.deleteTrigger(new DeleteTriggerRequest("my-service", "my-function", "every-5-minutes")); ``` -------------------------------- ### Add Maven Dependency for Aliyun Java SDK Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Include this dependency in your pom.xml to use the Aliyun Java SDK for Function Compute. ```xml com.aliyun aliyun-java-sdk-fc 1.8.37 ``` -------------------------------- ### Add Aliyun FC Java SDK Maven Dependency Source: https://github.com/aliyun/fc-java-sdk/blob/master/README.md Include this dependency in your pom.xml to use the Aliyun FC Java SDK. ```xml com.aliyun aliyun-java-sdk-fc 1.8.24 ``` -------------------------------- ### Manage Layers with Aliyun FC Java SDK Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Publish, retrieve, list, and delete layer versions. Layers package shared dependencies separately from function code and can be referenced by multiple functions. ```java import com.aliyuncs.fc.model.Code; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // Publish a layer from an OSS object Code layerCode = new Code(); layerCode.setOssBucketName("my-deps-bucket"); layerCode.setOssObjectName("layers/my-deps-v2.zip"); PublishLayerVersionRequest pubReq = new PublishLayerVersionRequest(); pubReq.setLayerName("my-common-deps"); pubReq.setDescription("Shared Python dependencies v2"); pubReq.setCompatibleRuntime(new String[]{"python3", "python3.9", "python3.10"}); pubReq.setCode(layerCode); PublishLayerVersionResponse pubResp = fcClient.publishLayerVersion(pubReq); String layerArn = pubResp.getLayerArn(); System.out.println("Layer ARN: " + layerArn); // Reference the layer in a function CreateFunctionRequest fnReq = new CreateFunctionRequest("my-service"); fnReq.setFunctionName("my-python-function"); fnReq.setRuntime("python3.9"); fnReq.setHandler("index.handler"); fnReq.setCode(new Code().setOssBucketName("my-bucket").setOssObjectName("fn.zip")); fnReq.setLayers(new String[]{layerArn}); fcClient.createFunction(fnReq); // --- List versions of a layer --- ListLayerVersionResponse listResp = fcClient.listLayerVersion( new ListLayerVersionRequest("my-common-deps")); for (var lv : listResp.getLayers()) { System.out.println("v" + lv.getVersion() + ": " + lv.getDescription()); } // --- Delete a specific layer version --- fcClient.deleteLayerVersion(new DeleteLayerVersionRequest("my-common-deps", 1)); ``` -------------------------------- ### Initialize Asynchronous AsyncClient Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Initialize the non-blocking client for asynchronous operations. It returns Futures and accepts callbacks. Configure thread pool size and connection pool settings via the Config object. ```java import com.aliyuncs.fc.client.AsyncClient; import com.aliyuncs.fc.client.FcCallback; import com.aliyuncs.fc.config.Config; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; import java.util.concurrent.Future; Config config = new Config("cn-shanghai", accountId, accessKey, secretKey, null, true); config.setThreadCount(4); // async thread pool size config.setMaxConnectCount(20); // HTTP connection pool max total config.setMaxPerRoute(4); // HTTP connection pool max per route try (AsyncClient asyncClient = new AsyncClient(config)) { InvokeFunctionRequest req = new InvokeFunctionRequest("my-service", "my-function"); req.setPayload("{\"key\":\"value\"}".getBytes()); Future future = asyncClient.invokeFunction(req, new FcCallback() { @Override public void onSuccess(InvokeFunctionRequest request, InvokeFunctionResponse response) { System.out.println("Result: " + new String(response.getContent())); } @Override public void onFailure(InvokeFunctionRequest request, Exception e) { e.printStackTrace(); } }); InvokeFunctionResponse response = future.get(); // block for result System.out.println("Status: " + response.getStatus()); } ``` -------------------------------- ### Create Node.js Function Code Directory and File Source: https://github.com/aliyun/fc-java-sdk/blob/master/README.md This bash script creates a directory and a Node.js file for a Function Compute function. The function includes an initializer and a handler. ```bash mkdir /tmp/fc_code cat < /tmp/fc_code/counter.js 'use strict'; var counter = 0; exports.initializer = function(ctx, callback) { ++counter; callback(null, ""); }; exports.handler = function(event, context, callback) { console.log('counter is %d', counter); callback(null, String(counter)); }; EOF ``` -------------------------------- ### Retrieve Account Settings Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Fetch account-level quotas and limits for the Function Compute service. This provides information on available resources and constraints for your account. ```java import com.aliyuncs.fc.request.GetAccountSettingsRequest; import com.aliyuncs.fc.response.GetAccountSettingsResponse; GetAccountSettingsResponse resp = fcClient.getAccountSettings(new GetAccountSettingsRequest()); System.out.println("Available memory (MB): " + resp.getAccountSettings().getAvailableAZs()); ``` -------------------------------- ### Manage Resource Tags with Java SDK Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Attach key-value metadata tags to Function Compute services for billing, access control, and organization using `tagResource`, `untagResource`, and `getResourceTags`. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; import java.util.HashMap; import java.util.Map; String serviceArn = "acs:fc:cn-shanghai:123456789:services/my-service"; // --- Tag --- Map tags = new HashMap<>(); tags.put("env", "production"); tags.put("team", "backend"); tags.put("cost-center", "engineering"); TagResourceRequest tagReq = new TagResourceRequest(); tagReq.setResourceArn(serviceArn); tagReq.setTags(tags); fcClient.tagResource(tagReq); // --- Get tags --- GetResourceTagsRequest getReq = new GetResourceTagsRequest(); getReq.setResourceArn(serviceArn); GetResourceTagsResponse getResp = fcClient.getResourceTags(getReq); getResp.getTagMetadata().getTags().forEach( (k, v) -> System.out.println(k + "=" + v)); // --- Untag --- UntagResourceRequest untagReq = new UntagResourceRequest(); untagReq.setResourceArn(serviceArn); untagReq.setTagKeys(new String[]{"cost-center"}); fcClient.untagResource(untagReq); ``` -------------------------------- ### Generate Signed URL for Function Invocation Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Create a pre-signed URL for time-limited, credential-free invocation of an HTTP-triggered function. Configure the HTTP method, service, function, expiry, and optional path or endpoint. ```java import com.aliyuncs.fc.auth.SignURLConfig; import com.aliyuncs.fc.model.HttpMethod; import java.util.Date; // URL valid for 10 minutes Date expiry = new Date(System.currentTimeMillis() + 10 * 60 * 1000); SignURLConfig signConfig = new SignURLConfig( HttpMethod.GET, "my-service", "my-http-function", expiry ); signConfig.setQualifier("PROD"); // optional alias/version signConfig.setEscapedPath("/report/download"); // path appended to proxy URL // signConfig.setCustomEndpoint("https://api.example.com"); // custom domain String signedUrl = fcClient.SignURL(signConfig); System.out.println("Signed URL: " + signedUrl); // Output: https://123456789.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/my-service.PROD/my-http-function/report/download?... ``` -------------------------------- ### Retrieve Account Settings Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Retrieve account-level quotas and limits for the Function Compute service. ```APIDOC ## Account Settings — `getAccountSettings` Retrieve account-level quotas and limits for the Function Compute service. ```java import com.aliyuncs.fc.request.GetAccountSettingsRequest; import com.aliyuncs.fc.response.GetAccountSettingsResponse; GetAccountSettingsResponse resp = fcClient.getAccountSettings(new GetAccountSettingsRequest()); System.out.println("Available memory (MB): " + resp.getAccountSettings().getAvailableAZs()); ``` ``` -------------------------------- ### Manage Function Async Invocation Config Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Configure retry behavior and destinations for asynchronous invocations. `putFunctionAsyncConfig` sets these parameters, `getFunctionAsyncConfig` retrieves them, `listFunctionAsyncConfigs` lists all, and `deleteFunctionAsyncConfig` removes the configuration. ```java import com.aliyuncs.fc.model.*; import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // Route failed async calls to an MQ topic for dead-letter handling Destination onFailure = new Destination(); onFailure.setDestination("acs:mns:cn-shanghai:123456789:/queues/fc-dlq"); DestinationConfig destConfig = new DestinationConfig(); destConfig.setOnFailure(onFailure); AsyncConfig asyncConfig = new AsyncConfig(); asyncConfig.setMaxAsyncEventAgeInSeconds(86400); // 24 hours TTL asyncConfig.setMaxAsyncRetryAttempts(3); asyncConfig.setStatefulInvocation(true); asyncConfig.setDestinationConfig(destConfig); PutFunctionAsyncConfigRequest putReq = new PutFunctionAsyncConfigRequest( "my-service", "PROD", "my-function"); putReq.setAsyncConfig(asyncConfig); PutFunctionAsyncConfigResponse putResp = fcClient.putFunctionAsyncConfig(putReq); System.out.println("Async config created at: " + putResp.getAsyncConfig().getCreatedTime()); // --- Get --- GetFunctionAsyncConfigResponse getResp = fcClient.getFunctionAsyncConfig( new GetFunctionAsyncConfigRequest("my-service", "PROD", "my-function")); System.out.println("Max retries: " + getResp.getAsyncConfig().getMaxAsyncRetryAttempts()); ``` -------------------------------- ### Manage Function On-Demand Config Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Configure the maximum number of on-demand instances for a function qualifier using `putOnDemandConfig`. `getOnDemandConfig` retrieves the current maximum, and `deleteOnDemandConfig` removes the setting. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; PutOnDemandConfigRequest putReq = new PutOnDemandConfigRequest( "my-service", "PROD", "my-function"); putReq.setMaximumInstanceCount(100); PutOnDemandConfigResponse putResp = fcClient.putOnDemandConfig(putReq); System.out.println("Max instances: " + putResp.getOnDemandConfigMetadata().getMaximumInstanceCount()); // --- Get --- GetOnDemandConfigResponse getResp = fcClient.getOnDemandConfig( new GetOnDemandConfigRequest("my-service", "PROD", "my-function")); System.out.println("Current max: " + getResp.getOnDemandConfigMetadata().getMaximumInstanceCount()); // --- Delete --- fcClient.deleteOnDemandConfig( new DeleteOnDemandConfigRequest("my-service", "PROD", "my-function")); ``` -------------------------------- ### Stateful Async Invocations Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Manage and track individual stateful asynchronous invocation instances. This allows for better control and monitoring of long-running or stateful operations. ```APIDOC ## Stateful Async Invocations — `getStatefulAsyncInvocation` / `listStatefulAsyncInvocations` / `stopStatefulAsyncInvocation` ### Description Track and control individual stateful async invocation instances when `statefulInvocation` is enabled. ### Method - `invokeFunction` (with `setStatefulAsyncInvocationId`) - `getStatefulAsyncInvocation` - `listStatefulAsyncInvocations` - `stopStatefulAsyncInvocation` ### Parameters #### `InvokeFunctionRequest` (for invoking) - **statefulAsyncInvocationId** (string) - Optional - A custom ID to track the stateful invocation. - **payload** (byte[]) - Required - The input payload for the function. #### `GetStatefulAsyncInvocationRequest` - **serviceName** (string) - Required - The name of the service. - **functionName** (string) - Required - The name of the function. - **statefulInvocationId** (string) - Required - The ID of the stateful invocation to retrieve. #### `ListStatefulAsyncInvocationsRequest` - **serviceName** (string) - Required - The name of the service. - **functionName** (string) - Required - The name of the function. - **limit** (int) - Optional - The maximum number of invocations to return. #### `StopStatefulAsyncInvocationRequest` - **serviceName** (string) - Required - The name of the service. - **functionName** (string) - Required - The name of the function. - **statefulInvocationId** (string) - Required - The ID of the stateful invocation to stop. ### Response #### `GetStatefulAsyncInvocationResponse` (Success Response) - **statefulAsyncInvocation.status** (string) - The current status of the invocation (e.g., ENQUEUED, RUNNING, SUCCEEDED, FAILED, STOPPED, INVALID_STATE). #### `ListStatefulAsyncInvocationsResponse` (Success Response) - **invocations** (List) - A list of stateful invocation objects, each containing `invocationId` and `status`. ``` -------------------------------- ### VPC Bindings Management Source: https://context7.com/aliyun/fc-java-sdk/llms.txt Manage VPC bindings for services to allow functions to access private VPC resources. Includes creating, listing, and deleting VPC bindings. ```APIDOC ## VPC Bindings — `createVpcBinding` / `listVpcBindings` / `deleteVpcBinding` Bind a VPC to a service so that functions within it can access private VPC resources. ```java import com.aliyuncs.fc.request.*; import com.aliyuncs.fc.response.*; // --- Create binding --- CreateVpcBindingRequest createReq = new CreateVpcBindingRequest("my-service"); createReq.setVpcId("vpc-uf6cxxxxxxxxxxxxxxxxx"); CreateVpcBindingResponse createResp = fcClient.createVpcBinding(createReq); System.out.println("Binding created, requestId=" + createResp.getRequestId()); // --- List bindings --- ListVpcBindingsRequest listReq = new ListVpcBindingsRequest("my-service"); ListVpcBindingsResponse listResp = fcClient.listVpcBindings(listReq); for (String vpcId : listResp.getVpcIds()) { System.out.println("Bound VPC: " + vpcId); } // --- Delete --- DeleteVpcBindingRequest delReq = new DeleteVpcBindingRequest("my-service", "vpc-uf6cxxxxxxxxxxxxxxxxx"); fcClient.deleteVpcBinding(delReq); ``` ```