Amazon API Gateway & Lambda 微服务最简单例子

来源:互联网 发布:java设置环境变量win8 编辑:程序博客网 时间:2024/05/21 23:59

Amazon API Gateway介绍:

Amazon API Gateway 是一种完全托管的服务,可以帮助开发者轻松创建、发布、维护、监控和保护任意规模的 API。只需在 AWS 管理控制台中点击几下,您便可以创建可充当应用程序“前门”的 API,从后端服务访问数据、业务逻辑或功能,例如基于 Amazon Elastic Compute Cloud (Amazon EC2) 运行的工作负载、基于 AWS Lambda 运行的代码或任意 Web 应用。Amazon API Gateway 负责管理所有任务,涉及接受和处理成千上万个并发 API 调用,包括流量管理、授权和访问控制、监控以及 API 版本管理。Amazon API Gateway 没有最低费用或启动成本,您只需为收到的 API 调用和传输出去的数据量付费。
https://aws.amazon.com/cn/api-gateway/
Lambda介绍:
AWS Lambda 是一项计算服务,可使您无需预配置或管理服务器即可运行代码。
http://blog.csdn.net/afxcontrolbars/article/details/51912795

微服务介绍

微服务(也称为微服务体系结构)是将应用程序构建为松散耦合服务的集合的架构风格,其实现业务功能。 微服务架构使得能够连续传送/部署大型复杂应用程序。 它还使组织能够发展其技术栈。
微服务架构将大型,复杂系统打碎为独立,小的个体,非常简单的管理和扩展服务。这使得开发人员实现可扩展,高可用,易维护的应用程序。

RESTFul API 介绍

(1)每一个URI代表一种资源;
(2)客户端和服务器之间,传递这种资源的某种表现层;
(3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”

实验步骤:
创建Lambda函数
点击Services -> 选择Lambda -> 点击Get Started Now -> 选择Blank Function
在Configure triggers页面点击空方格,选择API Gateway
这里写图片描述
Security下拉框悬着Open,允许公开访问,忽略警告,点击next,给你的Lambda起一个函数名, 选择node.js,然后选择eidt code inline,复一下代码到框里

console.log('Loading event...');var json = {  "service": "lambda",  "reference": "https://aws.amazon.com/lambda/faqs/",  "questions": [{    "q": "What is AWS Lambda?",    "a": "AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. "  },{   "q":"What events can trigger an AWS Lambda function?",   "a":"You can use AWS Lambda to respond to table updates in Amazon DynamoDB, modifications to objects in Amazon S3 buckets, "  },{   "q":"When should I use AWS Lambda versus Amazon EC2?",   "a":"Amazon Web Services offers a set of compute services to meet a range of needs. Amazon EC2 offers flexibility, with a wide range of instance types and the option to customize the operating system, "  },{    "q":"What kind of code can run on AWS Lambda?",    "a":"AWS Lambda offers an easy way to accomplish many activities in the cloud. For example, "  }  ]}exports.handler = function(event, context) {    var rand = Math.floor(Math.random() * json.questions.length);    console.log("Quote selected: ", rand);    var response = {        body: JSON.stringify(json.questions[rand])    };    console.log(response);    context.succeed(response);};

选择role 一个具有执行lambda 权限的角色,其他选择默认配置,点击next,点击创建函数。
这里写图片描述
点击下拉按钮,选择 Configure test event,选择默认的hello world, 删除字典里的内容,只留下一个空字典,点击测试你将看到上图的输出。

通过URL访问检验。
你在函数描述看到以下URL
https://gligmdoy44.execute-api.us-west-2.amazonaws.com/prod/lambda1test 点击访问这个URL,你讲看到以下输出

{"q":"what is AWS Lambda?","a":"AWS Lambda lets you run code without provisioning or managing servers."}

结论:

通过这个案例大家应该已经对于微服务的有一些了解和认识,我们可以基于以上例子得出一些简单的结论
1. 使用lambda 执行函数的时候非常快,完全能匹敌传统的service所提供的实时反馈。
2. 借助于APIGateway 你可以快速创建标准的API,并且可以直接调用Lambda 进行数据处理,及时是web应用也足以支撑,
3. 你无语管理人和服务器,只需提供数据源,和执行函数,更加符合 程序及数据加算法的理念。

原创粉丝点击