本文介绍如何使用 Java HTTP 触发器来快速迁移 Spring 应用,并使用函数计算提供的 fun 工具 做到真正一键部署。
您可以直接下载 Spring 集成到函数计算示例代码 测试运行
迁移 Sping 到函数计算只需以下四步:
添加 FC 入口函数 配置打包方式 部署服务和函数 测试运行
FcHandler.java
public class FcHandler implements FunctionInitializer, HttpRequestHandler { private AppLoader fcAppLoader = new FcAppLoader(); /* * Request url web path * 1. Without custom domain: /2016-08-15/proxy/${YourServiceName}/${YourFunctionName} * 2. With custom domain: your mapping settings path */ private String userContextPath = System.getenv("USER_CONTEXT_PATH"); // Webapp home directory after inited private String appBaseDir = System.getenv("APP_BASE_DIR"); @Override public void initialize(Context context) throws IOException { FunctionComputeLogger fcLogger = context.getLogger(); // Config FcAppLoader fcAppLoader.setFCContext(context); if (appBaseDir != null) fcAppLoader.setBaseDir(appBaseDir); // Load code from /code fcLogger.info("Begin load code"); fcAppLoader.loadCodeFromLocalProject(""); fcLogger.info("End load code"); // Init webapp from code long timeBegin = System.currentTimeMillis(); fcLogger.info("Begin load webapp"); boolean initSuccess = fcAppLoader.initApp(userContextPath, FcHandler.class.getClassLoader()); if(! initSuccess) { throw new IOException("Init web app failed"); } fcLogger.info("End load webapp, elapsed: " + (System.currentTimeMillis() - timeBegin) + "ms"); } @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) throws IOException, ServletException { try { fcAppLoader.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } }
ROSTemplateFormatVersion: '2015-09-01' Transform: 'Aliyun::Serverless-2018-04-03' Resources: # Create Service demo-fc-service demo-fc-service: Type: 'Aliyun::Serverless::Service' Properties: Description: 'Hello FC' Policies: - AliyunOSSFullAccess - AliyunLogFullAccess InternetAccess: true # Create function demo-spring demo-spring: Type: 'Aliyun::Serverless::Function' Properties: Initializer: com.aliyun.fc.example.FcHandler::initialize Handler: com.aliyun.fc.example.FcHandler::handleRequest Runtime: java8 CodeUri: './target/demo-spring-hello-1.0.war' MemorySize: 256 Timeout: 60 InitializationTimeout: 60 EnvironmentVariables: 'USER_CONTEXT_PATH': '/2016-08-15/proxy/demo-fc-service/demo-spring' 'APP_BASE_DIR': '/tmp' # Create http trigger Events: http: # trigger name Type: HTTP # http trigger Properties: AuthType: ANONYMOUS Methods: ['GET', 'POST'] 执行
mvn clean package fun deploy 即可部署成功
curl https://{account_id}.{region}.fc.aliyuncs.com/2016-08-15/proxy/demo-fc-service/demo-spring/ 成功返回 Spring 页面spring
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。