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 implement Hello World with Serverless

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

What this article shares with you is about how Serverless implements Hello World. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Without saying much, let's take a look at it.

In recent years, the update and iteration speed of IT technology is very fast, and there are typical nouns and concepts in each time point. At present, the terms and concepts such as machine learning, deep learning and reinforcement learning in the field of artificial intelligence are very hot. At the same time, the development of technology such as blockchain and Internet of things is also extremely hot.

In the field of cloud computing, there is such a technology that is regarded as a "tuyere project" by many cloud manufacturers, which can even subvert some of the existing patterns in cloud computing. For this reason, cloud manufacturers, including AWS, Google, Tencent Cloud, Aliyun, and so on, have invested a lot of manpower and energy in related product construction, which is Serverless technology.

What is Serverless?

Serverless can be said to be a kind of architecture, a product of the development of cloud computing. As for what is Serverless, there may be no one who can't give a clear concept. If you have to give a concept, you can refer to Martin Fowler's definition of Serverless in "Serverless Architectures":

Serverless was first used to describe applications that significantly or fully incorporate third-party, cloud-hosted applications and services, to manage server-side logic and state. These are typically "rich client" applications-think single-page web apps, or mobile apps-that use the vast ecosystem of cloud-accessible databases (e.g., Parse, Firebase), authentication services (e.g., Auth0, AWS Cognito), and so on. These types of services have been previously described as "(Mobile) Backend as a service", and I use "BaaS" as shorthand in the rest of this article. Serverless can also mean applications where server-side logic is still written by the application developer, but, unlike traditional architectures, it's run in stateless compute containers that are event-triggered, ephemeral (may only last for one invocation), and fully managed by a third party. One way to think of this is "Functions as a Service" or "FaaS". (Note: The original source for this name-a tweet by @ marak-isno longer publicly available.) AWS Lambda is one of the most popular implementations of a Functions-as-a-Service platform at present, but there are many others, too.

Of course, this description seems to be very long, and it is a bit dry and difficult to read. However, you can simply and roughly think of Serverless as BaaS + FaaS. If you use a picture to represent the above description, it can be:

At this point, different people may have different outlines of Serverless, but there may be a general question, how do I use Serverless? Upload my project to the cloud server? Or is it like a framework for writing code? What can I get with it? Performance improvement? Increase in efficiency? A reduction in costs?

First, let's take a common Web service as an example:

In this diagram, routing rules, authentication logic and other complex business codes may be involved in the server. at the same time, the development team has to put a lot of effort into the operation and maintenance of this server. including whether the server needs to be expanded when the number of customers suddenly increases; whether the scripts and business codes on the server are still running healthily; whether hackers are constantly attacking the server That is, when we switch this idea to the logic of Serverless, the figure above looks like this:

It can be considered that when the client and database remain unchanged, the server changes greatly, and the routing module and authentication module that need 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 code of these two parts, but only needs to maintain the relevant rules continuously. At the same time, the business code is also divided into function granularity, and different functions represent different functions. At the same time, under this structure, we can no longer see the existence of the server, because the purpose of Serverless is to let users only pay attention to their own business logic, so some security issues and resource scheduling problems (such as the surge in the number of users, how to achieve automatic expansion, etc.) are all left to cloud vendors, and compared with traditional projects, traditional projects are running regardless of whether users visit them or not. For Serverless, the function will be activated and executed only when the user initiates a request. Charge by quantity. Relatively speaking, it can be supported when there is traffic, and there will be no expenditure when there is no traffic, and the cost will be further reduced.

Through analysis and description, it is not difficult to see how the Serverless architecture is different from the traditional development model. But the problem is, there is no need for us to do a lot of work, all handed over to the cloud vendors to do, so what do we do?

Using Serverless architecture, users do not need to maintain the server themselves, and do not need to worry about the various performance indicators and resource utilization of the server, but can make users pay more time and energy to care about the state and logic of the application itself. At the same time, the deployment of the Serverless application itself is very easy, as long as we upload the basic code, for example, the Python program only needs to upload its logic and dependency package, the languages such as Calgary + and Go only need to upload its binary files, and Java only needs to upload its Jar package, etc., and there is no need to use Puppet, Chef, Ansible or Docker for configuration management, which greatly reduces the cost of operation and maintenance. For operators, the Serverless architecture no longer needs to monitor the underlying data, such as disk usage, CPU utilization, etc., and can focus more on monitoring the metrics of the application itself. At the same time, in the Serverless architecture, the role of operators will change, deployment will become more automated, and monitoring will be more oriented to the application itself.

