docs's People
docs's Issues
5分钟教程:使用Lambda和API网关在Java中开发RESTful微服务
摘要:遵循这个简单的教程,您应该能够开始使用Java在AWS上开发无服务器的微服务。
原标题:Developing RESTful APIs in Java using Amazon API Gateway and AWS Lambda
作者:Muhammad Ali
原文链接:https://www.bluestackcloud.com/insights/2018/6/14/developing-restful-apis-in-java-using-amazon-api-gateway-and-aws-lambda
导言
AWS Lambda和Amazon API-Gateway可用于在Java中创建RESTful Web服务,而无需进行复杂的Java框架配置或设置和维护Web服务器(如Tomcat、WebSphere等)。Lambda和APIGateway的结合使得开发API变得非常容易,并且还可以轻松地管理API的暂存环境,比如开发、测试和Prod。
AWS Lambda是一个高度可伸缩和高度可用的无服务器计算平台,您可以使用它运行Java代码来提供服务的主要功能。有关Lambda的更多信息,请访问链接(https://aws.amazon.com/documentation/lambda/).
AmazonAPI网关是由AWS提供的一种网络服务,允许开发人员轻松地构建和部署API端点。它使开发人员非常容易地创建HTTPS端点并将其与Lambda函数集成。数据从API端点传递到Lambda函数,并由API网关处理。欲了解更多关于API网关的内容,请访问链接(https://aws.amazon.com/documentation/apigateway/).
本文提供了关于如何使用Lambda和API网关在Java中开发RESTful微服务的循序渐进的指南。
先决条件
首先,您需要准备一台开发机器,为此您需要Java 8、Eclipse IDE和AWS Toolkit for Eclipse。有关如何完成此操作的详细信息,请参阅这里(https://www.bluestackcloud.com/insights/2018/5/7/getting-started-with-aws-development-using-java).
步骤1:创建Lambda函数
1、一旦您准备好使用Eclipse IDE,AWS图标将出现在主工具栏中。点击它并选择“新AWS Lambda项目.”
2、提供适当的项目名称和Maven配置。选择“Stream Request Handler”作为输入类型。
3、在点击“Finish”之后,示例代码将被加载到您新创建的项目中。打开主处理程序函数并更新以下代码。
package com.amazonaws.lambda.demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.Writer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
public class LambdaFunctionHandler implements RequestStreamHandler
{
JSONParser parser = new JSONParser();
@OverRide
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException
{
LambdaLogger logger = context.getLogger();
logger.log("Loading Java Lambda handler of ProxyWithStream");
String proxy = null;
String param1 = null;
String param2 = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject responseJson = new JSONObject();
String responseCode = "200";
JSONObject event = null;
try {
event = (JSONObject)parser.parse(reader);
if (event.get("pathParameters") != null) {
JSONObject pps = (JSONObject)event.get("pathParameters");
if ( pps.get("proxy") != null) {
proxy = (String)pps.get("proxy");
}
}
if (event.get("queryStringParameters") != null)
{
JSONObject qps = (JSONObject)event.get("queryStringParameters");
if ( qps.get("param1") != null)
{
param1 = (String)qps.get("param1");
}
}
if (event.get("queryStringParameters") != null)
{
JSONObject qps = (JSONObject)event.get("queryStringParameters");
if ( qps.get("param2") != null)
{
param2 = (String)qps.get("param2");
}
}
}
catch(Exception pex)
{
responseJson.put("statusCode", "400");
responseJson.put("exception", pex);
}
// Implement your logic here
int output = 0;
if (proxy.equals("sum"))
{
output = sum(Integer.parseInt(param1), Integer.parseInt(param2));
}
else if (proxy.equals("subtract"))
{
output = subtract(Integer.parseInt(param1), Integer.parseInt(param2));
}
JSONObject responseBody = new JSONObject();
responseBody.put("input", event.toJSONString());
responseBody.put("message", "Output is" + output);
JSONObject headerJson = new JSONObject();
headerJson.put("x-custom-header", "my custom header value");
headerJson.put("Access-Control-Allow-Origin", "*");
responseJson.put("isBase64Encoded", false);
responseJson.put("statusCode", responseCode);
responseJson.put("headers", headerJson);
responseJson.put("body", responseBody.toString());
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(responseJson.toJSONString());
writer.close();
}
public int sum(int a, int b)
{
return a+b;
}
public int subtract(int a, int b)
{
return a-b;
}
}
4、构建并部署此Lambda函数。有关部署Java Lambda函数的完整信息可以找到这里(https://docs.aws.amazon.com/lambda/latest/dg/java-create-jar-pkg-maven-and-eclipse.html).
在这个例子中,我们用“REST_API_HelloWorld”的名称在AWS控制台中创建了Lambda函数。
步骤2:创建API网关端点
1、转到AWS控制台并启动API-网关服务。asdfadfasdfadfdsf
2、点击“创建API”。
3、选择“新API”并提供“API名称”
4、在创建API之后,添加一个资源,如下所示:
5、确保勾选“配置为代理资源”选项。
在下一个显示“Any”方法设置的屏幕上,选择“Lambda Function”作为集成类型。同时选中“Use Lambda Proxy integration”。选择部署Lambda函数的区域,并输入Lambda名称。
6、现在,我们将把这个API部署到一个暂存环境中。为此,单击“Action”并选择“DeployAPI”。
7、选择[NewStage]并提供一个staging名称和描述。在本教程中,我们使用“Dev”作为名称。一旦部署完成,控制台将带您到staging页。
8、复制“Invoke URL”,并在其上添加代理资源名称和参数,其中包含要发送给Lambda的值。有关本教程,请参阅下面的示例:
• 格式:https://5yv20hbz44.execute-api.eu-west-1.amazonaws.com/Dev/{proxy}?{set_of_params_separated_by_&}
• 示例:https://5yv20hbz44.execute-api.eu-west-1.amazonaws.com/Dev/sum?param1=100¶m2=100
输出如下:
结语
像AWS Lambda这样的无服务器计算平台最近非常流行。许多组织要求他们的DevOps工程师能够开发无服务器应用程序,因为它减少了设置硬件/软件基础结构所需的时间,从而减少了项目交付时间。遵循这个简单的教程,您应该能够开始使用Java在AWS上开发无服务器的微服务。
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.