Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Serverless solution-- function calculation how to access Redis database

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Function Compute: Function Compute is an event-driven, fully managed computing service. With functional computing, you don't need to purchase and manage infrastructure such as servers, you just write and upload code. Functional computation prepares you for computing resources, runs tasks elastically and reliably, and provides log queries, performance monitoring, and alerts. With functional computing, you can quickly build any type of app and service and pay only for the resources that the task actually consumes.

Access to Redis database refers to the insertion and query of database through TCP protocol by calling database driver library through writing code in function calculation. Generally, different function instances running in function calculation do not share state, and structured data can be persisted in the form of database to achieve state sharing. Since user functions run in the VPC of function computation, and user databases run in the VPC to which users belong, accessing databases on function computation platforms involves cross-VPC access scenarios. Let's first introduce their working mechanism.

working mechanism

The principle and working mechanism of accessing Redis are exactly the same as accessing Mysql database. This article will not repeat it. For more details, please refer to the working mechanism chapter of accessing Mysql database.

Configure and write functions Common configuration Create proprietary network VPC Login VPC console. See VPC Building Proprietary Networks Create VPCs and Switches. create a security group

Create a new security group in the security group console, click Create Security Group, set the name of the security group, select Private Network for the network type, and select the private network you just created.

Creating and configuring Redis instances

To create cloud database Redis version instances suitable for business needs, please refer to Cloud Database Redis version.

After successful creation, click Whitelist Settings in the navigation bar on the left side of the instance information page.

Click Modify to the right of the default area box.

In the pop-up dialog box, configure the address of the VPC network segment where the function is calculated in the whitelist input box.

Log in to the VPC console, find the VPC where the application is located in the list of proprietary networks, and click the name of the VPC to go to the proprietary network details page. Copy the IPv4 segment of the VPC where the application resides.

Paste the IPv4 segment address of the VPC in the group whitelist settings box, and click OK.

Finally, visit the Redis database host as the intranet address of the instance. You can log in to Alibaba Cloud Console to view:

Multi-language client connection Aliyun Redis can refer to Redis client connection.

Function Calculation Configuration VPC

Note: The function calculates the service in the same region as the resource created in the common configuration.

Create a service in the function calculation console. For service creation steps, please refer to the article Add, Delete, and Modify Services. Select the VPC network, switch, and security group you created in step 1. In Permission Configuration, select New Role, click Authorize, and click Authorize on the Quick Role Creation page. The operation in this step is to grant the function calculation permission to operate ENI. The function calculates the permission required to access resources in VPC. Please refer to the article Configuring Function Calculation to Access Resources in VPC. Click OK to complete the new service. Function writing and debugging

Here is an example of how Python 3 can access Redis database:

Use the Fun tool to install dependencies and project deployments in the directory where the code and dependency modules are stored.

Create a directory for storing code and dependent modules, and create a template.yml file in this directory, such as/tmp/code/template.yml. The content is: ROSTemplateFormatVersion: '2015-09-01'Transform: 'Aliyun::Serverless-2018-04-03'Resources: Redis-test: Type: 'Aliyun::Serverless::Service' Properties: Description: This is Redis service Role: 'acs:ram::XXX:role/fc-public-test' LogConfig: Project: XXX Logstore: XXXX VpcConfig: VpcId: vpc-XXXXX VSwitchIds: - vsw-XXXX SecurityGroupId: sg-XXXX InternetAccess: true python-test: Type: 'Aliyun::Serverless::Function' Properties: Initializer: 'index.initializer' Handler: 'index.handler' Runtime: python3 Timeout: 10 MemorySize: 128 CodeUri: './ ' EnvironmentVariables: REDIS_HOST: r-XXXXX.redis.rds.aliyuncs.com REDIS_PASSWORD: XXXXX REDIS_PORT: '6379' Create a Funfile in this directory with the following contents: RUNTIME python3RUN fun-install pip install redis

Execute fun install to install dependencies:

$ fun install using template: template.yml start installing function dependencies without docker building Redis-test/python-test 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

Create a new code file in the function root directory, such as/tmp/code/index.py, and use redis :

# -*- 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')

Use fun tools to deploy:

$ fun deploy using template: template.yml using region: cn-hangzhou using accountId: ***********3743 using accessKeyId: ***********Ptgk using timeout: 60 Waiting for service Redis-test to be deployed... Waiting for function python-test to be deployed... Waiting for packaging function python-test code... The function python-test has been packaged. A total of 25 files files were compressed and the final size was 138.78 KB function python-test deploy success service Redis-test deploy success

Log in to the console and see that the related services and functions have been successfully created, and the trigger execution can return correct results.

summary

Through this article, you can quickly implement function calculation to access Redis database.

Advantages of using function calculations:

No need to purchase and manage infrastructure such as servers, just focus on the development of business logic, which can greatly shorten project delivery time and labor cost; provide log query, performance monitoring, alarm and other functions to quickly troubleshoot faults; OPM-free, millisecond level Auto Scaling, quickly realize bottom layer expansion to cope with peak pressure, excellent performance; cost is very competitive;

"Alibaba Cloud Native Technology Circle focuses on microservices, Serverless, containers, Service Mesh and other technical fields, focuses on cloud native popular technology trends, cloud native large-scale landing practices, and is the technology circle that understands cloud native developers best. "

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report