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

How to use Redis in Cloud Development

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces how to use Redis in cloud development. It is very detailed and has a certain reference value. Friends who are interested must read it!

Introduction and Application scenario of Redis

Redis is an open source In-Memory NoSQL database that can be used as database, cache, and messaging middleware. Supports many types of data structures, such as strings, hashes, lists, sets, and so on. Common application scenarios are:

1. Session caching: Redis not only stores in memory and is fast to read and write, but also provides a persistence scheme to provide consistency.

two。 Page cache: can be used as a cache of rendering results on the PHP or Node.js server.

3. Message queuing: Redis supports lists and Pub/Sub, and can be used as a message queue.

4. Ranking / counting: Redis is in memory, so it does a great job of increasing and decreasing. In addition, Redis also supports collection and sorting collection data structures, which is more suitable for ranking scenarios.

Introduction to VPC

Virtual Private Cloud,VPC is an exclusive cloud-based network space built by Tencent Cloud to provide network services for your resources on Tencent Cloud. Different VPCs are logically isolated. You can customize the network environment, routing table, security policy, etc. At the same time, VPC supports multiple ways to connect Internet, other VPC, and your local data center to help you easily deploy cloud networks.

Compared with the basic network in which users share the resource pool, users can freely define network segment division, IP address and routing policy in VPC; in terms of security, they can provide network ACL and security group access control, which is more flexible and secure.

VPC has three core components: VPC network segment, subnet and routing table.

A VPC consists of at least one subnet, and the CIDR (classless inter-domain routing) of the subnet must be within the CIDR of the VPC.

Subnet is used to manage a network in the network plane of elastic CVM, which can provide IP address management, DNS and other services. All cloud resources in the VPC (such as CVM, cloud database, etc.) must be deployed in the subnet.

VPC has a Region attribute (such as Guangzhou), while a subnet has an availability zone (Zone) attribute (such as Guangzhou Zone 1). Subnets under a VPC can belong to different availability zones in that region. Resources in each subnet under the same VPC are interconnected by default, regardless of whether they are in the same availability zone or not.

The routing table consists of multiple routing policies, which are used to control the outbound traffic direction of the subnet in the VPC. Only one routing table can be associated with each subnet, and one routing table can be associated with multiple subnets. You can create multiple routing tables for subnets with different traffic directions.

Create a new VPC

You can create a VPC free of charge in the VPC of Tencent Cloud console. Since VPC has a Region attribute, we need to create a VPC in the region where the function resides.

Here we choose the region of East China (Shanghai). If you have already established a private network in this region, you can skip this step.

When creating a VPC, you need to initialize a subnet. Here, we choose to build a subnet in the availability zone of Shanghai Zone 2.

Add cloud function to VPC

After creating a VPC and subnet, we need to configure the network mode of the function and add the function to the VPC in East China (Shanghai).

In Tencent Cloud's Cloud Development console, find the cloud function to be configured, and click Edit to enter the configuration interface:

In the function configuration interface, modify the network configuration to the virtual network and subnet of East China (Shanghai) region.

Purchase Redis and join the same VPC

Next, in the Tencent Cloud cloud database console, find the Shanghai region and create a new Redis instance:

In order to facilitate the demonstration, we have selected a single copy instance with 256 MB of memory. You can also choose the appropriate package according to your specific needs and scenarios.

Tips: in order to ensure reliability and high availability in production environment, it is recommended not to select single copy, but preferably multiple copies or Redis cluster. In addition, if Redis is only deployed on stand-alone machines such as CVM, disaster recovery and backup are also required.

Note that you need to select a VPC for the network type, as well as the VPC and subnet you just built:

Connect Redis in Cloud function

After purchasing Redis, an instance of Redis will be created soon. After the creation is successful, we can see the ip of the Redis instance under the network. We need to connect this instance in the cloud function:

1. Install Redis client library in cloud function

In order to connect and operate the Redis instance, we need a Redis client. Here we use the community open source ioredis as the Redis client library as an example:

First of all, add the dependency ioredis dependency to package.json in the SCF directory. After setting it, remember to upload and deploy it in the developer tool (cloud installation dependency):

{"name": "redis-demo", "dependencies": {"wx-server-sdk": "latest", "ioredis": "4.14.1"}}

two。 Connect and operate Redis in cloud function

Next, write code in the cloud function to connect and operate Redis. Here, you need to provide the ip, port, password and other information of the Redis instance.

Tips: it is recommended to create a new Redis client instance outside the main function, so that the Redis will not be repeatedly connected when the function instance is reused, and the performance is better.

In the main function, you can read and write data through redis.get, redis.set and other methods. You can view the API document of ioredis.

ConstRedis= require ('ioredis'); / / it is recommended to create a new Redis client instance outside the main function / / so that Redisconst redis = newRedis is not repeatedly connected when the function instance is reused ({port:6379,// Redis port host:'YOUR_REDIS_IP',// Redis host family:4,// 4 (IPv4) or 6 (IPv6) password:'YOUR_PASSWORD', db:0,}) / / Cloud function entry function exports.main = async (event, context) = > {/ / TODO can use redis.get, redis.set and other methods to operate Redis}. Example: Redis is used as cache in cloud function.

Now let's actually demonstrate how to use Redis as cache in cloud functions.

We need to create a new cloud function named redis-demo. The main implementation of this function is:

Connect the Redis deployed on the same VPC.

When a user requests a cloud function, the user's openid is first used as the key to query whether there is a cache in the Redis.

Return directly if there is a cache.

If there is no cache, a function will be executed to get the result. Here, we simulate a 2s operation to return a random number as an example. After getting the result, it will be cached in Redis and returned.

Example function code: / / Cloud function entry file const cloud = require ('wx-server-sdk'); constRedis= require (' ioredis'); cloud.init (); const redis = newRedis ({port:6379,// Redis port host:'YOUR_REDIS_IP',// Redis host family:4,// 4 (IPv4) or 6 (IPv6) password:'YOUR_PASSWORD', db:0,}) / / Cloud function entry function exports.main = async (event, context) = > {const wxContext = cloud.getWXContext (); const cacheKey = wxContext.OPENID;const cache = await redis.get (cacheKey); if (! cache) {const result = await newPromise ((resolve, reject) = > {/ / simulates a task that takes 2s and returns a random number setTimeout () = > resolve (Math.random ()), 2000);}) / / cache redis.set (cacheKey, result,'EX',3600) for one hour; return result;} else {return cache;}}

After writing the code, we need to upload and deploy the redis-demo function, and then try to call this cloud function in Mini Program to test the effect:

We can see that due to the use of Redis as the cache, the result of the function can be obtained in about 300 ms in multiple requests for calling the cloud function. The result returned by the function is the random number we cached, which is in line with the expected effect.

The above is all the contents of the article "how to use Redis in Cloud Development". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Database

Wechat

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

12
Report