In Function Compute, you can use a function to call the ApsaraDB for Redis API to perform operations such as insert and query on an ApsaraDB for Redis instance. In normal cases, states cannot be shared among different execution environments in Function Compute. You can persist structured data in a database so that states can be shared. This topic describes how to use FunCraft to deploy a function to access an ApsaraDB for Redis database.

Prerequisites

  1. You have created a virtual private cloud (VPC) and a VSwitch.

    The VSwitch must belong to a zone supported by Function Compute. For more information about the zones supported by Function Compute, see VPC access.

  2. An ApsaraDB for Redis instance has been created.

    You have created a database instance in same VPC as Function Compute. You do not need to create the VSwitch in the same zone as Function Compute. VSwitches under the same VPC can communicate with each other even when they are in different zones.

  3. A whitelist has been configured for the ApsaraDB for Redis instance.

    If you need to control access to databases by using an IP address whitelist, ensure that you have entered the internal Classless Inter-Domain Routing (CIDR) blocks of the target VPCs in the IP field. To find the CIDR block of a VPC, log on to the VPC console and view the VPC Details page.

  4. Create a security group

    You have configured the security group to allow outbound traffic from the internal CIDR block and port of the database.

Write a function

The following section describes how to use Funcraft to write a function that accesses a database. The sample code is written in Python 3.

  1. On the local machine, create a directory to store code and dependent modules. In the directory, create the template.yml file. In this example, the /tmp/code/template.yml file is created and contains the following content:
    ROSTemplateFormatVersion: '2015-09-01'
    Transform: 'Aliyun::Serverless-2018-04-03'
    Resources:
     service:
        Type: 'Aliyun::Serverless::Service'
        Properties:
          Description: This is Redis service
          Policies:
            - AliyunECSNetworkInterfaceManagementAccess
          VpcConfig:
            VpcId: vpc-xxxx
            VSwitchIds:
              - vsw-xxxx
            SecurityGroupId: sg-xxxx
          InternetAccess: true
        function:
          Type: 'Aliyun::Serverless::Function'
          Properties:
            Initializer: 'index.initializer'
            Handler: 'index.handler'
            Runtime: python3
            CodeUri: '. /'
            EnvironmentVariables:
              REDIS_HOST: r-xxxx.redis.rds.aliyuncs.com
              REDIS_PASSWORD: Txd1xxxx
              REDIS_PORT: '6379'

    The following list describes the main parameters:

    • A service named service is declared.
      • Policies: grants Function Compute permission to manage elastic network interfaces (ENIs) attached to Elastic Compute Service (ECS) instances. Function Compute can then access resources in the VPC.
      • VpcConfig: binds the VPC to the service. You must replace the following values with the information for your VPC.
        • VpcId: the ID of the VPC.
        • VSwitchId: the ID of the VSwitch.
        • SecurityGroupId: the ID of the security group.
    • A function named function is declared.
      • Initializer: the initializer function. For more information, see Initializer function.
      • Handler: the function handler. For more information, see Function entry point.
      • Runtime: the runtime environment of the function.
      • CodeUri: the directory where the code package is located.

        During function deployment, Funcraft packages and uploads the items in the directory specified by the CodeUri parameter.

      • EnvironmentVariables: the environment variables of the function.
        • REDIS_HOST: the internal endpoint of the ApsaraDB for Redis instance.

          To find the internal endpoint, log on to the ApsaraDB for Redis console and open the Instance Information page for the target instance. In the Connection Information section, check the value of Internal Endpoint (Host).

        • REDIS_PASSWORD: the password for logging on to the ApsaraDB for Redis database.
        • REDIS_PORT: the port used to connect to the ApsaraDB for Redis database.

    For more information about configuration rules, see Serverless Application Model.

  2. In the directory that contains the template.yml file, create the Funfile file. In this example, the new file contains the following sample content:
    RUNTIME python3
    RUN fun-install pip install redis                        
  3. Run the fun install command to install dependencies.
    $ fun install
    using template: template.yml
    start installing function dependencies without docker
    
    building service/function
    Funfile exist, Fun will use container to build forcely
    Step 1/2 : FROM registry.cn-beijing.aliyuncs.com/aliyunfc/runtime-python3.6:build-1.7.7
    ---> 373f5819463b
    Step 2/2 : RUN fun-install pip install redis
    ---> Running in f26aef48f9e5
    Task => PipTask
         => PYTHONUSERBASE=/code/.fun/python pip install --user redis
    Removing intermediate container f26aef48f9e5
    ---> 809c6655f9e9
    sha256:809c6655f9e93d137840b1446f46572fbab7548c5c36b6ae66599dfc2e27555b
    Successfully built 809c6655f9e9
    Successfully tagged fun-cache-78c74899-5497-4205-a670-24e4daf88284:latest
    copying function artifact to /Users/txd123/Desktop/Redis/Python
    
    Install Success                        
  4. In the directory that contains the template.yml file, create a Python file. In this example, the /tmp/code/index.py file is created and contains the following sample content:
    # -*- coding: utf-8 -*-
    import os,sys
    import redis
    def initializer(context):
        global conn_pool
        conn_pool=redis.ConnectionPool(host=os.environ['REDIS_HOST'],password=os.environ['REDIS_PASSWORD'],port=os.environ['REDIS_PORT'],db=1,decode_responses=True)
    
    def handler(event, context):
        r = redis.Redis(connection_pool=conn_pool)
        r.set('test','89898')
        r.set('zyh_info','{"name":"Tanya","password":"123456","account":11234}')
        print(r.get('test'))
        return r.get('zyh_info')                       
  5. Run the following command to deploy the function to Function Compute by using Funcraft:
    $ fun deploy
    using template: template.yml
    using region: cn-hangzhou
    using accountId: ***********3743
    using accessKeyId: ***********Ptgk
    using timeout: 60
    
    Waiting for service service to be deployed...
            Waiting for function function to be deployed...
                    Waiting for packaging function function code...
                    The function function has been packaged. A total of 25 files files were compressed and the final size was 138.78 KB
            function function deploy success
    service service deploy success                       

Debug the function

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select your region.
  3. In the left-side navigation pane, click Service/Function.
  4. Find the target function in the target service and click the name of the function.
  5. On the page that appears, click the Code tab. On this tab, click Invoke.
    After the execution is complete, you can view the execution results and logs. result