All in all, Serverless is developed on the traditional container technology and service grid. It refers more to the combination of back-end services and functional services. For developers, they will pay more attention to functional service providers, so that users can only pay attention to their own business logic. Serverless is the inevitable outcome of the development of cloud computing to a certain stage, cloud computing as inclusive technology, the final development must be green technology (maximize the use of resources, reduce the waste of idle resources), popular technology (low cost, including learning costs and use costs) products, and Serverless will well explain these! Serverless architecture is said to "really achieve the original goal of cloud computing", although this statement is somewhat exaggerated, but on the other hand, it also shows people's expectations and confidence in Serverless architecture. Since it was proposed in 2012, Serverless architecture has experienced more than 7 years and is gradually becoming mature.

Getting started with Serverless

Speaking of Serverless, we have to say that BaaS and FaaS,BaaS services are more provided / maintained by cloud vendors, so developers can focus more on the FaaS level, or at the functional computing level.

Next, let's experience Serverless. Take Tencent Cloud as an example. Through the Tencent Cloud console, select the cloud functions under the Serverless category:

Next you can see a part of the Serverless: the function evaluation section. At this point, we can create a new function, do some basic testing, and experience the difference between Hello World under Serverless and our traditional Hello World.

Create a new function:

Choose the runtime (that is, the programming language we want to use):

Write the code:

Click finish to save the code

Do code testing:

You can see the test results:

At this point, we have completed the basic writing of a function, but think about it carefully: it seems to be similar to some online programming tools, which can be written and run online. Where does BaaS embody? Reflected in the provision of an operating environment? Besides writing a hello world, what else can I do?

Next, we have the experience of triggers. The so-called trigger means that our function is generally "rest". Only when something touches it and activates it will we get up and work. How did we just get the function "up and running"? It is through the "test button" on the screen, so this is also a trigger. So besides this trigger, what else is there?

As you can see, the triggers provided to us by Tencent Cloud include:

Timing trigger (as the name implies, is to set a time to trigger a function, for example, what time to trigger every day, or how often to trigger, this kind of operation is suitable for us to do scheduled tasks, such as data collection / data aggregation, message push and so on. )

COS trigger we may store files to the file system, in traditional CVM, we can save to the machine itself, but under Serverless architecture, because the function is stateless, so we can not do persistence, so we need an external media. "object storage" is our commonly used persistent file product, which can store some files on it. Such as pictures, documents, executable programs... At the same time, we can also trigger our function by saving it to the above file. For example, when an image is uploaded to the object storage, the function calculation will download the image and perform image compression and watermark processing.

CMQ topic subscription trigger CMQ topic subscription means that when there is a queue in the CMQ, you can send the content to the cloud function for consumption processing.

The Ckafka trigger is basically the same as the CMQ topic subscription trigger mentioned above, except that this is Ckafka. When messages appear in the Ckafka (either each trigger or the maximum number of triggers), it will make the function "get up to work", process the data and complete the consumption.

API gateway trigger is a service that is very closely related to the function. Triggered by the API gateway, the function can be accessed. What does it mean to be interviewed? In other words, it can be used directly through the browser / interface, so the combination of API gateway triggers and cloud functions can usually be used as websites, backend services, and so on.

At this point, we can set up an API gateway trigger to see the interesting collision caused by the combination of the function and the API gateway:

A preliminary study of API Gateway and function

Let's create a new API gateway service:

After the creation is completed, the system will assign us an address:

Open this address through a browser:

At this time, we have successfully built a Web service, and the backend will show Hello World. If it is a traditional development condition, what needs to be done to make such a page?

Develop a Hello World using the framework

Purchase the server and configure the server environment

Upload locally developed projects to the server

Purchase domain name / use server IP, bind our project

This process may involve commonly used Web frameworks (such as Django,Spring,Express … ), server software (Nginx,Apache,Tomcat... ), and so on, and even we have to consider how much traffic is on the site, how much memory machines to buy, how many processes to start, how many threads, and how to optimize the server.

But what we just did was:

Establish function

Add API gateway trigger

We don't have to care about the rest of the operation, we can focus more on "Coding".

Do something interesting with functions and API gateways

In production and life, we often need to obtain the IP address to do some work, for example, I made a website, the user signature system of this website includes the user's IP, and the client wants to obtain the user's IP is a more complicated process. In general, it is necessary to access the IP interface of the server to obtain the corresponding IP address of the client. So what should we do through function calculation and API gateway?

