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 reuse the configuration idea into the platform system by Serverless

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

In this issue, the editor will bring you about how Serverless reuses the idea of configuration into the platform system. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

What is Serverless?

Serverless consists of two parts, Server and Less.

The former can be understood as that the scope of the solution is on the server side.

The latter can be translated into a small number of

Taken together, it is a server-side solution with less server intervention.

The opposite of Serverless is Serverfull, and the corresponding concepts may be easier to understand.

In the era of Serverfull, the R & D delivery process generally has three roles: RD,PM,QA.

RD develops the function according to PM's PRD, delivers it to QA for testing, and publishes it to the server after the test is completed. The operation and maintenance personnel plan the specification and quantity of servers, the deployment of computer rooms, the expansion and reduction of nodes, and so on. This era, which is more handled by manpower, is the era of Serverfull.

And then entered the era of DevOps. In this era, operators develop a set of operation and maintenance console, which allows R & D students to carry out service observation, data query, operation and maintenance processing and so on on the console. The work of operation and maintenance students is much easier, and this stage mainly releases the manpower of operation and maintenance students.

In the Serverless era, this set of OPS console has more and more capabilities, which can realize automatic expansion and reduction according to configuration, performance monitoring, DevOps pipelining, etc., while invading the R & D process side, such as automatic release pipeline, compilation and packaging, code quality monitoring, grayscale release, elastic scaling and other processes basically do not need human processing, this is the Serverless era.

How to use Serverless

I'm sure you've had the experience of writing code on the left and showing the execution effect on the right on a Web interface.

Write a block of code, the amount of code will not be very large.

The code runs fast.

Support for multiple programming languages

Can support unpredictable flow peak impact.

Abstractly, the front end only needs to pass the code snippet and programming language identity to the Server side and wait for the response result. The Server side can classify and preprocess runtime for different programming languages.

What does Serverless do?

Many people regard Serverless as FC (function compute: function calculation). Using function calculation, there is no need for the business to build its own IT infrastructure, just need to encode and upload code. Function computing will prepare computing resources for you as needed, run flexibly and reliably, and provide governance capabilities such as trace, log query, monitoring and alarm.

There are services and functions in FC. A service can contain multiple functions. We can understand it in terms of microservices. We have built a microservice architecture through golang or java, and the FC service is the class, and the FC function is a method in the class.

The difference is that the microservices built by Java can only run java class code, while golang classes can only run code written by go, while FC functions can install runtime in different languages and support running programs in different languages.

After understanding the analogy, let's take a look at how to call the function of FC. There is a concept of trigger in a general FC solution. For example, HTTP trigger, object storage trigger, log service trigger, scheduled task trigger, CDN trigger, message queue trigger and so on. Triggers are abstract endpoints for FC function calls. For example, HTTP triggers are generally analogous to a http request event of a gateway, or upload an image under a specified object storage path. The entry of these triggering events can be a trigger.

After the trigger generates an event, the FC function can be called, and the logic executed by the function can be to download a picture or register a user.

So logical processing from triggers to FC functions is a life cycle of FC.

So how does FC achieve high availability?

In fact, the underlying code of each function runs on an IaaS platform. Using IaaS resources, we can set the memory configuration needed for each function to run the code, such as a minimum of 128m, a maximum of 3G and so on. Developers do not need to care about what kind of server the code is running on, how many function instances are started to support the current scenario, and do not need to pay attention to the elastic scaling problems behind them, which are converged after FC.

There are two highly available strategies:

Set the number of concurrent instances to the function, such as three, so when three requests come in, the function starts only one instance, but starts three threads to run the logic

After the thread reaches the upper limit, another instance of the function is pulled.

So how does Serverless improve its effectiveness?

High efficiency: if you add a new language, you only need to create a corresponding FC function of Runtime

High availability: high availability is guaranteed by multi-thread and multi-instance, and the expansion and reduction of function instances is handled by FC without any configuration by operation and maintenance staff.

Low cost: when there is no trigger request, the function instance will not be pulled or billed, so the cost of FC consumption is very low during the traffic trough or at night.

