Author: Ethin

 title=

Click on the image above for event details!

Hello fellow developers, in order to help you understand and use Alibaba Cloud Function Computing (FC) objectively, the Alibaba Cloud Developer Community and the Serverless team of the cloud native application platform have released the "Serverless Function Computing Collection Order", providing free resource quotas and inviting you to post comments , Participate in the event before July 31st, you will have the opportunity to get a thousand yuan gift + thousand yuan function computing resource package!

Join now:

https://developer.aliyun.com/topic/serverless2022

Whisper... Now you can also get a Youku video season card for submissions; let's follow the steps of pen pal "Ethin" and see the serverless world in his eyes!

function computing, you name it

Cloud computing is a computing method based on the Internet. In this way, the shared software and hardware resources and information can be provided to various computer terminals and other equipment as required, and the computer infrastructure provided by the service provider is used as computing resources. "Cloud" to refer to "network computing resources" is a very apt metaphor.

 title=

The National Institute of Standards and Technology's definition of cloud computing defines three service models, namely software as a service (SaaS), platform as a service (PaaS), and infrastructure as a service (IaaS).

Alibaba Cloud's products can cover all these three service modes. If you give an example, they should be: Yida (SaaS accelerator), function computing FC, and cloud server ECS.

Serverless computing services, which are based on PaaS and different from PaaS, are more often referred to as Function-as-a-Service (FaaS for short). Function Compute FC is an event-driven fully managed serverless computing service product of Alibaba Cloud. I think that's how the name of Function Compute was born.

Function computing, right to the core of the application

We know that the core of the application is logic and storage, and the code mainly implements business logic and persistence.

Function computing FC is generally: FaaS+BaaS

Functions refer to computing functions, including business logic, which is implemented by FaaS; while data persistence, message push, and account systems are implemented by BaaS.

ECS? FC?

 title=

Serverless services are not without servers, but as a new architecture, our work on traditional application maintenance in the past has been further reduced.

Taking common web services mainly based on cloud servers as an example, there is roughly the following process:

 title=

During the service process, the server may involve routing rules, authentication logic, and various other complex business codes. At the same time, the development team should not only devote their energy to development, but also devote a lot of energy to the operation and maintenance of the server. For example, always pay attention to the following questions:

  • Can the server performance cope with the sudden burst of user requests, and when will the capacity be expanded?
  • How many scripts and business codes on the server are still running healthy?
  • How to ensure data security when external network security threats come?

Faced with many problems, it will be a big headache, but if we abandon the server-based architecture and switch to the serverless architecture; the process of serving becomes like this:

 title=

When the client and database remain unchanged, the server becomes a serverless architecture. The division of work has changed dramatically.

For example, the routing module and authentication module that previously needed to be maintained by the development team will be connected to the API gateway system and authentication system provided by the service provider. The development team no longer needs to maintain the business codes of these two parts, but only needs to continuously maintain the relevant rules. , no longer need to worry about application construction; business code is divided into function granularity, different functions represent different functions, and millisecond-level expansion can be achieved according to the amount of requests; some security issues and resource scheduling issues other than business logic are all handled It is the responsibility of the cloud vendor.

 title=

In addition to the worry-free development and maintenance of products, it can also achieve the effect of reducing costs and increasing efficiency in terms of specific implementation costs. Compared with the 24/7 operation of traditional project services, Function Compute FC is event-driven. The function will be activated and executed only when the user initiates a request. The operation cost is charged according to the amount, and the cost is significantly higher than the saving plan. price advantage.

Function Compute FC: Liberate productivity and focus more on the business itself of the application

Using cloud servers, we don't have to worry about the operation and maintenance of the physical computer room and other contents under the operating system layer; using function computing FC, we no longer need to install the operating system, container configuration, and operating environment, let alone the environment program will hang.

 title=

It can be seen that after adopting the serverless architecture of function computing FC, users only need to operate and maintain the functions related to the application. There is only one thing left to worry about under the ECS architecture:

 title=

Function computing seems to be a brand new technological revolution. When we use the serverless architecture of function computing FC:

The development team does not need to maintain the server by itself, nor does it need to worry about various performance indicators and resource utilization of the server. The team's operation and maintenance can focus more on monitoring the measurement of the application itself.

Application deployment will become very easy. We only need to upload basic code, and we do not need to use Puppet, Chef, Ansible or Docker for configuration management, which greatly reduces operation and maintenance costs.

