Todos os produtos
Search
Central de documentação

:Otimização de pipeline: Use o plug-in de cache do OSS para acelerar a compilação de dependências

Última atualização: Jul 04, 2026

A cada execução de uma tarefa de pipeline, uma nova instância é provisionada. É necessário obter o código para compilação e instalar as dependências exigidas. Quando a obtenção dessas dependências consome muito tempo, a execução da tarefa pode ficar lenta ou atingir o tempo limite. A comunidade Serverless-cd disponibiliza um plug-in de cache baseado no Object Storage Service (OSS) para solucionar problemas como lentidão na obtenção de dependências e timeouts de compilação. Este tópico descreve como utilizar o plug-in de cache do OSS para acelerar a compilação de dependências.

Método de uso do plug-in de cache

A comunidade Serverless-cd oferece um plug-in de cache otimizado para os recursos do Serverless Application Center. Ao utilizar esse plug-in, basta especificar o bucket do OSS destinado ao cache. Com base nas chaves definidas, o plug-in recupera, lê e atualiza os dados armazenados no bucket do OSS especificado ou no bucket padrão.

Caso uma chave de cache seja encontrada durante a execução do plug-in, o arquivo correspondente será baixado para um diretório local específico.

Após a execução do mecanismo, os arquivos presentes no diretório local são enviados para o bucket do OSS.

Defina o cache do OSS no contexto de execução

É possível definir as configurações de cache do OSS no contexto de execução dentro de um pipeline, modelo de pipeline ou modelo de tarefa. Exemplo de código:

---
# Submit the pipeline for execution.
kind: Pipeline
name: "p-<% .git.shortCommitId %>-<% .currentTimestampMs %>"
# The description.
description: cached pipeline
spec:
  context:
    data:
      # The cache configuration of Serverless Application Center. If you leave this section empty, the engine is automatically initialized in the region where the task node is scheduled.
      # The default bucket name is serverless-cd-cache-${region-id}-<% .accountId %>. 
      cacheConfig:
        # Specify to use OSS for caching. If you leave this section empty, the platform automatically performs the initialization.
        # We recommend that you use the platform to automatically perform the initialization, because the worker nodes may be scheduled to a region that is different from the region in which the specified OSS bucket resides.
        # For code repositories on GitHub, the worker nodes and corresponding OSS buckets reside in the Singapore region (ap-southeast-1).
        # For code repositories on GitLab, Codeup, and Gitee, the worker nodes and the corresponding OSS buckets reside in the China (Hangzhou) region (cn-hangzhou).
        oss:
          # The name of the bucket that is used for caching. If the bucket does not exist, the engine does not automatically perform the initialization.
          bucketName: serverless-cd-cache-ap-southeast-1-<% .accountId %>
          # The region where the bucket resides. We recommend that you do not pull data from a cache that reside in another region.
          regionId: ap-southeast-1
  templateName: mytemplate-<% .git.branch %>
---

Utilize o plug-in de cache nas etapas

Para usar o plug-in de cache, execute as etapas de contexto em um modelo de pipeline ou modelo de tarefa. Não é necessário especificar credentials, pois o plug-in utiliza automaticamente as permissões de função concedidas ao Serverless Application Center. Exemplo de código:

---
kind: PipelineTemplate
name: mytemplate-<% .git.branch %>
description: cached pipelinetemplate
spec:
  context:
    data:
      envName: test
      deployFile: s.yaml
  tasks:
  # Perform a pre-build check.
  - name: pre-check
    context:
      data:
        displayName: "Pre-build check"
        enable: true
        steps:
          - plugin: "@serverless-cd/checkout"
          - plugin: "@serverless-cd/s-setup"
          - run: s plan --local -o json
    taskTemplate: serverless-runner-task
    runAfters: []
  - name: pre-check-approval
    context:
      data:
        dingdingNotification:
          enable: false
        enable: true
    taskTemplate: need-approval
    runAfters:
    - name: pre-check
  # Build and deploy
  - name: build-and-deploy
    context:
      data:
        enable: true
        steps:
          - plugin: "@serverless-cd/checkout"
          - plugin: "@serverless-cd/s-setup"
          - plugin: "@serverless-cd/cache"
            inputs:
              # Define a unique identifier for the cache, which can be associated with related information, such as the application information or Git version information.
              # You can also use "cache-${{hashFile('./package.json')}}".
              # Calculate the unique identifier of the cache based on the hash value of the on-premises file.
              # The path of the cached object in the bucket is cache-home/${key}.
              # In this example, the cache path in the bucket is cache-home/cache-<% .appName %>.
              key: "cache-<% .appName %>"
              # Configure the cache path as required by the current build tool.
              # For example, for a Node.js runtime, you can use the default value ~/.npm as the path of the pipeline application cache.
              path: ~/.npm
          # Run s-deploy.
          - run: |
              set -e
              s deploy -t --use-local --assume-yes --skip-push
              echo "Deploy by Serverless Devs success."
    taskTemplate: serverless-runner-task
    runAfters:
    - name: pre-check-approval
---

Caminho do cache

O caminho real do cache varia conforme a ferramenta de compilação utilizada. A tabela a seguir lista os caminhos padrão para as ferramentas mais comuns. Consulte também a documentação específica da sua ferramenta de compilação para verificar o caminho correto.

Ferramenta

Caminho do cache

Maven

~/.m2

Gradle

~/.gradle

NPM

~/.npm

Yarn

~/.yarn

gomod

$GOPATH/pkg/mod

Outros caches (como pip3)

~/.cache

Cache local

Se o serviço de compilação de dependências apresentar baixo desempenho ou se restrições de segurança impedirem a obtenção de dependências diretamente da nuvem, utilize o ossutils para criar um cache local. Nesse cenário, armazene os dados em cache no dispositivo de desenvolvimento local e faça o upload para o OSS. O cache enviado poderá então ser utilizado nos pipelines.

Alternativamente, acesse o console do OSS e envie manualmente o cache local, como o diretório ~/.npm, para um bucket do OSS.

Exemplo de código:

# Use ossutils to create a cache for cloud-based build. Copy the on-premises npm cache to an OSS bucket.
# The automatically created bucket, whose URL is serverless-cd-${region-id}-cache-${uid}.oss-${region-id}.aliyuncs.com.
# For code repositories on GitHub, the worker nodes and corresponding OSS buckets must be deployed in the Singapore region (ap-southeast-1).
# For code repositories on GitLab, Codeup, and Gitee, worker nodes and corresponding OSS buckets must be deployed in the China (Hangzhou) region (cn-hangzhou).
./ossutil64 cp -r ~/.npm oss://${bucket_url}/cache-home/${cache_key}