How to create a FC1 on the cloud platform. Create a service

First create a new service name

Select the area where the service is deployed (behind to help you deploy in the nearest target computer room)

Choose whether to open the debug log (the development process is on and can be turned off when running online).

two。 Create function

With the service in place, you can create functions, such as selecting functions based on http requests.

Select the service bound by the function

Set the function name

Select runtime environment

Whether the elasticity of function instances is required

Function entry (the target method called directly by the trigger)

Function execution memory

Function execution timeout

Sets the concurrency of the instance.

Configure the trigger, for example, select the HTTP trigger, and then bind the function name to the trigger. Since it is http access, you can choose the authentication method, authentication method, and request method POST or GET.

3. Code writing

When the function is created, enter the function, and you can see the description, code execution history, trigger type, log query page, and so on.

If it is a HTTP trigger, you need to configure the http trigger path.

Similar to a function in a class, the context request is called here and executed directly.

Python code as an example:

#-*-coding: utf-8-*-import loggingimport urllib.parseimport timeimport subprocessdef handler (environ, start_response): context = environ ['fc.context'] request_uri = environ [' fc.request_uri'] for k, v in environ.items (): if k.startswith ('HTTP_'): pass try: request_body_size = int (environ.get (' CONTENT_LENGTH') 0) except (ValueError): request_body_size = 0 # get the code request_body passed by the user = environ ['wsgi.input'] .read (request_body_size) codeStr = urllib.parse.unquote (request_body.decode ("GBK")) # because the object in body has two attributes code and input Here, get the user code and the user input codeArr = codeStr.split ('&') code = codeArr [0] [5:] inputStr = codeArr [1] [6:] # Save the user code as a py file and put it in the / tmp directory With the timestamp as the file name fileName ='/ tmp/' + str (int (time.time () + '.py' f = open (fileName, "w") # here the preset introduces the time library f.write ('import time\ r\ n') f = open (fileName, "a") f.write (code) f.close () # create child process Execute the user code py file p = subprocess.Popen ("python" >) you just saved

The process is as follows:

The code snippet is passed in at the front end, and the format is a string

Get the incoming code string in the FC function, and intercept the code content and input content

Save the code as a py file, named after the timestamp, in the / tmp directory of the FC function. Each function has its own independent / tmp directory.

Import time library code

Create a subprocess through subprocess, and execute the py file saved in the / tmp directory by shell through the py command

Finally, the execution result is read and returned to the front end.

The whole process only needs the front end to transfer the code to the FC function, and each link of the whole Server side does not need the concern of R & D and operation and maintenance students, which embodies the essence of Serverless.

Coordinate workflows with Serverless

The workflow can arrange the execution of tasks in order, branch, parallel, etc., and then the process will reliably coordinate the execution of the task according to the set steps, track the state transition of each task, and execute the defined retry logic if necessary to ensure the smooth execution of the process.

Workflow process monitors the execution of workflow by logging and auditing, which is convenient for process diagnosis and debugging.

The core of the flexibility and expansibility of the system is the orchestration of services, so what we need to do is to sort out, split, pull away the functions that the existing internal users want to customize, combine the stateless capabilities provided by FC, and arrange these function points to realize the customization of business processes.

Businesses that need to configure workflows flexibly

For example, in a catering scene, different businesses can configure different payment methods, such as WeChat Pay, UnionPay and Alipay. Can support three at the same time, can also be a certain one, can be paid, can also be points exchange and so on. If there is not a good configuration process solution, a large number of hard-coding rule judgment conditions will appear in the system, and the system iteration is on the run, which is an unsustainable process.

With the workflow built by FC, this problem can be solved elegantly.

The above process is the process on the user side, and then needs to be converted into the process on the program side, and the workflow is created through the constrained FDL.

The FDL code is as follows:

