AWS Lambda FunctionでJavaを採用したい

承前

  • AWS Lambda FunctionJava で作るというお仕事をしています
    • 基本的に Spring-Boot がメインの現場です
    • Spring-Framawaork はやめておけ、と公式でも言われてますね。1
  • Java で何かしらする時は、背骨(フレームワーク)欲しいですよね
    • DI(DependencyInjection) 無いと、もう無理ですよね
  • Guice/Dagger を使えと言われていますが、どっち使ったらいいの?
    • 色々なケースがありますが

自分でやったこと

で、どうやってビジネスロジック注入する?を考えて、やっぱりgoogle/guiceかなぁって。

設定注入は、Apache Geronimo Configかな 2

Daggerはコンパイル時DI、Guice実行時DI。コンパイル時にDI設定やればそっちの方が速いと思いがちですが、実際やってみると、Javaは起動するとかなり速いので、あまり差が無いのですね。 まぁ、そもそも AWS Lambda Function って、プロダクション的に小さいですし 3 そうすると、コードや設定少ないGuiceの方がいいですよね。

ケース

よくあるケースですが、 API Gateway で、何かを送ってもらって、何かをやるみたいなことをやってみましょうか。

public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

  private final AnyService anyService;

  @Override
  public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    this.anyService.execute(input);
    APIGatewayProxyResponseEvent res = ... // do something
    return res;
  }

  public App() {
    Injector injector = Guice.createInjector(new AppModule());
    this.anyService = injector.getInstance(AnyService.class);
  }
}
@Singleton
public class AnyService {

  public void execute(APIGatewayProxyRequestEvent input) {
    // do something
  }
}
public class AppModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(AnyService.class);

    // bind microprofile-config.properties
    final Map<String, String> props = new HashMap<>();
    Sets.newLinkedHashSet(ConfigProvider.getConfig().getConfigSources())
        .stream()
        .map(ConfigSource::getProperties)
        .forEach(props::putAll);
    Names.bindProperties(this.binder(), props);
  }
}

まぁー、こんな感じですかね?4


  1. AWS Lambda 関数を使用するためのベストプラクティス - AWS Lambda ↩︎

  2. JavaEE MicroProfile Config の実装参照なので、まぁ廃れることはないでしょう 第6回 お手軽便利MicroProfile Config | 豆蔵デベロッパーサイト ↩︎

  3. 小さく作るべきですよね ↩︎

  4. たまに、こういう(所謂)「黒魔術」成分少ない、手組みのものを作ると、本当に勉強になります ↩︎