Todos los productos
Search
Centro de documentos

Elastic Compute Service:Handle spot instance interruptions with SMQ

Última actualización: Sep 02, 2026

Utilice Simple Message Queue (anteriormente MNS) para recibir notificaciones de interrupción de instancias spot y ejecutar la lógica de apagado ordenado antes de que se reclame la instancia.

Descripción general del flujo de trabajo

image

Requisitos previos

  1. Crear un accesskey

    Utilice el accesskey de un usuario de RAM con los permisos mínimos obligatorios en lugar de la cuenta raíz. Consulte Create an AccessKey.

  2. Otorgar permisos al usuario de RAM

    Otorgue al usuario de RAM el siguiente permiso para consumir mensajes de Simple Message Queue (MNS):

    Productos en la nube

    Permisos a otorgar

    Simple Message Queue (SMQ, anteriormente MNS)

    AliyunMNSFullAccess

  3. Configurar las credenciales de acceso y el endpoint

    El código de ejemplo lee las credenciales de acceso y el endpoint desde variables de entorno.

  4. Instalar el SDK de SMQ

    Instale el SDK de Java para SMQ mediante una dependencia de Maven. Para otros métodos, consulte Instalación del SDK de SMQ.

    Agregue la siguiente dependencia de Maven:

    <dependencies>
        <!-- Alibaba Cloud Simple Message Queue SDK -->
        <dependency>
          <groupId>com.aliyun.mns</groupId>
          <artifactId>aliyun-sdk-mns</artifactId>
          <version>1.2.0</version>
        </dependency>
    </dependencies>

