【问题标题】:AWS Lambda + Spring, how to load application.ymlAWS Lambda + Spring,如何加载 application.yml
【发布时间】:2017-08-18 12:20:29
【问题描述】:

对于部署在 AWS lambda 上的 restful 应用程序,我在自定义 API 网关域时遇到问题。自定义域以这种方式工作,根据 basePath 选择不同的 API,最终触及 Lambda。例如:

api.mycustomdomain.com/view/ping -> 使用路径/view/ping 转到应用程序view api.mycustomdomain.com/admin/ping -> 使用路径 /admin/ping 转到应用程序 admin

我将此示例用作样板:https://github.com/awslabs/aws-serverless-java-container/tree/master/samples/spring/pet-store

我想要实现的是依赖于 Host 标头从请求路径中去除前缀​​的处理程序。

我准备了以下application.yml文件:

server:
  contextPath: "/view"
  productionHost: "api.mycustomdomain.com"

问题/问题是。我现在如何将它们加载到我的 Lambda 函数中?这是我天真的尝试:

public class LambdaHandler implements RequestHandler<AwsProxyRequest, AwsProxyResponse> {
    SpringLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
    boolean isinitialized = false;

    @Value("${server.contextPath}")
    private String prefix;

    @Value("${server.productionHost}")
    private String productionHost;

    public AwsProxyResponse handleRequest(AwsProxyRequest awsProxyRequest, Context context) {
        if(awsProxyRequest.getHeaders().get("Host").equals(productionHost))
            awsProxyRequest.setPath(awsProxyRequest.getPath().substring(prefix.length()));

        if (!isinitialized) {
            isinitialized = true;
            try {
                handler = SpringLambdaContainerHandler.getAwsProxyHandler(PingPongApp.class);
            } catch (ContainerInitializationException e) {
                e.printStackTrace();
                return null;
            }
        }
        return handler.proxy(awsProxyRequest, context);
    }
}

显然这不起作用,LambdaHandler 正在脱离 Spring 上下文。

任何想法我该如何处理?

【问题讨论】:

    标签: java spring amazon-web-services aws-lambda microservices


    【解决方案1】:

    您似乎无法加载这些属性。请遵循以下两个选项中的任何一个。

    1> 您可以在配置中添加以下 bean,这样您就可以自动装配字符串并使用您已经使用的方式

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
    }
    

    2>

    public AwsProxyResponse..{
    @Autowired
    private Environment env;
    ..
        public AwsProxyResponse handleRequest{
        ..
        String contextPath = env.getRequiredProperty(“server.contextPath”));
        ...
        }
    }
    

    【讨论】:

    • 我尝试了第一个选项。它没有用。我认为原因是,执行流程是: 1. api 获取请求 -> 传递给 lambda (LambdaHandler) -> 2. Lambda 处理程序正在调用 Spring,所以我无法访问 LambdaHandler 中的 @Value (spring 不是此时已初始化)。
    • 我不明白你在第二个提案中的意思。你想让我覆盖 AwsProxyResponse 吗?为什么?
    • 不,我只是说另一种检索属性的方法。声明环境变量(org.springframework.core.env.Environoment),因为这里加载属性有问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2019-07-17
    • 2019-06-20
    • 2020-11-05
    • 2016-12-07
    • 2019-11-23
    • 2016-03-30
    相关资源
    最近更新 更多