All Products
Search
Document Center

Function Compute:Access an ApsaraDB for Redis database

Last Updated:Jun 18, 2024

This topic provides guidance for establishing access to an ApsaraDB for Redis database from Function Compute through a virtual private cloud (VPC). Specifically, you can configure VPC-related settings in a function and a whitelist in the database to access the ApsaraDB for Redis database and perform related operations. In this topic, Serverless Devs is used to deploy a function to access an ApsaraDB for Redis database in the Python 3 runtime.

Before you start

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, see Zones where Function Compute is available.

    If your database instance is not in a zone that is supported by Function Compute, you can create a vSwitch in your VPC in the same zone as Function Compute and use this vSwitch ID in the VPC configurations of the function. 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 What do I do if the vSwitch is in unsupported zone error is reported?

Procedure

  1. Install Serverless Devs and Docker and configure the AccessKey information.

  2. Run the following command to initialize your project.

    sudo s init

    In the CLI, specify Alibaba Cloud as the vendor, specify the quick start mode, and select a built-in Python runtime. Configure the project name and the region where the project is deployed. In this example, the start-fc-redis-python project is deployed in the China (Hangzhou) region.

  3. Run the following command to go to the project directory:

    cd start-fc-redis-python
  4. Modify the directory file based on your own business requirements.

    • Edit the s.yaml file. Example:

      edition: 3.0.0
      name: hello-world-app
      access: "default"
      
      vars: # The global variables.
        region: "cn-hangzhou"
      
      resources:
        hello_world:
          component: fc3 # The component name.
          # actions:       # The custom execution logic. For more information about actions, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E8%A1%8C%E4%B8%BA%E6%8F%8F%E8%BF%B0actions.
          props:
            region: ${vars.region}              # For information about how to use variables, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC.
            functionName: "start-python-xbk4"
            description: 'hello world by serverless devs'
            runtime: "python3.9"
            code: ./code
            handler: index.handler
            memorySize: 128
            timeout: 30
            internetAccess: true
            vpcConfig:
             vpcId: vpc-bp11y195luy47h8cm**** # The ID of the VPC in which the database instance resides.
             securityGroupId: sg-bp1el3hto8hhkdup**** # The ID of the security group.
             vSwitchIds: 
              - vsw-bp18vwna9x79koh3q**** # Make sure that the CIDR block of the vSwitch is added to the whitelist of the database instance. 
          environmentVariables:
           REDIS_HOST: r-bp17w15ohdk7****.redis.rds.aliyuncs.com # The private endpoint of the database instance. 
           REDIS_PASSWORD: 15**** # The password of the database instance. 
           REDIS_PORT: 6379 # The private port of the database instance.

      Important

      Make sure that the CIDR block of the vSwitch that you configure for the function is added to the whitelist of the database instance. For more information, see Configure an IP address whitelist for the database.

    • Edit the index.py code file. The following code snippet provides an example. The code logic is to read the value of the counter key from Redis, increase the value by 1, and then write the new value back to Redis.

      # -*- coding: utf-8 -*-
      import os
      import redis
      
      conn_pool = None
      
      
      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):
          global conn_pool
          r = redis.Redis(connection_pool=conn_pool)
      
          counter = r.get('counter')
      
          if counter is None:
              counter = 0
          else:
              counter = int(counter)
      
          print('counter: ' + str(counter))
      
          r.set('counter', str(counter + 1))
          return counter
      
  5. Run the following command to build the project.

    sudo s build --use-docker
  6. Run the following command to deploy the project.

    sudo s deploy -y
  7. Run the following command to invoke the function.

    sudo s invoke -e "{}"

    The following code snippet shows the expected output. The value in the returned result increases from 0, which indicates that the value of the counter key is successfully read from Redis.

    [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

Configure an 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 of the instance details page, click Whitelist Settings. On the Whitelist Settings tab, find the whitelist that you want to modify and click Modify in the Actions column.

  5. In the Modify Whitelist panel, enter the CIDR block of the vSwitch to which the instance is bound in the Whitelist field and click OK.

More information