This topic describes how to access a Tair (Redis OSS-compatible) database from Function Compute over a virtual private cloud (VPC). You can configure VPC-related settings in a function and a whitelist in the database to access the Tair (Redis OSS-compatible) database and perform related operations. In this topic, Serverless Devs is used to deploy a function to access a Tair (Redis OSS-compatible) database in the Python 3 runtime.
Prerequisites
A Tair (Redis OSS-compatible) instance is created. For more information, see Step 1: Create an instance.
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 supported.
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?.
Procedure
Install Serverless Devs and Docker and configure the AccessKey information.
For more information, see Quick start and the "Add a key" section of the Configure Serverless Devs topic.
Run the following command to initialize your project:
sudo s initIn the CLI, specify Alibaba Cloud as the vendor, specify the quick start mode, and then select a built-in Python runtime. Specify the project name and the region in which the project is deployed. In this example, the start-fc-redis-python project is deployed in the China (Hangzhou) region.
Run the following command to go to the project directory:
cd start-fc-redis-pythonModify the directory file based on your own business requirements.
Edit the s.yaml file. Sample file:
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-bp1oeg1fwxzuxcliq**** # The ID of the VPC in which the database instance resides. securityGroupId: sg-bp164seaxj7wc4d0**** # The ID of the security group. vswitchIds: - vsw-bp1192npo1ziqzw4**** # 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-bp1h2g53l3thqg****.redis.rds.aliyuncs.com # The private IP address of the database instance. REDIS_PASSWORD: **** # The password used to log on to the database instance. REDIS_PORT: 63** # The private port of the database instance.ImportantMake 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 section of this topic.
Edit the index.py code file. The code logic is to read the value of the counter key from Tair (Redis OSS-compatible), increase the value by 1, and then write the new value back to Tair (Redis OSS-compatible). Sample code:
# -*- 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
Run the following command to build the project:
sudo s build --use-dockerRun the following command to deploy the project:
sudo s deploy -yRun 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 Tair (Redis OSS-compatible).
[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
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.
Log on to the console.
In the top navigation bar, select the region in which the instance is deployed.
On the Instances page, find the instance and click its ID.
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.
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.
References
For more information about accessing a Tair (Redis OSS-compatible) database, visit GitHub.
For more information about how to view the information about the configured vSwiches in Function Compute and add CIDR blocks of Function Compute vSwiches to the whitelist of a Tair (Redis OSS-compatible) database, see Configure network settings and Configure an IP address whitelist.
You must import a Tair (Redis OSS-compatible) client library to ensure that the sample code provided in this topic runs as expected. For more information about how to install third-party dependencies, see Install a third-party dependency for a function.
If the configured vSwitch cannot access the specified zone, see How can I resolve the "vSwitch is in unsupported zone" error? For more information about the common exceptions that may occur when you access a Tair (Redis OSS-compatible) database, see Common errors and troubleshooting. You can also troubleshoot a database connection failure by referring to How to troubleshoot database access failures? based on the problem description.