This is the first 76 Original without water , Want to get more original articles , Please search the official account for us ~ This article first appeared in the front-end blog of Zhengcai cloud : Combined with Alibaba cloud FC Talk about my right to FaaS The understanding of the
Before entering the topic , First of all, from the background of the latest frontier hot words Serverless, Actually ,Serverless This concept has been proposed in other fields for a long time .
Serverless
Concept
Serverless No server , Represents a kind of No server architecture ( Also known as “ Serverless computation ”), Doesn't mean you don't need a physical server , It's about not having to focus on and manage the server , You can use the service directly , It's kind of Service Outsourcing Or say Service hosting , These services are provided by third party providers .
say concretely ,Serverless It means that the server-side logic is implemented by the developer , Running in a stateless computing container , from Event driven , Completely Managed by a third party , Business level status is recorded in A database or storage resource in .
At present, some large domestic companies such as Ali 、 tencent 、 Every drop has already made Serverless Step by step in the business ( Case sharing :2020.06.19 ServerlessDays · China Online).
Serverless And FaaS The connection of
Serverless = FaaS+BaaS , It is a well-known definition in the field at present :
FaaS(Function as a Service): Functions are services
- be responsible for Service side business logic scenario , Need to be implemented by developers themselves , The granularity of services is smaller than that of microservices , It's as small as a function
- Event driven Of Serverless service , Millisecond elastic scaling
- Unable to share memory or data , yes Stateless
- No operation and maintenance is required , Deploy 、 Operation and maintenance are provided by cloud platform
BaaS(Backend as Service): Back end as a service
- be responsible for Common service scenarios , You don't have to develop it yourself , Provided by cloud vendors , Like databases 、 Authentication 、 Message queue 、 Object storage and other services
- yes A stateful Of
The author thinks , Just look FaaS perhaps BaaS, Is a kind of Serverless , It's just that our complete application needs a combination of the two .
good , Here is the official introduction FaaS.
FaaS
As a front end , It's hard for us to access the server on weekdays 、 Operation and maintenance . Suppose you're given a task now , Let you develop an application that has front-end and back-end interaction , And from 0 To 1 Deployment , Do you think you can't do it by yourself , It's a little difficult .
Deployment of traditional applications , We need to do a lot of work : Prepare the server 、 Configuration environment 、 Purchase domain name 、 To configure nginx、……. After the app is released , We also need to consider the issue of operation and maintenance , Online monitoring , Expansion and contraction capacity , Disaster recovery and so on .
Now? , We use FaaS To develop and deploy , None of the above needs to be considered , Just focus on business logic development , because Everything else is entrusted to FaaS platform Helped us deal with .
Concept
FaaS It's a form of serverless computing . adopt FaaS, Can quickly build any type of application and service , It has the characteristics of agile development 、 Automatic elastic expansion capability 、 Free transportation and perfect monitoring facilities . therefore :
- Developers just need to focus on business logic development , No need to manage servers 、 Operation environment, etc IT infrastructure
- FaaS The platform will provide us with computing resources , With elastic 、 Run our code in a reliable way , To achieve millisecond level Stretch and stretch , Coping with peak pressure easily
- The user only needs to base on the actual execution time of the function Pay as you go
therefore , Compared with the traditional development model ,FaaS Greatly improved development and delivery efficiency , It is the general trend of cloud service development in the future . since 2014 In the beginning , stay AWS Lambda after ,Google、IBM、Microsoft、 Ali 、 tencent 、 Huawei and other cloud manufacturers at home and abroad have launched cloud function computing platforms FaaS.
Quick creation FaaS application
There are many ways to develop function computing , such as :Fun Tools 、 Function calculation FC platform 、Serverless VScode、 Cloud development platform . With the help of Alicloud function computing platform , Create quickly through the templates it provides 、 Deploy a Web application , To show you more clearly FaaS What is it? .
This article is based directly on the template , Users can also choose to upload their own application code to deploy directly Web application .
We choose to have front-end interaction 、 Data addition, deletion, modification, etc Todo List application , It's a Front and rear integration ( The front and back-end code is developed in a project 、 debugging 、 Deploy , Efficient and resource efficient ) FaaS application .
service / function
service
An application can be split into multiple services . From the perspective of resource use , A service can be composed of multiple functions . First create the service , And then create the function .
You can see TodoList Create a good service after the application deployment is successful , We can configure the service 、 Delete 、 Check indicators and other operations , You can also configure the functions under it 、 Delete .
function
Function is the unit of system scheduling and running . Functions must be subordinate to services , There can be multiple functions under the same service , All functions under the same service share the same settings , For example, service authorization 、 Log configuration , But they are independent of each other , They don't influence each other .
function code
FaaS Yes A variety of languages They all have good support , For example, alicloud supports Node.js、Python、PHP、Java wait , Developers can use a language they are familiar with , Write the code according to the function interface form provided by the platform . It also means that , In teamwork , You can use a variety of languages to develop complex applications .
Click code execution , You can see here is an online editor , Inside is the template generated code , You can run it here 、 debugging . The front page of the application uses React Realization , Back end services are based on Node Of Express frame .
Function entrance
template.yml
It is our Function information configuration file , Tell cloud vendors our code entry function 、 Trigger type, etc .
The function entry is src/index.handler
, namely src/index.js
In the server code file handler Method , The file code is as follows :
const { Server } = require('@webserverless/fc-express')
const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
// initial todo list
let todos = [
{
id: '123',
text: 'Go shopping',
isCompleted: false,
},
{
id: '213',
text: 'Clean room',
isCompleted: true,
},
];
const staticBasePath = path.join('public', 'build');
const app = express();
// index.html
app.all("/", (req, resp) => {
resp.setHeader('Content-Type', 'text/html');
resp.send(fs.readFileSync('./public/build/index.html', 'utf8'));
});
// Static resource file :js、css、 picture
// static js resources
app.all('/*.js', (req, resp) => {
const filePath = path.join(staticBasePath, req.path);
resp.setHeader('Content-Type', 'text/javascript');
resp.send(fs.readFileSync(filePath, 'utf8'));
});
// static css resources
app.all('/*.css', (req, resp) => {
const filePath = path.join(staticBasePath, req.path);
resp.setHeader('Content-Type', 'text/css');
resp.send(fs.readFileSync(filePath, 'utf8'));
});
// static svg resources
app.all('/*.svg', (req, resp) => {
const filePath = path.join(staticBasePath, req.path);
resp.setHeader('Content-Type', 'image/svg+xml');
resp.send(fs.readFileSync(filePath, 'utf8'));
});
// static png resources
app.all('/*.png', (req, resp) => {
const filePath = path.join(staticBasePath, req.path);
resp.setHeader('Content-Type', 'image/png');
resp.send(fs.readFileSync(filePath, 'utf8'));
});
app.all('/manifest.json', (req, resp) => {
const filePath = path.join(staticBasePath, req.path);
resp.setHeader('Content-Type', 'application/json');
resp.send(fs.readFileSync(filePath, 'utf8'));
});
// Add, delete, modify and check the corresponding api Interface
// list api
app.get('/api/listTodos', (req, resp) => {
resp.send(JSON.stringify(todos));
});
// create api
app.get('/api/createTodo', (req, resp) => {
const { todo: todoStr } = req.query;
const todo = JSON.parse(todoStr);
todos.push({
id: todo.id,
text: todo.text,
isCompleted: todo.isCompleted,
});
resp.send(JSON.stringify(todos));
});
// update api
app.get('/api/updateTodo', (req, resp) => {
const { todo: todoStr } = req.query;
const targetTodo = JSON.parse(todoStr);
const todo = todos.find((todo) => todo.id === targetTodo.id);
if (todo) {
todo.isCompleted = targetTodo.isCompleted;
todo.text = targetTodo.text;
}
resp.send(JSON.stringify(todos));
});
// remove api
app.get('/api/removeTodo', (req, resp) => {
const { id } = req.query
// TODO: Implement methods to filter todos, filtering out item with the same id
// todos = todos.filter();
const todosIndex = todos.findIndex((todo) => todo.id === id);
if (todosIndex !== -1) {
todos.splice(todosIndex, 1);
}
resp.send(JSON.stringify(todos));
});
const server = new Server(app);
// It's exposed http Trigger entry
// http trigger entry
module.exports.handler = function(req, res, context) {
server.httpProxy(req, res, context);
};
You can see , We don't need to serve ourselves ,FaaS The platform will manage for us . This file , There are two important parts :
- 1. Function entrance handler, It's also HTTP Trigger entry , More on that later
// http trigger entry
module.exports.handler = function(req, res, context) {
server.httpProxy(req, res, context);
};
- 2.Web Service and api, Call the corresponding service through routing , For example, the request path is "/" when , Returns the Web Applied html page ; request "/api/*" when , Call the interface to return data
trigger
As I said before ,FaaS It's a kind of Event driven The calculation model of , That is, the execution of a function is event driven , No event triggers , The function doesn't run . Different from the traditional development model , Function does not need to start a service to listen to data , But by binding a ( Or more ) trigger .
trigger It's how the trigger function is executed , We need to create the specified trigger for the function .
FaaS There are many kinds of triggers used ( Different cloud manufacturers have different triggers ), But they all support HTTP、 Object storage 、 Timing task 、 Triggers such as message queues , among HTTP Triggers are the most common .
Take Alibaba cloud functional computing as an example , Introduce several representative types :
Trigger Type
name | describe |
---|---|
HTTP trigger | 1.HTTP Trigger by sending HTTP Request trigger function execution , It is mainly suitable for rapid build Web Service, etc 2.HTTP Triggers support HEAD、POST、PUT、GET and DELETE Mode trigger function 3. You can customize the domain name as HTTP Function mapping is different HTTP Access path 4. Developers can quickly use HTTP Trigger setup Web service and API |
OSS trigger ( Object storage ) | 1.OSS Events can trigger the execution of related functions , Realize to OSS Data in the user-defined processing |
Log service triggers | 1. When the log service regularly gets updated data , Through log service triggers , Trigger function consumes incremental log data , And complete the user-defined processing of the data |
Timing trigger | 1. Automatically trigger function execution at a specified point in time |
API Gateway triggers | 1.API Gateway as event source , The back-end function is set when the request arrives API Gateway time ,API The gateway triggers the execution of the function . Function evaluation will return the execution result to API gateway 2. And HTTP Triggers are similar to , Can be used to build Web application . Compare with HTTP trigger , You can use API The gateway does IP White list or blacklist settings and other advanced operations |
Developers are debugging , If you don't configure triggers , You can also use the console 、 Command line tools perhaps SDK Call function directly to execute .
Let's drive TodoList The trigger of , You can see the created HTTP trigger ,WEB User pass HTTP The request triggers the execution of the function .
Pay attention to the message here : Open the link , Will download a html The attachment , Now we turn it on , Because the static resource file cannot be found , The app doesn't work properly .
You can click on the Custom domain name To use the platform to create for us Temporary domain name open :
You can see , The page and functionality are working . We see the 、 newly added 、 to update 、 Delete , In the console, you can see the request initiated and the result returned
HTTP trigger
The application HTTP The entry function of the trigger Form the following :
// http trigger entry
module.exports.handler = function(req, res, context) {
server.httpProxy(req, res, context);
};
To configure HTTP The function of a trigger can be done by HTTP The request is triggered to execute . In this case, the function can be regarded as a Web Server, Yes HTTP Request for processing , And return the processing result to the calling end .
visit html page 、 Request static resource file , And the request interface , It's all through http Request to trigger the execution of the corresponding function .
You can debug it here :
FaaS frame
At present, there are some mature open source on the market FaaS frame , such as OpenFaaS、funktion、Kubeless、Fission wait , This article introduces the official release of Alibaba cloud this year Midway FaaS frame , It's used to build Node.js Of cloud function Serverless frame , It provides the function's local Development 、 call 、 Test the entire link . It can develop new Serveless application , It also provides solutions to migrate traditional applications to cloud functions of cloud vendors . Ali has been using it for more than a year .
We can use scaffolding @midwayjs/faas-cli
The ability to provide is in Local quick creation 、 debugging 、mock、 Deploy One FaaS application .Serverless There's a big one disadvantages , Namely Strong binding with cloud service provider platform , however Midway Serverles It's anti platform locking , It can A set of code can run on different platforms and runtimes ,Midaway faas Can be deployed Cross cloud vendors , It is deployed to alicloud by default FC, We can also modify the deployment to other platforms , Like Tencent cloud SCF、AWS Lambda.
Midway FaaS The system is also integrated with the cloud workbench , Using the same capabilities as local , Here you choose to log in Alicloud development platform , Use the sample library template to create another TodoList Application for demonstration , It's just that this is for Midway FaaS Built .
Code directory structure It can be simply extracted as :
|-- src
| |-- apis // function code
| |-- config // Create configuration files for different environments
| |-- configuration.ts // Expansion capability configuration
| |-- index.ts // Function code entry file , It contains multiple functions
| |-- components // Front end components
| |-- index.tsx // Front page entry file ( The front end of the application is based on React, if Vue, It is App.vue)
|-- f.yml // Function information configuration file
f.yml The configuration file
service: serverless-hello-world
// Service provider
provider:
name: aliyun
runtime: nodejs10 // Runtime environment and version information
// Function details ( Including function entry 、 Triggers, etc )
functions:
render:
handler: render.handler
events:
- apigw:
path: /*
list:
handler: todo.list
events:
- apigw:
path: /api/list
update:
handler: todo.update
events:
- apigw:
path: /api/update
remove:
handler: todo.remove
events:
- apigw:
path: /api/remove
add:
handler: todo.add
events:
- apigw:
path: /api/add
// Configuration information for the build
package:
include:
- build // Package directory
artifact: code.zip // Package name
In function code, a function corresponds to a api Interface :
After installing dependency , We npm run dev
, Alicloud created a temporary domain name for us to debug :
You can see the requested resource and interface data :
One key deployment , Very convenient .
Charging standard
Traditional applications our services are always taking up resources , and FaaS There is no charge for resources when they are idle , Pay as you go , It can save a lot of money .
Charging standard :
- The number of calls to the function
- Function run time
Because there's a free quota every month , So there is no need to pay for personal daily use .
(PS: But pay special attention to , Deployed applications must be offline in time when not in use , Otherwise, there may be a charge , There are also services that are open 、 The function also must pay close attention to the charging standard , For example, you may want to solve the problem of cold start , The reserved instance function will be enabled , If we don't use it , Be sure to pay attention to manual release , Otherwise, even if it doesn't execute any requests , It will also be charged continuously from the start , The cost is not small )
Cold start
Say again FaaS There's a big concern right now —— Cold start .
FaaS The function in Call for the first time 、 Update the function or call the function again if it has not been called for a long time when , The platform initializes a function instance , This process is Cold start , It takes an average of a few hundred milliseconds .
Delay problem
FaaS Because of the cold start , Function cannot be called immediately , Call latency can affect application performance , For the delay problem of cold start , Cloud service providers are very concerned , We are looking for ways to continuously optimize .
Corresponding to the cold start is the hot start , Hot start When a function is called, there is no need to recreate a new function instance , Instead, it directly reuses the previous function instance . because FaaS If a function is not triggered by an event for a period of time , The cloud service provider will recycle the container resources that run the function , Destroy function instances , therefore , Calling the function again during this period of time that is not recycled is a hot start ; After destruction , Re creation is a cold start .
The reason for the delay
What are the specific operations of cold start ? Take Alibaba cloud for example , The scheduling instance is roughly included 、 Download the decompression code 、 Start the container 、 Start runtime , When the process is over , The function starts executing . So the start-up time of cold start is affected by many factors :
- programing language
There are special studies comparing , Different languages have different cold start times
- Code size
This process is relatively time-consuming in the cold start process , Maybe tens of milliseconds , Maybe a few seconds , Look at the size of the code
- Container to create
The time consuming of this process depends on the cloud service provider
- Configuration etc.
How to optimize
Each big cloud manufacturer already has some best practice of optimization scheme , Developers and cloud vendors need to work together :
Reduce code size :
- Developers can streamline code , Remove useless dependencies , Speed up the process of downloading function code
- For example, Tencent cloud does two levels of caching for the code , Can effectively reduce the code download time
- Resource reuse , Shorten function execution time
- Choose a language with less cold start time
- Choose the right memory : The larger the function memory , The better cold start performance
- Avoid unnecessary configuration
Reduce the cold start frequency
- Use the timer trigger to access the function , This prevents the function instance from being destroyed when it has not been used for a period of time
- Use initializer Function entrance , Function evaluation calls the initialization interface asynchronously , Eliminate time to initialize user code
- Reserved instance
The execution time
FaaS There is also a limitation , The platform will limit the execution time of the function , The process that executes the code after the time limit is exceeded will be forcibly destroyed , therefore FaaS Not suitable for long-running applications . for example AWS Lambda Function is not allowed to run more than 15 minute ( There used to be only 5 minute ), If it exceeds that, it will break down . When using , You should set the timeout value according to your expected execution time , Prevent functions from running longer than expected , And it is recommended to call the client Terminal timeout It should be slightly larger than the function setting timeout, This prevents the execution environment from accidentally exiting .
FaaS Workflow
I believe you have read it here , It should be almost understandable FaaS The workflow of , Let's summarize :
- Developers write function code , It can be edited online or uploaded locally , After completion ,FaaS The platform deploys applications for us , establish Function service
- The client sets the trigger , notice Function service
- If exist Function instance , The function is called directly in the execution environment ; No, , Then go through Cold start ( Scheduling instance 、 Download code 、 Boot instance 、 Start runtime ), Then execute the function
- The function dynamically expands the capacity according to the amount of user requests , Return the content to the user . After the function is executed , If there is no event triggered for a period of time , The function instance will be destroyed ,FaaS Quickly shrink to 0
The impact on the front end
Serverless It's so hot now , What impact does it have on the front end ?
In practice, we found that ,FaaS Help us expand the capability boundary of the front end , As front-end , We can quickly complete the front and back-end development and deployment work by ourselves , We don't have to worry about the server and the problems that we are not good at . The front end also has the opportunity to participate in the development of service-side business logic , Deeper into the business , Create greater value .
Conclusion
This article combines with Alibaba cloud FC、Midway FaaS Framework quick creation FaaS The practice of application , It shows you what FaaS,FaaS workflow , Advantages and disadvantages , It shows FaaS Subvert the charm of traditional development mode . Now? FaaS It has a wide range of application scenarios ,Web Mobile applications such as apps and applets 、AI And machine learning 、 The Internet of things 、 Real time data processing and so on .Serverless Time , Productivity has been greatly improved , Everyone has more opportunities to create infinite possibilities , Let's cheer for the future together !
Reference article
Serverless Handbook—— No service architecture practice manual
Alicloud function calculation documents
Midway Serverless Using document
Tencent cloud function computing cold start Optimization Practice
Serverless Architectures( translation )—(Martin Fowler)
invite to one 's side men of wisdom and valor
Front end team of Zhengcai cloud (ZooTeam), A young, passionate and creative front-end team , It belongs to the research and Development Department of Zhengcai cloud products ,Base In the picturesque Hangzhou . The team has 40 More front-end partners , Average age 27 year , near 3 Cheng is a full stack engineer , A proper youth Stormtrooper . The membership comes from Ali 、 Netease's “ The old ” The soldiers , There are also Zhejiang University 、 China University of science and technology 、 New comers from Hang Dian and other schools . The team is outside the daily business connection , Still in the material system 、 Engineering platform 、 Build a platform 、 Performance experience 、 Cloud Applications 、 Data analysis, visualization and other aspects of technical exploration and practical warfare , Promote and landing a series of internal technical products , Continue to explore the new boundary of front-end technology system .
If you want to change, you've been haunted by things , I hope I can make trouble at first ; If you want to change, you need to think more if you've been warned , But there's no way to break it ; If you want to change you have the ability to do that , But I don't need you ; If you want to change what you want to do, you need a team to support you , But there's no place for you to take people ; If you want to change the set rhythm , Will be “5 Annual working hours 3 Years of working experience ”; If you want to change the original understanding is good , But there's always that blurring of window paper … If you believe in the power of trust , Believe that ordinary people can achieve extraordinary things , I believe I can meet a better myself . If you want to be involved in the process of taking off with the business , Personally promote a deep business understanding 、 Perfect technical system 、 Technology creates value 、 The growth process of the front-end team with spillover influence , I think we should talk about . Anytime , Waiting for you to write something , issue [email protected]