Version: v1beta1type: flowtimeoutSeconds: 3600steps:-type: task name: generateInfo timeoutSeconds: 300 resourceArn: acs:mns:::/topics/generateInfo-fnf-demo-jiyuan/messages pattern: waitForCallback inputMappings:-target: taskToken source: $context.task.token-target: products source: $input.products-target: supplier source: $input.supplier-target: address source: $input.address-target: orderNum Source: $input.orderNum-target: type source: $context.step.name outputMappings:-target: paymentcombination source: $local.paymentcombination-target: orderNum source: $local.orderNum serviceParams: MessageBody: $Priority: 1 catch:-errors:-FnF.TaskTimeout goto: orderCanceled-type: task name: payment timeoutSeconds: 300 resourceArn: acs:mns:::/topics/payment -fnf-demo-jiyuan/messages pattern: waitForCallback inputMappings:-target: taskToken source: $context.task.token-target: orderNum source: $local.orderNum-target: paymentcombination source: $local.paymentcombination-target: type source: $context.step.name outputMappings:-target: paymentMethod source: $local.paymentMethod-target: orderNum source: $local.orderNum-target: price Source: $local.price-target: taskToken source: $input.taskToken serviceParams: MessageBody: $Priority: 1 catch:-errors:-FnF.TaskTimeout goto: orderCanceled-type: choice name: paymentCombination inputMappings:-target: orderNum source: $local.orderNum-target: paymentMethod source: $local.paymentMethod-target: price source: $local.price -target: taskToken source: $local.taskToken choices:-condition: $.paymentMethod = = "zhifubao" steps:-type: task name: zhifubao resourceArn: acs:fc:cn-hangzhou:your_account_id:services/FNFDemo-jiyuan/functions/zhifubao-fnf-demo inputMappings:-target: price source: $input.price -target: orderNum source: $input.orderNum-target: paymentMethod source: $input.paymentMethod-target: taskToken source: $input.taskToken-condition: $.paymentMethod = = "weixin" steps:-type: task name: weixin resourceArn: acs:fc:cn-hangzhou : your_account_id:services/FNFDemo-jiyuan.LATEST/functions/weixin-fnf-demo inputMappings:-target: price source: $input.price-target: orderNum source: $input.orderNum-target: paymentMethod source: $input.paymentMethod-target: taskToken source: $input.taskToken -condition: $.paymentMethod = = "unionpay" steps:-type: task name: unionpay resourceArn: acs:fc:cn-hangzhou:your_account_id:services/FNFDemo-jiyuan.LATEST/functions/union-fnf-demo inputMappings:-target: price source: $input.price-target: orderNum Source: $input.orderNum-target: paymentMethod source: $input.paymentMethod-target: taskToken source: $input.taskToken default: goto: orderCanceled-type: task name: orderCompleted resourceArn: acs:fc:cn-hangzhou:your_account_id:services/FNFDemo-jiyuan.LATEST/functions/orderCompleted end: true-type: task name: orderCanceled resourceArn: acs:fc:cn-hangzhou:your_ Account_id:services/FNFDemo-jiyuan.LATEST/functions/cancerOrder

The example shows that Serverless-based FC can implement flexible workflows.

How does the process trigger?

After the user has selected the product and filled in the address, the process can be triggered automatically by pulling the item and order context.

In the context of micro-services, many capabilities are not closed-loop in single code logic, but often connect multiple business systems, such as cascading multiple OpenAPI interfaces.

If you want to use the process engine, you need to carry out relevant license authentication:

@ Configurationpublic class FNFConfig {@ Bean public IAcsClient createDefaultAcsClient () {DefaultProfile profile = DefaultProfile.getProfile ("cn-xxx", / / region ID "ak", / / AccessKey ID "sk" of RAM account); / / RAM account AccessKey Secret IAcsClient client = new DefaultAcsClient (profile); return client;}}

How the processes in the startFNF code are concatenated:

Enter the name of the process to start, such as each order number as the startup process instance name

Process instance name after process startup

Start input parameters, such as business parameters, such as a json that contains contextual information such as goods, merchants, addresses, orders, and so on.