I just mentioned triggers. Each flip-flop has a specification with the function. What kind of format data I give you can be seen through the test template below the function:

From here, you can see a structure of the API gateway and function convention:

{"requestContext": {"serviceId": "service-f94sy04v", "path": "/ test/ {path}", "httpMethod": "POST", "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "identity": {"secretId": "abdcdxxxxxxxsdfs"}, "sourceIp": "10.0.2.14", "stage": "release"} "headers": {"Accept-Language": "en-US,en,cn", "Accept": "text/html,application/xml,application/json", "Host": "service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com", "User-Agent": "User Agent String"}, "body": "{\" test\ ":\" body\ "}," pathParameters ": {" path ":" value "} "queryStringParameters": {"foo": "bar"}, "headerParameters": {"Refer": "10.0.2.14"}, "stageVariables": {"stage": "release"}, "path": "/ test/value", "queryString": {"foo": "bar", "bob": "alice"}, "httpMethod": "POST"}

At the same time, the function passes this structure to the developer as one of the input parameters. For example, Tencent Cloud names this parameter event, that is, developers can parse the content related to the API gateway through the event parameter of the function entry.

So what is the entrance to a function?

The entry function is actually the file name + method name in the user code, in which the default setting is the main_handler method in the index file. You can see that the main_handler method does have a parameter event, which is the data structure passed by the trigger.

Through the above data interface, we can see that sourceIp in requestContext is the user's IP address, so can we return the IP directly to the user to achieve the IP query function?

#-*-coding: utf8-*-import jsondef main_handler (event, context): return ({"ip": event ['requestContext'] [' sourceIp']})

After writing four lines of code, we bind the API gateway and can see through browser access:

Yes, such a function can be done with only four lines of code.

Let's talk about Serverless.

We have just started the cloud function, and we also have a preliminary understanding of the cloud function, so let's talk about the advantages and disadvantages of Serverless architecture.

Advantages

Elastic expansion

In the traditional sense, how much traffic a server can accept and how much the peak is, we need to evaluate it. At the same time, we have to maintain and update the data at a later stage. But under the Serverless architecture, users do not need to think about this problem, cloud vendors will achieve self-scaling capabilities for users. When the platform receives the first event that triggers the function, it starts the container to run your code. If a new event is received at this time, and the first container is still processing the previous event, the platform launches a second code instance to handle the second event. This automatic zero-management horizontal scaling of SCF will continue until there are enough code instances to handle all workloads. When concurrency occurs, cloud manufacturers will launch multiple containers to deal with "traffic peaks". Compared with traditional servers, Serverless architecture or cloud function is really convenient at this level.

Pay by quantity

Pay-by-quantity is an advantage of Serverless architecture. We have to pay for the cost of traditional servers, regardless of whether there is traffic or not, and the server configuration has to be configured according to the maximum traffic in a certain period of time, so the expenditure is actually unreasonable. However, the function calculation is actually charged by quantity, and the price is relatively low, especially for projects with large differences in the peak and trough of resource consumption in different periods of time.

Shortcoming

Cold start

When it comes to the shortcomings of Serverless architecture, we have to say that cold startup is common, whether it is AWS or Google, Tencent Cloud or Ali Cloud. Of course, various cloud manufacturers are also trying to reduce the cold start rate through a variety of strategies and programs.

Debugging difficulty

Another disadvantage of cloud function is that it is difficult to debug, because it provides us with a container for function operation, and many basic businesses are bound with vendors, which leads to debugging difficulties. For example, if we want to debug a function, we can debug it by simulating some triggers, but if some private network resources are involved in the function, such as those related to redis and can only be accessed through vpc, then the difficulty of local debugging will be multiplied, and online debugging may be very poor because the log output is too slow.

With the development of cloud computing, Serverless is an inevitable product. Serverless as a new technology or a new architecture, it is difficult to describe clearly through an article, its advantages and disadvantages are not just the two described above, we just picked a more typical list. When using Serverless, there will be a lot of pits, sometimes from getting started to giving up, sometimes it will be really convenient, and from giving up to entering the pit, but anyway, as a relatively new thing, Serverless has more areas and values waiting for us to develop and explore, including Serverless application areas, use experience and so on.

Serverless architecture is said to "really achieve the original goal of cloud computing", although this statement is somewhat exaggerated, but on the other hand, it also shows people's expectations and confidence in Serverless architecture. Since it was proposed in 2012, Serverless architecture has experienced more than 7 years and is gradually becoming mature.

This is how Serverless implements Hello World. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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

Servers

Wechat

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

12
Report