To sum up, compared to traditional projects, Function Compute FC has the following advantages:

  • Users do not need to purchase and manage infrastructure such as servers, with low operation and maintenance costs and higher security. (covers the advantages of cloud servers).
  • Users only need to focus on the development of business logic, and use the development language supported by Function Compute to design, optimize, test, review, and upload their own application code. Combined with the workflow, code submission is automatically deployed and run directly!
  • Function Compute FC triggers applications to respond to user requests in an event-driven manner. Seamless integration with Alibaba Cloud Object Storage OSS, API Gateway, Log Service, and Table Storage to help quickly build applications.
  • Simplify operation and maintenance, and provide functions such as log query, performance monitoring, and alarm to quickly troubleshoot faults.
  • Don't worry about performance issues, the architecture is more flexible, the millisecond-level elastic scaling, and the underlying capacity can be quickly expanded to cope with peak pressure.
  • Low cost of use, pay-as-you-go, and support charging at the 100-millisecond level. You only need to pay for the computing resources actually used, which is suitable for user access scenarios with obvious peaks and valleys.

Function Compute FC seems to be a true realization of the cloud computing vision of "like cloud", which is a good interpretation of the environmental protection concept of maximizing resource utilization, reducing waste of idle resources, and reducing learning costs and usage costs.

How to experience such wonderful function computing?

Function Compute FC provides functions such as a runtime environment, developer tools, and function triggers. Meanwhile, Function Compute FC provides free execution times: 1 million (times) and free resource usage: 400,000 (GB-sec). For small-scale online use, we only need to pay for public network traffic and other resources.

 title=

The most common way to create Function Compute is to enter the Services and Functions sub-page in the console, and create services and functions in turn. A service can be composed of multiple functions, and a function can only belong to one service.

Of course, Alibaba Cloud provides a one-click function computing console-application page, which we can create by importing templates and warehouses:

At present, the template center in the public beta contains a total of 56 application or framework templates from various official or community sources, and the coverage is quite comprehensive. Under the guidance of official documents, it is possible to create FC applications based on zero basis.

 title=

From complex to simple, from long to short

Practice: Web Short URL Jump Based on Node.js + Serverless

The main function:

Implement the mapping between long and short links.

A brief description:

Users can create corresponding short links for specified URLs

The user accesses the short link and automatically jumps to the corresponding URL

As mentioned above, building applications with function computing FC is generally FaaS+BaaS. The following practical projects involve the use of the BaaS database. For convenience, use the cloud development platform to build applications.

The application architecture diagram is as follows:

 title=

Resource preparation:

You need to register and activate the cloud development platform and activate the following services;

  • API Gateway/API Gateway
  • Function Compute
  • Object Storage/Object Storage Service
  • Log Service/Log Service
  • MongoDB Serverless instance

Database part:

  • Purchase MongoDB Serverless Edition.
  • Creating a new collection is actually equivalent to creating a new table. Create collections: links, logs.
  • Connect to the Serverless instance through program code, see the official documentation for usage: https://help.aliyun.com/document_detail/185473.html

Example of logic code section: (Attention: The project also uses the Express framework to simplify routing processing)

 import storage from '../storage'

export default async (req, res): Promise<any> => {
  // params from request body or querystring
  const params = req.body ?? req.query
  const { url = '', slug = '' } = params as { url?: string, slug?: string }

  // url is required
  if (url === '') {
    return res.status(400).send({ message: 'Missing required parameter: url.' })
  }

  // url format check
  if (!/^https?://.{3,}/.test(url)) {
    return res.status(400).send({ message: 'Illegal format: url.' })
  }

  // custom slug length check
  if (slug.length !== 0 && (slug.length < 2 || slug.length > 10)) {
    return res.status(400).send({ message: 'Illegal length: slug, (>= 2 && <= 10).' })
  }

  const getForwarded = (name: string): string => req.headers[`x-forwarded-${name}`]?.toString() ?? ''

  try {
    // request origin url
    const origin = `${getForwarded('proto')}://${getForwarded('host')}/`

    // if slug customized
    if (slug !== '') {
      const existUrl = await storage.getUrlBySlug(slug)

      // url & slug are the same.
      if (existUrl === url) {
        return res.send({ slug, link: origin + slug })
      }

      // slug already exists
      if (existUrl != null) {
        return res.status(400).send({ message: 'Slug already exists.' })
      }
    }

    // target url exists
    const existSlug = await storage.getSlugByUrl(url)

    // url exists & no custom slug
    if (existSlug != null && slug === '') {
      return res.send({ slug: existSlug, link: origin + existSlug })
    }

    // create if not exists
    const newSlug = await storage.addLink(url, slug)

    // response
    res.send({ slug: newSlug, link: origin + newSlug })
  } catch (e) {
    return res.status(500).send({ message: e.message })
  }
}

 title=

After completing the front-end static page, you can bind the domain name for online testing.

(Attention: Need to bind registered domain name)

Epilogue

Serverless, as the preferred microservice for cloud native players, has gradually been recognized by the public and has developed rapidly. It is expected that there will be more serverless-based applications in the future.

Click here to view the author's original text immediately!


阿里云云原生
1k 声望302 粉丝