@ GetMapping ("/ startFNF/ {fnfname} / {execuname} / {input}") public StartExecutionResponse startFNF (@ PathVariable ("fnfname") String fnfName, @ PathVariable ("execuname") String execuName, @ PathVariable ("input") String inputStr) throws ClientException {JSONObject jsonObject = new JSONObject (); jsonObject.put ("fnfname", fnfName) JsonObject.put ("execuname", execuName); jsonObject.put ("input", inputStr); return fnfService.startFNF (jsonObject);}

Take another look at fnfService.startFNF:

Override public StartExecutionResponse startFNF (JSONObject jsonObject) throws ClientException {StartExecutionRequest request = new StartExecutionRequest (); String orderNum = jsonObject.getString ("execuname"); request.setFlowName (jsonObject.getString ("fnfname")); request.setExecutionName (orderNum); request.setInput (jsonObject.getString ("input")); JSONObject inputObj = jsonObject.getJSONObject ("input"); Order order = new Order (); order.setOrderNum (orderNum) Order.setAddress (inputObj.getString ("address")); order.setProducts (inputObj.getString ("products")); order.setSupplier (inputObj.getString ("supplier")); orderMap.put (orderNum, order); return iAcsClient.getAcsResponse (request);}

The first part is to start the process.

The second part is to create order alignment and simulate storage.

How is the front end called?

At the front end, when you click the next step on the select goods and merchants page, call the HTTP protocol interface / startFNF/ {fnfname} / {execuname} / {input} through GET. Corresponds to the Java method above.

Fnfname: name of the process to start

Execuname: randomly generate uuid as the order number and as the name of the startup process instance

Input: the product, merchant, order number, and address are constructed as JSON strings into the process.

