In Function Compute, you can use a function to call database APIs to insert or query data. In most cases, instance status is not shared among different execution environments in Function Compute. If you want to share instance status, you need to store structured data in a database. This topic describes how to deploy a function to access an ApsaraDB for Redis database by using Serverless Devs. Python 3 is used in this topic.

Prerequisites

Create an ApsaraDB for Redis instance

Important
  • Make sure that the database instance that you create is in the same region as the function that needs to access the database instance.

  • We recommend that you create the database instance in a zone that Function Compute supports. For more information about the message routing feature, see Zones where Function Compute is available.

    If your database instance is not deployed in a zone that is supported by Function Compute, create a vSwitch in your VPC. The vSwitch must be in the same zone as Function Compute. In addition, you must specify the vSwitch ID in the VPC configuration of the specified service in Function Compute. vSwitches in the same VPC can communicate with each other over the private network. Therefore, Function Compute can use the vSwitch to access resources in VPCs that reside in other zones. For more information, see How can I resolve the "vSwitch is in unsupported zone" error?.

Step 1: Configure the IP address whitelist for the database

Important Use an IP address whitelist to authorize functions to access the database. Do not use the security group mode. Otherwise, functions may occasionally fail to connect to the database, which affects the businesses.
  1. Log on to the ApsaraDB for Redis console.
  2. In the top navigation bar, select the region in which the instance is deployed.
  3. On the Instances page, find the instance and click its ID.
  4. In the left-side navigation pane, click Whitelist Settings.
  5. Find the desired whitelist group and click Modify.
    Important The IP address that you specify must belong to the CIDR block of the vSwitch that you want to add when you configure the network for Function Compute.
  6. Click Confirm.

Step 2: Deploy and invoke the function

  1. Install Serverless Devs and Docker and add a key.
    For more information, see Install Serverless Devs and Docker and Add a key.
  2. Initialize a project.
    s init start-fc-redis-python -d start-fc-redis-python
  3. Access the project.
    cd start-fc-redis-python
  4. Edit the s.yaml file.

    The following sample code provides a configuration example:

    edition: 1.0.0         
    name: fcDeployApp       
    access: "default"  
    
    services:
      fc-db-redis-python: 
        component: devsapp/fc  
        props: 
          region: cn-hangzhou
          service:
            name: fc-db-demo
            description: 'demo for fc visit db'
            internetAccess: true
            vpcConfig:
              vpcId: vpc-bp1hcg467ekqsv0zr**** # The ID of the virtual private cloud (VPC) in which the database instance resides. 
              securityGroupId: sg-bp1gg2tyyzuvz8x0**** # The ID of the security group. 
              vswitchIds:
                - vsw-bp1sciqyju9qxocys**** # Make sure that the CIDR block of the vSwitch is added to the whitelist of the database instance. 
          function:
            name: redis
            description: visit redis
            runtime: python3
            codeUri: ./code
            handler: index.handler
            memorySize: 256
            timeout: 30
            initializationTimeout: 60
            initializer: index.initializer
            environmentVariables:
              REDIS_HOST: r-bp1v04cjj0jlr7****.redis.rds.aliyuncs.com # The private IP address of the database instance. 
              REDIS_PASSWORD: Hangzhou**** # The password of the database instance. 
              REDIS_PORT: 63** # The private port of the database instance. 
  5. Run the following command to build the project:
    s build --use-docker
  6. Run the following command to deploy the project:
    s deploy -y
  7. Run the following command to invoke a function:
    s invoke -e "{}"

    Expected command output:

    [2021-09-14T17:08:50.875] [INFO ] [S-CLI] - Start ...
    ========= FC invoke Logs begin =========
    FC Initialize Start RequestId: ccd73383-048d-4c8d-834e-93da59b86a21
    FC Initialize End RequestId: ccd73383-048d-4c8d-834e-93da59b86a21
    FC Invoke Start RequestId: eccafc0a-493e-4f3e-9afa-45c0b84a2c0f
    counter: 0
    FC Invoke End RequestId: eccafc0a-493e-4f3e-9afa-45c0b84a2c0f
    
    Duration: 27.51 ms, Billed Duration: 28 ms, Memory Size: 256 MB, Max Memory Used: 34.05 MB
    ========= FC invoke Logs end =========
    
    FC Invoke Result:
    0
    
    
    End of method: invoke

Sample code

Access a ApsaraDB for Redis database in a Python runtime of Function Compute

FAQ