はじめに
SpringプロジェクトにはServerless用のフレームワークとしてSpring Cloud Functionというものがあります。
Webアプリで使い慣れたSpring Bootと同じ考えをAWS LambdaやAzure Functionsなどに適用できることから、魅力的に映る人もいるかなと思います。ここから数回はSpring Cloud Functionを使ってAWS Lambda上で関数を動かすことをやってみます。
プロジェクトの作成
まずはgradle init
でGradleプロジェクトを作り、以下のようなbuild.gradle
を作ります。
plugins { id 'java' // dependencyManagement用 id 'io.spring.dependency-management' version '1.1.5' // bootRunのため。 id 'org.springframework.boot' version '3.2.4' } group = 'com.github.miyohide' version = '1.0' repositories { mavenCentral() } ext { set('springCloudVersion', "2023.0.1") } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-function-web' implementation 'org.springframework.cloud:spring-cloud-function-adapter-aws' testImplementation platform('org.junit:junit-bom:5.10.0') testImplementation 'org.junit.jupiter:junit-jupiter' } test { useJUnitPlatform() }
依存関係をまとめるSpring Cloudのバージョンを変数springCloudVersion
で設定して、dependencyManagement
で設定。dependencies
にて指定するものとしてorg.springframework.cloud:spring-cloud-starter-function-web
とorg.springframework.cloud:spring-cloud-function-adapter-aws
を指定しておきます。
アプリの実装
アプリは以下のような感じで実装します。
package com.github.miyohide; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.util.function.Function; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } @Bean public Function<String, String> reverseString() { return value -> new StringBuilder(value).reverse().toString(); } }
これだけで./gradlew bootRun
でアプリを起動し、別のシェルでcurl localhost:8080/reverseString -H "Content-Type: text/plain" -d "abc"
を実行するとcba
が返ります。メソッド名をURLに付与し、-d "abc"
で与えた文字列が逆転した結果cba
が返ります。
ちょっと発展
別のクラスに処理を実装してみます。
package com.github.miyohide.functions; import java.util.function.Function; public class Greeter implements Function<String, String> { @Override public String apply(String s) { return "Hello " + s; } }
@Component
を付与しなくても、application.properties
に以下の記述を追加することでapply
メソッドが関数として登録されます。
spring.cloud.function.scan.packages=com.github.miyohide.functions
公式ドキュメントとしては以下のものです。
実際試してみます。別のシェルでcurl localhost:8080/greeting -H "Content-Type: text/plain" -d "abc"
にアクセスすると、Hello abc
が返ります。
考察
とりあえずSpring Cloud Functionを使ってアプリを作ってみました。Springに関する前提知識が多分に求められていますが、すでにSpringに慣れ親しんでいる場合はSpring Cloud Functionを使ってみるのも良いかなと思います。
ちょっと調べた感じ、最小限必要な記述を解説したものはなかったので、build.gradle
などの設定ファイルをつくるのはちょっと苦労しました。何が必要で何が不要なのかがちょっと分かりにくいです。