SubmitOrder () {const orderNum = uuid.v1 () this.$axios.$get ('/ startFNF/OrderDemo-Jiyuan/'+orderNum+'/ {\ n' +'"products": "'+ this.products+'",\ n' +'"supplier": "'+ this.supplier+'",\ n' +'"orderNum": "'+ orderNum+'" \ n' +'"address": "'+ this.address+'"\ n' +'}') .then ((response) = > {console.log (response) if (response.message = = "success") {this.$router.push ('/ orderdemo/' + orderNum) })} 1. GenerateInfo node

Take a look at the first FDL node definition:

-type: task name: generateInfo timeoutSeconds: 300resourceArn: acs:mns:::/topics/generateInfo-fnf-demo-jiyuan/messages pattern: waitForCallback inputMappings:-target: taskToken source: $context.task.token-target: products source: $input.products-target: supplier source: $input.supplier-target: address source: $input.address-target: orderNum source: $input.orderNum -target: type source: $context.step.name outputMappings:-target: paymentcombination source: $local.paymentcombination-target: orderNum source: $local.orderNum serviceParams: MessageBody: $Priority: 1 catch:-errors:-FnF.TaskTimeout goto: orderCanceled````-name: node name -timeoutSeconds: timeout, waiting time, jump to the orderCanceled node pointed by the goto branch after the timeout;-pattern: set to waitForCallback, indicating the need to wait for confirmation;-inputMappings: input parameter of this node;-Token;-products automatically generated by taskToken:Serverless workflow: selected merchant;-supplier: selected merchant;-address: delivery address;-orderNum: order number;-outputMappings: output parameter of this node -paymentcombination: the payment method supported by the merchant;-orderNum: order number;-catch: catch exceptions and jump to other branches. Serverless workflow supports the integration of multiple cloud services, using other services as execution units of task steps. Service integration is implemented through FDL expressions. In task steps, you can use resourceArn to define the target service of the integration and pattern to define the integration pattern. Configuring / topics/generateInfo-fnf-demo-jiyuan/messages information in resourceArn integrates the MNS message queuing service, which sends a message to the generateInfo-fnf-demo-jiyuanTopic when the generateInfo node triggers. The body and parameters of the message are specified by zhi'd in the serviceParams object. MessageBody is the message body, and the configuration $indicates that the message body is generated through the input mapping inputMappings. GenerateInfo-fnf-demo function: this message sent to generateInfo-fnf-demo-jiyuanTopic contains product information, merchant information, address, and order number, indicating the beginning of an order placing process. Since a message is sent, there must be an accepted message for subsequent processing. In the function calculation console, create a service, and create an event trigger function named generateInfo-fnf-demo under the service. Here, select Python Runtime17.png! [17.png] (https://ucc.alicdn.com/pic/developer-ecology/89d43991349e422e8bda26f905cce0c4.png) creates MNS triggers, and select to listen to generateInfoMuz, Fnfo, demotion, jiyuanTopicGlug! [18.png]) (https://ucc.alicdn.com/pic/developer-ecology/4612a6cd4ba54dc38a79cebf7cacc3ac.png) opens the message service MNS console. [19.png] (https://ucc.alicdn.com/pic/developer-ecology/f51714a2ee594dcba4bbbc888c42288c.png) then write the function code:-- coding: utf-8-- import loggingimport jsonimport timeimport requestsfrom aliyunsdkcore.client import AcsClientfrom aliyunsdkcore.acs_exception.exceptions import ServerExceptionfrom aliyunsdkfnf.request.v20190315 import ReportTaskSucceededRequestfrom aliyunsdkfnf.request.v20190315 import ReportTaskFailedRequestdef handler (event, context): 1. Build Serverless workflow Clientregion = "cn-hangzhou" account_id = "XXXX" ak_id = "XXX" ak_secret = "XXX" fnf_client = AcsClient (ak_id, ak_secret, region) logger = logging.getLogger () # 2. The information in event receives the message content in Topic generateInfo-fnf-demo-jiyuan and converts it into Json object bodyJson = json.loads (event) logger.info ("products:" > code is divided into five parts:-build Serverless workflow Client -the information in the event is received into the message content in the TopicgenerateInfo-fnf-demo-jiyuan and converted into a Json object;-to determine which merchants use what combination of payment methods. The example here is relatively simple and rough. Normally, it should be obtained using metadata configuration. For example, there is a configuration function of merchant information in the system, by configuring which payment methods the merchant supports on the interface, forming metadata configuration information, providing query interfaces, and querying here;-calling the interface exposed by the Java service to update the order information, mainly to update the payment method;-responding to the generateInfo node and returning data, where the order number and payment method are returned. Because the pattern of this node is waitForCallback, you need to wait for the response result. The generateInfo-fnf-demo function is configured with a MNS trigger, which triggers the execution of the generateInfo-fnf-demo function when the TopicgenerateInfo-fnf-demo-jiyuan has a message. # 2. Payment node is followed by the FDL code definition of payment:

Type: task

Name: payment

TimeoutSeconds: 300

ResourceArn: acs:mns:::/topics/payment-fnf-demo-jiyuan/messages

Pattern: waitForCallback

InputMappings:

FnF.TaskTimeout

Goto: orderCanceled

Target: taskToken

Source: $context.task.token

Target: orderNum

Source: $local.orderNum-target: paymentcombination source: $local.paymentcombination

Target: type

Source: $context.step.name outputMappings:-target: paymentMethod source: $local.paymentMethod

Target: orderNum

Source: $local.orderNum-target: price source: $local.price

Target: taskToken

Source: $input.taskToken serviceParams: MessageBody: $

Priority: 1

Catch:

Errors:

When the process flows to the payment node, the user can go to the payment page.

The payment node sends a message to the Topicpayment-fnf-demo-jiyuan of MNS, triggering the payment-fnf-demo function.

Payment-fnf-demo function:

The payment-fnf-demo function is created in a similar way to the generateInfo-fnf-demo function.

#-*-coding: utf-8-*-import loggingimport jsonimport osimport timeimport loggingfrom aliyunsdkcore.client import AcsClientfrom aliyunsdkcore.acs_exception.exceptions import ServerExceptionfrom aliyunsdkcore.client import AcsClientfrom aliyunsdkfnf.request.v20190315 import ReportTaskSucceededRequestfrom aliyunsdkfnf.request.v20190315 import ReportTaskFailedRequestfrom mns.account import Account # pip install aliyun-mnsfrom mns.queue import * def handler (event Context): logger = logging.getLogger () region = "xxx" account_id = "xxx" ak_id = "xxx" ak_secret = "xxx" mns_endpoint = "http://your_account_id.mns.cn-hangzhou.aliyuncs.com/" queue_name =" payment-queue-fnf-demo "my_account = Account (mns_endpoint, ak_id Ak_secret) my_queue = my_account.get_queue (queue_name) # my_queue.set_encoding (False) fnf_client = AcsClient (ak_id, ak_secret) Region) eventJson = json.loads (event) isLoop = True while isLoop: try: recv_msg = my_queue.receive_message (30) isLoop = False # body = json.loads (recv_msg.message_body) logger.info ("recv_msg.message_body:==" >

The core idea of the above code is to wait for the user to select a payment method on the payment page to confirm the payment. The queue of MNS is used to simulate waiting. The loop waits for the message in the queue payment-queue-fnf-demo to be received, and when the message is received, the order number, the specific payment method and amount selected by the user are returned to the payment node.

Front end Select payment method page:

After passing the generateInfo node, the payment method information of the order is already available, so for the user, after filling in the product, merchant and address, the page that jumps to is the confirmation payment page and contains the payment method supported by the merchant.

After entering the page, the interface exposed by the Java service is requested to obtain the order information, and different payment methods are displayed on the page according to the payment method.

When the user selects a payment method and clicks the submit order button, a message is sent to the payment-queue-fnf-demo queue, informing the payment-fnf-demo function to continue the subsequent logic.

A function of HTTP trigger type is used to implement the logic of sending messages to MNS. The paymentMethod-fnf-demo function code:

#-*-coding: utf-8-*-import loggingimport urllib.parseimport jsonfrom mns.account import Account # pip install aliyun-mnsfrom mns.queue import * HELLO_WORLD = b'Hello world!\ n'def handler (environ, start_response): logger = logging.getLogger () context = environ ['fc.context'] request_uri = environ [' fc.request_uri'] for k V in environ.items (): if k.startswith ('HTTP_'): # process custom request headers pass try: request_body_size = int (environ.get (' CONTENT_LENGTH') 0) except (ValueError): request_body_size = 0 request_body = environ ['wsgi.input'] .read (request_body_size) paymentMethod = urllib.parse.unquote (request_body.decode ("GBK")) logger.info (paymentMethod) paymentMethodJson = json.loads (paymentMethod) region = "cn-xxx" account_id = "xxx" ak_id = "xxx" ak_secret = "xxx" mns_endpoint = "http://your_account_id.mns.cn-hangzhou.aliyuncs.com/" queue_name =" payment-queue-fnf-demo "my_account = Account (mns_endpoint Ak_id, ak_secret) my_queue = my_account.get_queue (queue_name) output = "{\" paymentMethod\ ":\"% s\ ",\" price\ ":\"% s\ ">

The logic of the function is simple: send the payment method and amount selected by the user to the queue payment-queue-fnf-demo of MNS.

3. PaymentCombination node

The paymentCombination node is a routing node. By judging a parameter to route to different nodes, the paymentMethod is used as the judgment condition:

-type: choice name: paymentCombination inputMappings:-target: orderNum source: $local.orderNum-target: paymentMethod source: $local.paymentMethod-target: price source: $local.price-target: taskToken source: $local.taskToken choices:-condition: $.paymentMethod = = "zhifubao" steps:-type: task name: zhifubao resourceArn: acs:fc : cn-hangzhou:your_account_id:services/FNFDemo-jiyuan/functions/zhifubao-fnf-demo inputMappings:-target: price source: $input.price-target: orderNum source: $input.orderNum-target: paymentMethod source: $input.paymentMethod-target: taskToken Source: $input.taskToken-condition: $.paymentMethod = = "weixin" steps:-type: task name: weixin resourceArn: acs:fc:cn-hangzhou:your_account_id:services/FNFDemo-jiyuan.LATEST/functions/weixin-fnf-demo inputMappings:-target: price source: $input.price -target: orderNum source: $input.orderNum-target: paymentMethod source: $input.paymentMethod-target: taskToken source: $input.taskToken-condition: $.paymentMethod = = "unionpay" steps:-type: task name: unionpay resourceArn: acs:fc:cn-hangzhou:your_account_id:services/FNFDemo-jiyuan .LATEST / functions/union-fnf-demo inputMappings:-target: price source: $input.price-target: orderNum source: $input.orderNum-target: paymentMethod source: $input.paymentMethod-target: taskToken source: $input.taskToken default: goto: orderCanceled

The process is that after the user chooses the payment method, it sends it to the payment-fnf-demo function through a message, and then returns the payment method, so it flows to the paymentCombination node to determine the payment method and flows to the nodes and functions that specifically deal with the payment logic.

4. Zhifubao node

Look at a zhifubao node:

Choices:-condition: $.paymentMethod = = "zhifubao" steps:-type: task name: zhifubao resourceArn: acs:fc:cn-hangzhou:your_account_id:services/FNFDemo-jiyuan/functions/zhifubao-fnf-demo inputMappings:-target: price source: $input.price-target: orderNum Source: $input.orderNum-target: paymentMethod source: $input.paymentMethod-target: taskToken source: $input.taskToken

The resourceArn of the node is different from that of the previous two nodes. Here, the ARN of the function in the function calculation is configured, that is, the zhifubao-fnf-demo function will be triggered when the process flows to this node. This function is an event trigger function, but no triggers need to be created. The process passes the order amount, order number, and payment method to the zhifubao-fnf-demo function.

Zhifubao-fnf-demo function:

#-*-coding: utf-8-*-import loggingimport jsonimport requestsimport urllib.parsefrom aliyunsdkcore.client import AcsClientfrom aliyunsdkcore.acs_exception.exceptions import ServerExceptionfrom aliyunsdkfnf.request.v20190315 import ReportTaskSucceededRequestfrom aliyunsdkfnf.request.v20190315 import ReportTaskFailedRequestdef handler (event, context): region = "cn-xxx" account_id = "xxx" ak_id = "xxx" ak_secret = "xxx" fnf_client = AcsClient (ak_id, ak_secret Region) logger = logging.getLogger () logger.info (event) bodyJson = json.loads (event) price = bodyJson ["price"] taskToken = bodyJson ["taskToken"] orderNum = bodyJson ["orderNum"] paymentMethod = bodyJson ["paymentMethod"] logger.info ("price:" >

The code logic is simple: after receiving the amount, the amount is discounted by 20%, and then the price is updated back to the order. The nodes and functions of other payment methods are made in the same way, and the implementation logic can be changed. In this example, WeChat Pay gives a 50 per cent discount and UnionPay pays a 30 per cent discount.

The above is a workflow implemented by FC based on Serverless, which simulates and builds an order module. The rules include:

Configure metadata rules for merchants and payment methods

Confirm the metadata rules for the payment page.

In the actual project, the customizable part needs to be abstracted into metadata description, and there needs to be a configuration interface for operators or merchants to customize the payment method, that is, metadata rules, and then the front and rear pages display the corresponding content based on metadata information.

If you need to access a new payment method later, you only need to determine the routing rules in the paymentCombination routing node, and then add the corresponding payment method function. By adding metadata configuration items, you can display the new payment method on the page and route it to the new payment function.

After the whole article, I believe that many people already have a certain understanding of the definition of Serverless and how to achieve business capabilities based on the Serverless capabilities of existing public cloud systems, and even powerful companies can develop a set of Serverless platform. Of course, the idea is the same, in fact, many of the logic and theories in this paper are not only applicable to Serverless, but also our daily platform / platform solutions based on micro-services, from which we can obtain design nutrition and application in our work.

The above is how the Serverless shared by the editor reuses the configuration idea into the platform system. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are 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

Servers

Wechat

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

12
Report