Procedimiento

  1. Crear una cola en Simple Message Queue

    Cree una cola para recibir las notificaciones de interrupción de instancias spot.

    1. Inicie sesión en la consola de Simple Message Queue (anteriormente MNS). En el panel de navegación izquierdo, seleccione Queue Model > Queues.

    2. En la barra de menú superior, seleccione una región. En la página Queues, haga clic en Create Queue.

    3. En el panel Create Queue, configure los parámetros y haga clic en OK.

      Los parámetros de configuración incluyen:

      • Name: nombre de la cola, con un máximo de 120 caracteres.

      • Maximum Message Size: valor predeterminado de 64 KB.

      • Long Polling Wait Time: valor predeterminado de 15 segundos.

      • Message Visibility Timeout: valor predeterminado de 30 segundos.

      • Message Retention Period: valor predeterminado de 4 días.

      • Message Receive Delay: valor predeterminado de 0 segundos.

      • Enable Logging: valor predeterminado deshabilitado.

      • Dead-Letter Policy: valor predeterminado deshabilitado.

  2. Crear una directiva de suscripción

    Cloud Monitor envía las notificaciones de interrupción de instancias spot a través del canal de envío especificado en la directiva de suscripción.

    1. Inicie sesión en la consola de Cloud Monitor. En el panel de navegación izquierdo, seleccione Event Hub > Event Subscriptions.

    2. En la pestaña Subscription Policies, haga clic en Create Subscription Policy. Haga clic en Next y configure los parámetros.

      Aquí solo se describen los parámetros clave. Para consultar otros parámetros, vea Manage event subscriptions (recommended).

      • Subscription Type: seleccione System Events.

      • Subscription Scope: configure los siguientes parámetros:

        • Product: seleccione Elastic Compute Service.

        • Event Type: seleccione Status Notification.

        • Event Name: seleccione Spot Instance Interruption Notification.

        • Event Level: seleccione Warning.

      • Push and Integration: haga clic en + Add Channel > Add Channel, seleccione la cola creada en el paso 1 y complete los campos restantes. Consulte Manage Push Channels.

  3. Simular un evento de interrupción

    Utilice Test Event Subscription para simular un evento de interrupción, ya que las interrupciones de instancias spot se desencadenan de forma pasiva y resultan difíciles de reproducir durante el desarrollo.

    1. En la pestaña Subscription Policies, haga clic en Test Event Subscription.

    2. En el panel Create Event Debugging, establezca Service en ECS y Name en Spot Instance Interruption Notification.

      El sistema genera contenido JSON de depuración. Reemplace los campos relacionados con recursos por la información de su instancia spot.

      • Reemplace Alibaba Cloud account UID con el UID de su cuenta.

      • Reemplace <resource-id> y <instanceId> con el ID de su instancia spot.

      • Reemplace <region-id> con el ID de región de su instancia spot.

        {
            "product": "ECS",
            "resourceId": "acs:ecs:cn-shanghai:Alibaba Cloud account UID:instance/<resource-id>",
            "level": "WARN",
            "instanceName": "instanceName",
            "regionId": "<region-id>",
            "groupId": "0",
            "name": "Instance:PreemptibleInstanceInterruption",
            "content": {
                "instanceId": "<instanceId>",
                "instanceName": "wor***b73",
                "action": "delete"
            },
            "status": "Normal"
        }
    3. Haga clic en OK. El sistema muestra The operation is successful. y Cloud Monitor envía una notificación de prueba a su cola.

  4. Extraer mensajes y responder a ellos

    Extraiga las notificaciones de interrupción de la cola y responda con lógica personalizada. El siguiente código de ejemplo muestra cómo gestionar un evento de interrupción mediante un programa de conversión de imágenes a escala de grises:

    1. Utilice una tarea de hilo para simular el programa de conversión de imágenes.

      import com.aliyun.mns.client.CloudAccount;
      import com.aliyun.mns.client.CloudQueue;
      import com.aliyun.mns.client.MNSClient;
      import com.aliyun.mns.common.utils.ServiceSettings;
      import com.aliyun.mns.model.Message;
      import org.json.JSONObject;
      
      import javax.imageio.ImageIO;
      import java.awt.image.BufferedImage;
      import java.io.File;
      import java.util.Base64;
      import java.util.concurrent.atomic.AtomicBoolean;
      
      /**
       * Interruptible image processor that supports grayscale conversion.
       * Uses atomic variables and thread interruption flags for detection.
       * Features:
       * 1. Chunked processing with automatic progress saving
       * 2. Immediate response to spot instance interruption
       * 3. Partial result file generation after interruption
       */
      public class InterruptibleImageProcessor implements Runnable {
          /**
           * Thread-safe state control using an atomic Boolean
           */
          private final AtomicBoolean running = new AtomicBoolean(true);
          /**
           * Stores image data being processed
           */
          private BufferedImage processedImage;
          /**
           * Processing progress percentage (0–100)
           */
          private int progress;
          /**
           * Thread entry point
           * **Interruption logic**:
           * 1. Save current progress after catching InterruptedException
           * 2. Restore thread interruption status (preserve semantics)
           */
          @Override
          public void run() {
              try {
                  convertToGrayScale(new File("input.jpg"), new File("output.jpg"));
                  // Simulate post-processing delay
                  Thread.sleep(5000); 
                  System.out.println("Image processing completed");
              } catch (InterruptedException e) {
                  System.out.println("Processing interrupted. Progress saved at " + progress + "%");
                  saveProgress(new File("partial_output.jpg"));
                  Thread.currentThread().interrupt(); // Restore interruption status
              } catch (Exception e) {
                  System.err.println("Processing error: " + e.getMessage());
              }
          }
      
          /**
           * External interruption trigger method
           * **Coordination mechanism**:
           * Works with thread interruption flag for dual detection
           */
          public void stop() {
              running.set(false);
          }
      }
      
    2. Método de conversión de imagen a escala de grises.

      /**
       * Convert input image to grayscale and save
       * @param inputFile Source image file object
       * @param outputFile Output file object
       * @throws Exception Includes I/O and interruption exceptions
       *
       * **Algorithm**:
       * Weighted average grayscale conversion matching human luminance perception:
       * Gray = 0.30*R + 0.59*G + 0.11*B
       * Reference: ITU-R BT.601 standard
       */
      public void convertToGrayScale(File inputFile, File outputFile) throws Exception {
          // Read source image
          BufferedImage original = ImageIO.read(inputFile);
          int width = original.getWidth();
          int height = original.getHeight();
          // Create grayscale image buffer
          processedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
      
          // Process in chunks to support progress saving
          for (int y = 0; y < height && running.get(); y++) {
              // Process pixel by pixel
              for (int x = 0; x < width; x++) {
                  // First interruption check: thread interruption flag
                  if (Thread.interrupted()) {
                      throw new InterruptedException("Image processing interrupted");
                  }
                  /* Core grayscale algorithm */
                  int rgb = original.getRGB(x, y);
                  // Extract RGB channels (ARGB format)
                  // Red channel
                  int r = (rgb >> 16) & 0xFF;
                  // Green channel
                  int g = (rgb >> 8) & 0xFF;
                  // Blue channel
                  int b = rgb & 0xFF;
                  // Calculate grayscale value (weighted average)
                  int gray = (int)(0.3 * r + 0.59 * g + 0.11 * b);
                  // Reconstruct RGB (grayscale value replicated across channels)
                  processedImage.setRGB(x, y, (gray << 16) | (gray << 8) | gray);
                  // Update progress percentage (watch for integer division)
                  progress = (y * width + x) * 100 / (width * height);
              }
              // Auto-save progress every 50 rows (checkpoint mechanism)
              if (y % 50 == 0) {
                  saveProgress(outputFile);
              }
          }
          // Save final result
          ImageIO.write(processedImage, "jpg", outputFile);
      }
    3. Guarde el progreso del procesamiento de la imagen.

      /**
       * Save processing progress to specified file
       * @param outputFile Output file object
       *
       * **Note**:
       * 1. Uses silent failure to avoid interrupting save process
       * 2. Generates temporary file named partial_output.jpg
       */
      private void saveProgress(File outputFile) {
          try {
              // Use temporary filename to avoid overwriting final file
              ImageIO.write(processedImage, "jpg", new File("partial_output.jpg"));
          } catch (Exception e) {
              System.err.println("Auto-save failed: " + e.getMessage());
          }
      }
    4. Pruebe la gestión de respuestas.

      Pruebe el procesador de imágenes para detectar y responder a una interrupción de instancia spot durante la ejecución.

      /**
       * Main method (for testing)
       * **Test scenario**:
       * 1. Start processing thread
       * 2. Pull interruption notification message
       * 3. Wait for thread termination
       */
      public static void main(String[] args) throws InterruptedException {
          // Initialize MNS client
          CloudAccount account = new CloudAccount(
                  ServiceSettings.getMNSAccessKeyId(),
                  ServiceSettings.getMNSAccessKeySecret(),
                  ServiceSettings.getMNSAccountEndpoint());
          MNSClient client = account.getMNSClient();
          // Check if message matches spot instance interruption event
          boolean isMatch = false;
          // Start image processor
          InterruptibleImageProcessor processor = new InterruptibleImageProcessor();
          Thread processThread = new Thread(processor);
          processThread.start();
          try{
              // Pull message from queue
              CloudQueue queue = client.getQueueRef("spot-interruption");
              Message popMsg = queue.popMessage();
              if (popMsg != null){
                  // Message body is Base64-encoded by default
                  System.out.println("message body: " + popMsg.getMessageBodyAsRawString());
                  // Base64 decode
                  byte[] decodedBytes = Base64.getDecoder().decode(popMsg.getMessageBodyAsRawString());
                  String decodedString = new String(decodedBytes);
                  System.out.println("message content: " + decodedString);
                  // Parse JSON string
                  JSONObject json = new JSONObject(decodedString);
                  // Get event name from "name" field
                  String name = json.getString("name");
                  isMatch = "Instance:PreemptibleInstanceInterruption".equals(name);
                  // Handle spot instance interruption event
                  if(isMatch){
                      System.out.println("Spot instance will be interrupted and reclaimed");
                      // Stop image processor
                      processor.stop();
                      processThread.interrupt();
                      System.out.println("Program terminated");
                      processThread.join();
                      // Delete message
                      queue.deleteMessage(popMsg.getReceiptHandle());
                  }
              }
          }catch (Exception e){
              System.out.println("Unknown exception happened!");
              e.printStackTrace();
          }
          client.close();
      }

    Código de ejemplo completo:

    import com.aliyun.mns.client.CloudAccount;
    import com.aliyun.mns.client.CloudQueue;
    import com.aliyun.mns.client.MNSClient;
    import com.aliyun.mns.common.utils.ServiceSettings;
    import com.aliyun.mns.model.Message;
    import org.json.JSONObject;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.Base64;
    import java.util.concurrent.atomic.AtomicBoolean;
    
    /**
     * Interruptible image processor that supports grayscale conversion.
     * Uses atomic variables and thread interruption flags for detection.
     * Features:
     * 1. Chunked processing with automatic progress saving
     * 2. Immediate response to spot instance interruption
     * 3. Partial result file generation after interruption
     */
    public class InterruptibleImageProcessor implements Runnable {
        /**
         * Thread-safe state control using an atomic Boolean
         */
        private final AtomicBoolean running = new AtomicBoolean(true);
        /**
         * Stores image data being processed
         */
        private BufferedImage processedImage;
        /**
         * Processing progress percentage (0–100)
         */
        private int progress;
    
        /**
         * Convert input image to grayscale and save
         * @param inputFile Source image file object
         * @param outputFile Output file object
         * @throws Exception Includes I/O and interruption exceptions
         *
         * **Algorithm**:
         * Weighted average grayscale conversion matching human luminance perception:
         * Gray = 0.30*R + 0.59*G + 0.11*B
         * Reference: ITU-R BT.601 standard
         */
        public void convertToGrayScale(File inputFile, File outputFile) throws Exception {
            // Read source image
            BufferedImage original = ImageIO.read(inputFile);
            int width = original.getWidth();
            int height = original.getHeight();
            // Create grayscale image buffer
            processedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    
            // Process in chunks to support progress saving
            for (int y = 0; y < height && running.get(); y++) {
                // Process pixel by pixel
                for (int x = 0; x < width; x++) {
                    // First interruption check: thread interruption flag
                    if (Thread.interrupted()) {
                        throw new InterruptedException("Image processing interrupted");
                    }
                    /* Core grayscale algorithm */
                    int rgb = original.getRGB(x, y);
                    // Extract RGB channels (ARGB format)
                    // Red channel
                    int r = (rgb >> 16) & 0xFF;
                    // Green channel
                    int g = (rgb >> 8) & 0xFF;
                    // Blue channel
                    int b = rgb & 0xFF;
                    // Calculate grayscale value (weighted average)
                    int gray = (int)(0.3 * r + 0.59 * g + 0.11 * b);
                    // Reconstruct RGB (grayscale value replicated across channels)
                    processedImage.setRGB(x, y, (gray << 16) | (gray << 8) | gray);
                    // Update progress percentage (watch for integer division)
                    progress = (y * width + x) * 100 / (width * height);
                }
                // Auto-save progress every 50 rows (checkpoint mechanism)
                if (y % 50 == 0) {
                    saveProgress(outputFile);
                }
            }
            // Save final result
            ImageIO.write(processedImage, "jpg", outputFile);
        }
    
        /**
         * Save processing progress to specified file
         * @param outputFile Output file object
         *
         * **Note**:
         * 1. Uses silent failure to avoid interrupting save process
         * 2. Generates temporary file named partial_output.jpg
         */
        private void saveProgress(File outputFile) {
            try {
                // Use temporary filename to avoid overwriting final file
                ImageIO.write(processedImage, "jpg", new File("partial_output.jpg"));
            } catch (Exception e) {
                System.err.println("Auto-save failed: " + e.getMessage());
            }
        }
    
        /**
         * Thread entry point
         * **Interruption logic**:
         * 1. Save current progress after catching InterruptedException
         * 2. Restore thread interruption status (preserve semantics)
         */
        @Override
        public void run() {
            try {
                convertToGrayScale(new File("/Users/shaoberlin/Desktop/idea_workspace/aliyun/src/main/resources/input.jpg"), new File("output.jpg"));
                // Simulate post-processing delay
                Thread.sleep(5000); 
                System.out.println("Image processing completed");
            } catch (InterruptedException e) {
                System.out.println("Processing interrupted. Progress saved at " + progress + "%");
                saveProgress(new File("partial_output.jpg"));
                Thread.currentThread().interrupt(); // Restore interruption status
            } catch (Exception e) {
                System.err.println("Processing error: " + e.getMessage());
            }
        }
    
        /**
         * External interruption trigger method
         * **Coordination mechanism**:
         * Works with thread interruption flag for dual detection
         */
        public void stop() {
            running.set(false);
        }
    
        /**
         * Main method (for testing)
         * **Test scenario**:
         * 1. Start processing thread
         * 2. Trigger interruption after 5000 ms
         * 3. Wait for thread termination
         */
        public static void main(String[] args) throws InterruptedException {
            // Initialize MNS client
            CloudAccount account = new CloudAccount(
                    ServiceSettings.getMNSAccessKeyId(),
                    ServiceSettings.getMNSAccessKeySecret(),
                    ServiceSettings.getMNSAccountEndpoint());
            MNSClient client = account.getMNSClient();
            // Check if message matches spot instance interruption event
            boolean isMatch = false;
            // Start image processor
            InterruptibleImageProcessor processor = new InterruptibleImageProcessor();
            Thread processThread = new Thread(processor);
            processThread.start();
            try{
                // Pull message from queue
                CloudQueue queue = client.getQueueRef("spot-interruption");
                Message popMsg = queue.popMessage();
                if (popMsg != null){
                    // Message body is Base64-encoded by default
                    System.out.println("message body: " + popMsg.getMessageBodyAsRawString());
                    // Base64 decode
                    byte[] decodedBytes = Base64.getDecoder().decode(popMsg.getMessageBodyAsRawString());
                    String decodedString = new String(decodedBytes);
                    System.out.println("message content: " + decodedString);
                    // Parse JSON string
                    JSONObject json = new JSONObject(decodedString);
                    // Get event name from "name" field
                    String name = json.getString("name");
                    isMatch = "Instance:PreemptibleInstanceInterruption".equals(name);
                    // Handle spot instance interruption event
                    if(isMatch){
                        System.out.println("Spot instance will be interrupted and reclaimed");
                        // Stop image processor
                        processor.stop();
                        processThread.interrupt();
                        System.out.println("Program terminated");
                        processThread.join();
                        // Delete message
                        queue.deleteMessage(popMsg.getReceiptHandle());
                    }
                }
            }catch (Exception e){
                System.out.println("Unknown exception happened!");
                e.printStackTrace();
            }
            client.close();
        }
    }
    
Nota

Referencias

Si su instancia spot almacena datos o configuraciones críticas, consulte Preserve and recover data for spot instances para evitar la pérdida de datos.