What is Serverless?

Serverless is also known as Serverless. The so-called Serverless does not mean that it does not need to rely on or rely on resources such as servers, but developers do not need to think too much about servers and can focus more on product code. Serverless in the narrow sense is composed of Faas and Baas.

Traditional high-concurrency architectures

In the traditional high concurrency framework, we need to configure a lot of things, first, we need to buy the server, then the server configuration, also these servers can be divided into the web server and database server, configure load balancing, master-slave configuration database, static server configuration, and so on, then the deployment process, also need to constantly be maintained after deployment, This is the traditional high-concurrency architecture.

High concurrency architecture under Serverless

Under Serverless, users do not need to care about how many servers they need to buy, which are used as Web servers and which are used as database servers, and they do not need to care about setting up environment and deploying projects. The developer simply needs to deploy the project to a Serverless server. Also, Serverless provides users with logging services, monitoring services, and high concurrency.

Egg.js project structure diagram

Tencent cloud Severless

  1. Install the serverless
npm install -g serverless
Copy the code
  1. Check the version
serverless -v
Copy the code

Quickly build a project

  1. Run the serverless command in an empty folder
serverless
Copy the code
  1. Select the Express template

  2. Choose to deploy in the cloud

Deploy to the cloud

serverless deploy
Copy the code

Creating a cloud function

Select Custom Create, environment select Node12, and click Finish.

  • Access our cloud functions in the browser address bar

Configure trigger management, create trigger, set trigger mode to API gateway trigger, create NEW API service, set request type to Any, publish, authentication exemption, and cancel integrated response. The response cannot return a string directly without unintegrating.

Access is achieved through the following access path.

After modifying the cloud function and clicking Deploy, you can revisit the target URL.

What is the use of layer management in cloud functions? The layer manager in the cloud function can upload our node_modules and then configure the cloud function to select this environment.

Cloud functions that want to change the custom domain name can be configured by triggering the custom domain name in the API service name in the management.

Cloud functions are created using application templates in WebCli

  1. Click on cloud Products to enter the Serverless Application Center
  2. The new application
  3. Select the Express framework template

Create and write cloud functions using plug-ins in Vscode

Install the following plug-ins

When you log in for the first time, you can access the ID and key by following the url in the plug-in’s description.

Serverless Cli Create and write applications

Please refer to ## Tencent Cloud Severless above for installation method

Once the installation is complete, use the following code in your project to use Serverless

serverless
Copy the code

When we are done updating our code, we can sync our local code to the cloud using the following code.

serverless deploy
Copy the code

Debugging locally can be done in the following ways

nodemon app.js
Copy the code

You can configure not to upload the node_modules folder, but you need to enable automatic installation dependencies in the cloud function.

Configuring Static Resources

app.use(express.static(__dirname  + "/public"))
Copy the code

You can refer to the experience of this article about deployment bloodbath caused by the lack of absolute paths

Deploy KOA projects using Serverless

In KOA we need to comment out the following line of code if we want to enable API gateway triggers directly after deployment.

Configure static resource services

  1. Installation-dependent dependencies
npm install koa-static
Copy the code
  1. Introduction toolkit
const static = require('koa-static')
Copy the code
  1. Configuring middleware
app.use(static(path.join(__dirname,'public')))
Copy the code

Deploy egg.js using Serverless

The basic deployment method is the same as the preceding method. Local test egg

npm run dev
Copy the code

Deploy vue.js with Serverless

Vue projects created using the Serverless template use Vue2 projects by default. If you want to use Vue3 projects, simply add the Serverless. Yml configuration file to your existing project and do the following.

npm i
npm run serve
npm run build
serverless deploy
Copy the code

Tencent Cloud Serverless will store static files on COS. The following is the name of COS. The code in the bucket is the code in our dist folder.

Use Node to operate Mysql and Mongodb databases in Serverless

Tencent cloud Mysql and cloud functions to build a private network

First of all, Mysql and cloud functions should be in the same area, such as District 6 of Shanghai, and under the same private network, so that LAN access can be realized. Otherwise, only public network access can be realized.

Run the Mongodb database in Serverless

The method is similar to the Mysql operation mentioned above and will not be repeated in this article.

Serverless uploads local files to Tencent Cloud COS.

Synchronize local resources to the server.

  1. Follow the documentation below to install dependencies.
  • Object storage SDK guide
  1. Create a bucket on Tencent cloud and set the bucket to read in common and write in private.

The local code is shown below.

const fs = require('fs');

/ / SECRETID and SECRETKEY please log on to https://console.cloud.tencent.com/cam/capi to view and manage
var COS = require('cos-nodejs-sdk-v5');
var cos = new COS({
  SecretId: 'xxx'.SecretKey: 'xxx'
});

// Upload objects
cos.putObject({
  Bucket: 'serverless1test-1301559367'./ * must * /
  Region: 'ap-beijing'./ * must * /
  Key: 'test.png'./ * must * /
  StorageClass: 'STANDARD'.Body: fs.createReadStream('./python.png'), // Upload the file object
  onProgress: function(progressData) {
      console.log(JSON.stringify(progressData)); }},function(err, data) {
  console.log(err || data);
});
Copy the code

Express enables uploading of images to COS in Serverless

  1. Configure the body-Parser middleware in app.js
  • Body – parser middleware
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
Copy the code
  1. Configure multer middleware in app.js
const multer = require('multer');
var storage = multer.memoryStorage()
var upload = multer({ storage: storage })
Copy the code
  1. Configure routes to upload images to a specified bucket
app.post(`/doUpload`, upload.single("img"), (req, res) = > {
  var cos = new COS({
    SecretId: 'AKID4xbz6wWNyIM8droUt0qQjkUyBCwPbW9V'.SecretKey: 'xxx'
  });
  // Upload objects
  cos.putObject({
    Bucket: 'serverless1test-1301559367'./ * must * /
    Region: 'ap-beijing'./ * must * /
    Key: req.file.originalname,              / * must * /
    StorageClass: 'STANDARD'.Body: req.file.buffer, // Upload the file object
    onProgress: function (progressData) {
      console.log(JSON.stringify(progressData));
      res.send(req.body)
    }
  }, function (err, data) {
    console.log(err || data);
  });
})
Copy the code

Configure domain name access in Serverless

  1. Find the corresponding Serverless application.
  2. Go to the API gateway, click on the service ID, and click on the custom domain name.
  3. When you customize a domain name, the domain name must point to the specified address.
  4. Configuring Path Mapping

Configure HTTPS access in Serverless

To configure HTTPS access for applications corresponding to Serverless, add the corresponding security certificate.

Configure the COS custom domain name

You only need to set the domain name of the corresponding bucket.