This commit is contained in:
Yanyutin753
2024-02-14 11:38:29 +08:00
parent 41efd39080
commit f918d929a0
22 changed files with 1393 additions and 2 deletions

2
.gitattributes vendored
View File

@@ -1,2 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

20
.idea/compiler.xml generated Normal file
View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="benchmark-jibber" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel target="17" />
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="benchmark-jibber" options="-parameters" />
</option>
</component>
</project>

6
.idea/encodings.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
</component>
</project>

20
.idea/jarRepositories.xml generated Normal file
View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

6
.idea/kotlinc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Kotlin2JvmCompilerArguments">
<option name="jvmTarget" value="11" />
</component>
</project>

15
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CodeInsightWorkspaceSettings">
<option name="optimizeImportsOnTheFly" value="true" />
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="corretto-17" project-jdk-type="JavaSDK" />
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

18
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@@ -0,0 +1,18 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar

20
Dockerfiles/Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
# Using Oracle GraalVM for JDK 17
FROM container-registry.oracle.com/graalvm/native-image:21-ol8 AS builder
# Set the working directory to /home/app
WORKDIR /build
# Copy the source code into the image for building
COPY . /build
# Build
RUN ./mvnw --no-transfer-progress native:compile -Pnative
# The deployment Image
FROM container-registry.oracle.com/os/oraclelinux:8-slim
EXPOSE 8080
# Copy the native executable into the containers
COPY --from=builder /build/target/benchmark-jibber app
ENTRYPOINT ["/app"]

View File

@@ -0,0 +1,13 @@
# Using Oracle GraalVM for JDK 17
FROM container-registry.oracle.com/graalvm/jdk:21-ol8
# JAR file will be specified by passing in a build time argument to docker build
ARG APP_FILE
EXPOSE 8080
# opy the JAR file into the root and rename
COPY ./target/${APP_FILE} app.jar
# Run java with the jar file when the container starts up
CMD ["java","-jar","app.jar"]

View File

@@ -0,0 +1,7 @@
FROM container-registry.oracle.com/os/oraclelinux:8-slim
ARG APP_FILE
EXPOSE 8080
COPY target/${APP_FILE} app
ENTRYPOINT ["/app"]

158
README-Cloud-Shell.md Normal file
View File

@@ -0,0 +1,158 @@
# Spring Boot Microservice with Oracle GraalVM in OCI Cloud Shell
This part shows how you can get started quickly with Oracle GraalVM in Oracle Cloud Infrastructure (OCI) Cloud Shell using the Spring Boot 3 microservice example.
Oracle GraalVM is available for use on Oracle Cloud Infrastructure (OCI) at no additional cost.
## What is Cloud Shell?
[Cloud Shell](https://www.oracle.com/devops/cloud-shell/) is a free-to-use browser-based terminal accessible from the Oracle Cloud Console. It provides access to a Linux shell with preinstalled developer tools and a pre-authenticated OCI CLI. You can use the shell to interact with OCI resources, follow labs and tutorials, and quickly run utility commands.
Oracle GraalVM for JDK 17 (with Native Image) is preinstalled in Cloud Shell, so you dont have to install and configure a development machine to get started.
## Step 1: Launch Cloud Shell
[Login to OCI Console and launch Cloud Shell](https://cloud.oracle.com/?bdcstate=maximized&cloudshell=true).
## Step 2: Select GraalVM as the Current JDK
1. List the installed JDKs:
```shell
csruntimectl java list
```
The output should be similar to (versions may vary):
```shell
graalvmjdk-17 /usr/lib64/graalvm/graalvm-java17
* oraclejdk-11 /usr/java/jdk-11.0.17
oraclejdk-1.8 /usr/lib/jvm/jdk-1.8-oracle-x64
```
2. Select GraalVM as the current JDK:
```shell
csruntimectl java set graalvmjdk-17
```
The output should be similar to:
```shell
The current managed java version is set to graalvmjdk-17.
```
## Step 3: (Optional) Confirm Software Version and Environment Variables
This step is optional - [Check software version and environment variables](../_common/README-check-version-env-vars.md)
## Step 4: Set up Your Project, Build and Run a JAR
1. Git clone this example.
```shell
git init graalvmee-spring-native-image
cd graalvmee-spring-native-image
git remote add origin https://github.com/graalvm/graalvm-demos.git
git config core.sparsecheckout true
echo "spring-native-image/*">>.git/info/sparse-checkout
git pull --depth=1 origin master
cd spring-native-image
```
2. Build a JAR file for the example app.
```shell
mvn clean package
```
3. Run the app JAR in the background.
```shell
java -jar ./target/benchmark-jibber-0.0.1-SNAPSHOT.jar &
```
4. Test the app JAR.
```shell
curl http://localhost:8080/jibber
```
It should generate a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol. The output should be similar to:
```shell
...
And, as in uffish thought he stood, The Jabberwock, my beamish boy!<br/>
Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
He left it dead, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
Beware the Jabberwock, my beamish boy!<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Twas brillig, and with its head He went galumphing back.<br/>
And, as in uffish thought he stood, The Jabberwock, my son!<br/>
Come to my arms, my son!<br/>
Twas brillig, and shun The frumious Bandersnatch!<br/>
```
5. Bring the running app JAR in the foreground
```shell
fg
```
6. Once the app is running in the foreground, press CTRL+C to stop it.
## Step 5: Build and Run a Native Executable
Now build a native executable for your Spring Boot microservice using Oracle GraalVM Native Image.
1. Build the app native executable
```shell
mvn -Pnative native:compile
```
This will create a binary executable `target/benchmark-jibber`.
2. Run the app native executable in the background
```shell
./target/benchmark-jibber &
```
3. Test the app native executable
```shell
curl http://localhost:8080/jibber
```
It should generate a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol. The output should be similar to:
```shell
...
The Jabberwock, my beamish boy!<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
Beware the Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And the mome raths outgrabe.<br/>
He left it dead, and shun The frumious Bandersnatch!<br/>
He left it dead, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
Twas brillig, and with its head He went galumphing back.<br/>
Come to my arms, my son!<br/>
Beware the Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came!<br/>
```
4. Bring the running app native executable in the foreground
```shell
fg
```
5. Once the app is running in the foreground, press CTRL+C to stop it.

158
README-Code-Editor.md Normal file
View File

@@ -0,0 +1,158 @@
# Spring Boot Microservice with Oracle GraalVM in OCI Code Editor
This part shows how you can get started quickly with Oracle GraalVM in Oracle Cloud Infrastructure (OCI) Code Editor using the Spring Boot 3 microservice example.
Oracle GraalVM is available for use on Oracle Cloud Infrastructure (OCI) at no additional cost.
## What is Code Editor?
[Code Editor](https://www.oracle.com/devops/code-editor/) enables you to edit and deploy code directly from the Oracle Cloud Console. You can develop applications, service workflows, and scripts entirely from a browser. This makes it easy to rapidly prototype cloud solutions, try new services, and accomplish quick coding tasks.
Oracle GraalVM for JDK 17 (with Native Image) is preinstalled in Cloud Shell, so you dont have to install and configure a development machine to get started. Code Editor's integration with Cloud Shell gives you direct access to Oracle GraalVM JDK and Native Image.
## Step 1: Open Terminal in Code Editor
1. [Login to OCI Console and launch Code Editor](https://cloud.oracle.com/?bdcstate=maximized&codeeditor=true).
2. Open a `New Terminal` in Code Editor. Use this Terminal window to run the commands shown in this sample.
![](./images/oci-ce-terminal.png)
## Step 2: Select GraalVM as the Current JDK
1. List the installed JDKs:
```shell
csruntimectl java list
```
The output should be similar to (versions may vary):
```shell
graalvmjdk-17 /usr/lib64/graalvm/graalvm-java17
* oraclejdk-11 /usr/java/jdk-11.0.17
oraclejdk-1.8 /usr/lib/jvm/jdk-1.8-oracle-x64
```
2. Select GraalVM as the current JDK:
```shell
csruntimectl java set graalvmjdk-17
```
The output should be similar to:
```shell
The current managed java version is set to graalvmjdk-17.
```
## Step 3: [OPTIONAL] Confirm Software Version and Environment Variables
This step is optional - [Check software version and environment variables](../_common/README-check-version-env-vars.md)
## Step 4: Set up Your Project, Build and Run as a JAR
1. Git clone this example.
```shell
git init graalvmee-spring-native-image
cd graalvmee-spring-native-image
git remote add origin https://github.com/graalvm/graalvm-demos.git
git config core.sparsecheckout true
echo "spring-native-image/*">>.git/info/sparse-checkout
git pull --depth=1 origin master
cd spring-native-image
```
2. Build a JAR file for the example app.
```shell
mvn clean package
```
3. Run the app JAR in the background.
```shell
java -jar ./target/benchmark-jibber-0.0.1-SNAPSHOT.jar &
```
4. Test the app JAR.
```shell
curl http://localhost:8080/jibber
```
It should generate a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol. The output should be similar to:
```shell
...
And, as in uffish thought he stood, The Jabberwock, my beamish boy!<br/>
Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
He left it dead, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
Beware the Jabberwock, my beamish boy!<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Twas brillig, and with its head He went galumphing back.<br/>
And, as in uffish thought he stood, The Jabberwock, my son!<br/>
Come to my arms, my son!<br/>
Twas brillig, and shun The frumious Bandersnatch!<br/>
```
5. Bring the running app JAR in the foreground
```shell
fg
```
6. Once the app is running in the foreground, press CTRL+C to stop it.
## Step 5: Build and Run a Native Executable
Now build a native executable for your Spring Boot microservice using GraalVM Native Image.
1. Build the app native executable
```shell
mvn -Pnative native:compile
```
This will create a binary executable `target/benchmark-jibber`.
2. Run the app native executable in the background
```shell
./target/benchmark-jibber &
```
3. Test the app native executable
```shell
curl http://localhost:8080/jibber
```
It should generate a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol. The output should be similar to:
```shell
...
The Jabberwock, my beamish boy!<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Beware the Jubjub bird, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
Beware the Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And the mome raths outgrabe.<br/>
He left it dead, and shun The frumious Bandersnatch!<br/>
He left it dead, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.<br/>
Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And burbled as it came!<br/>
Twas brillig, and with its head He went galumphing back.<br/>
Come to my arms, my son!<br/>
Beware the Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came!<br/>
```
4. Bring the running app native executable in the foreground
```shell
fg
```
5. Once the app is running in the foreground, press CTRL+C to stop it.

306
README.md Normal file
View File

@@ -0,0 +1,306 @@
# Spring Boot Native Image Microservice
This demo shows how to build, package, and run a simple Spring Boot 3 microservice from a JAR file with the GraalVM JDK, and from a native executable with GraalVM Native Image. The benefits of using a native executable are faster start-up times and reduced memory consumption. It also demonstrates how to run the application and build the native executable within a Docker container.
There are two ways to generate a native executable from a Spring Boot application:
- [Using GraalVM Native Build Tools](https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.developing-your-first-application.native-build-tools)
- [Using Buildpacks](https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.developing-your-first-application.buildpacks)
## Sample Application
The example is a minimal REST-based API application, built on top of Spring Boot 3. It consists of:
- `com.example.jibber.JibberApplication`: the main Spring Boot class. It is also a REST controller which serves as an entry-point for HTTP requests.
- `com.example.jibber.Jabberwocky`: a utility class that implements the logic of the application.
If you call the HTTP endpoint, `/jibber`, it will return some nonsense verse generated in the style of the Jabberwocky poem, by Lewis Carroll. The program achieves this by using a Markov Chain to model the original poem (this is essentially a statistical model). This model generates a new text. The example application provides the text of the poem, then generates a model of the text, which the application then uses to generate a new text that is similar to the original text. The application uses the [RiTa library](https://rednoise.org/rita/) as an external dependency to build and use Markov Chains.
By default, the demo uses the [Native Build Tools Maven plugin](https://graalvm.github.io/native-build-tools/latest/maven-plugin.html) to perform the tasks. If you would like to run this demo using [BuildPacks](https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.developing-your-first-application.buildpacks), the build configuration is provided for you too.
## Prerequisites
1. Download and install the latest GraalVM JDK using [SDKMAN!](https://sdkman.io/).
```bash
sdk install java 21.0.2-graal
```
2. (Optional) Install and run a Docker-API compatible container runtime such as [Rancher Desktop](https://docs.rancherdesktop.io/getting-started/installation/), [Docker](https://www.docker.io/gettingstarted/), or [Podman](https://podman.io/docs/installation). If you are using Docker, configure it to [allow non-root user access](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user) if you are on Linux.
3. Download the demos repository or clone it as follows:
```bash
git clone https://github.com/graalvm/graalvm-demos
```
4. Change directory to the demo subdirectory:
```bash
cd spring-native-image
```
## Application JAR
### Build and Run as a JAR
This demo is built using Maven.
1. Build the application on top of a JVM:
```shell
./mvnw clean package
```
It generates a runnable JAR file that contains all of the applications dependencies and also a correctly configured `MANIFEST` file.
2. Run the application JAR and put it into the background by appending `&`:
```shell
java -jar ./target/benchmark-jibber-0.0.1-SNAPSHOT.jar &
```
3. Open the application [http://localhost:8080/jibber](http://localhost:8080/jibber) in a browser, or call the endpoint using `curl`:
```shell
curl http://localhost:8080/jibber
```
It should generate a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol.
4. Bring the application to the foreground using `fg`, and then enter `<CTRL-c>` to terminate the application.
### (Optional) Containerize the JAR
The following steps (5-8) show how you can easily containerize the JAR built in the previous step using the Oracle GraalVM JDK container image `container-registry.oracle.com/graalvm/jdk:17-ol8`.
5. Run this command to package the JAR as a Docker container:
```shell
docker build -f Dockerfiles/Dockerfile.jvm --build-arg APP_FILE=benchmark-jibber-0.0.1-SNAPSHOT.jar -t jibber-benchmark:jvm.0.0.1-SNAPSHOT .
```
6. Run the container:
```shell
docker run --rm --name graal -p 8080:8080 jibber-benchmark:jvm.0.0.1-SNAPSHOT
```
7. Open the application [http://localhost:8080/jibber](http://localhost:8080/jibber) in a browser, or from a new terminal window, call the endpoint using `curl`:
```shell
curl http://localhost:8080/jibber
```
You should get a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol.
8. To stop the application, first get the container id using `docker ps`, and then run:
```shell
docker rm -f <container_id>
```
## Native Executable
Recap what you have so far: built a Spring Boot application with an HTTP endpoint, and successfully containerised it.
Now you will look at how you can create a native executable from your application.
Spring Boot 3's built-in support for GraalVM Native Image makes it easy to compile a Spring Boot 3 application into a native executable.
This native executable not only starts faster but also uses far fewer resources than running the application as a JAR file.
You can use the `native-image` tool from the GraalVM installation to build a native executable.
In this example, you'll use the [GraalVM Native Build Tools for Maven](https://graalvm.github.io/native-build-tools/latest/maven-plugin.html) to build a native executable.
### Default Native Build Configuration
Make sure youre using `spring-boot-starter-parent` in order to inherit the out-of-the-box `native` profile, and the `org.graalvm.buildtools:native-maven-plugin` plugin.
You should see the following in the Maven `pom.xml` file:
``` xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
```
``` xml
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
...
</plugins>
</build>
```
The out-of-the-box `native` profile has [GraalVM Reachability Metadata](https://www.graalvm.org/native-image/libraries-and-frameworks/) enabled by default.
### Build and Run as a Native Executable
With the out-of-the-box `native` profile active, you can invoke the `native:compile` goal to trigger native-image compilation.
1. Run the following command:
```shell
./mvnw native:compile -Pnative
```
The `native` profile is used to generate a native executable for your platform. The native executable is called _benchmark-jibber_ and is generated in the _target_ directory.
>Alternatively, to build using BuildPacks, run the `./mvnw spring-boot:build-image -Pnative` command to generate a native executable. For more information about using BuildPacks to create a native executable, see [Building a Native Image Using Buildpacks](https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.developing-your-first-application.buildpacks).
2. Run the native executable and put it into the background by appending `&`:
```shell
./target/benchmark-jibber &
```
3. Open the application [http://localhost:8080/jibber](http://localhost:8080/jibber) in a browser, or call the endpoint using `curl`:
```shell
curl http://localhost:8080/jibber
```
You should get a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol.
4. Bring the application to the foreground using `fg`, and then enter `<CTRL-c>` to terminate the application.
From the log output, notice how much quicker the native executable version of this Spring Boot application starts compared to the JAR. The native executable also uses fewer resources than running from a JAR file.
### Additional Native Build Configuration
Notice that you can pass additional configuration arguments to the underlying `native-image` build tool using the `<buildArgs>` section. In individual `buildArg` tags, you can pass parameters exactly the same way as you do from a command line. This lets you use all of the parameters that work with the `native-image` tool from Maven.
Add the following snippet to the pom.xml to pass additional arguments to enable verbose output, quick build mode, etc. over and above the out-of-the-box `native` profile.
```xml
<profiles>
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<!--<version>0.9.28</version>-->
<configuration>
<verbose>true</verbose>
<quickBuild>true</quickBuild>
<buildArgs combine.children="append">
<arg>-H:+ReportExceptionStackTraces</arg>
</buildArgs>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
```
### Build and Run as a Native Executable
Let's rebuild the native executable with the additional configuration arguments.
1. Run the following command:
```shell
./mvnw native:compile -Pnative
```
With the quick build mode enabled, it takes less time to build the native executable. This mode should be used in development for faster builds.
2. Run the native executable and put it into the background by appending `&`:
```shell
./target/benchmark-jibber &
```
3. Open the application [http://localhost:8080/jibber](http://localhost:8080/jibber) in a browser, or call the endpoint using `curl`:
```shell
curl http://localhost:8080/jibber
```
You should get a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol.
4. Bring the application to the foreground using `fg`, and then enter `<CTRL-c>` to terminate the application.
From the log output, notice how much quicker the native executable version of this Spring Boot application starts compared to the JAR. The native executable also uses fewer resources than running from a JAR file.
### (Optional) Containerize the Native Executable on Linux
The following steps (5-8) are for Linux only.
5. On Linux, you can easily containerise the native executable using the following command:
```shell
docker build -f Dockerfiles/Dockerfile.native --build-arg APP_FILE=benchmark-jibber -t jibber-benchmark:native.0.0.1-SNAPSHOT .
```
6. Run the application:
```shell
docker run --rm --name native -p 8080:8080 jibber-benchmark:native.0.0.1-SNAPSHOT
```
7. Open the application [http://localhost:8080/jibber](http://localhost:8080/jibber) in a browser, or from a new terminal window, call the endpoint using `curl`:
```shell
curl http://localhost:8080/jibber
```
It should generate a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol.
8. To stop the application, first get the container id using `docker ps`, and then run:
```shell
docker rm -f <container_id>
```
### (Optional) Use Multistage Docker Builds to Build a Native Image and Package it in a Lightweight Container
The following steps (9-12) are for all platforms - MacOS, Windows, and Linux.
For MacOS and Windows, to build a Docker image containing your native executable, you need to build the native executable inside a Docker container. To do this, we've provided a [multistage Docker build file](./Dockerfiles/Dockerfile).
9. Run this command to build the native executable within a Docker container:
```shell
docker build -f Dockerfiles/Dockerfile -t jibber-benchmark:native.0.0.1-SNAPSHOT .
```
10. Run the application:
```shell
docker run --rm --name native -p 8080:8080 jibber-benchmark:native.0.0.1-SNAPSHOT
```
11. Open the application [http://localhost:8080/jibber](http://localhost:8080/jibber) in a browser, or from a new terminal window, call the endpoint using `curl`:
```shell
curl http://localhost:8080/jibber
```
It should generate a random nonsense verse in the style of the poem Jabberwocky by Lewis Carrol.
12. To stop the application, first get the container id using `docker ps`, and then run:
```shell
docker rm -f <container_id>
```
## Measure the Performance of the Application and Metrics
The Spring Actuator dependency has been added to the project, along with support for Prometheus. If you want to test the performance of either the JVM version, or the native executable version of the application, you can make use of the Prometheus support. If you are hosting the application locally, it is available on port 8080:
[http://localhost:8080/actuator/prometheus](http://localhost:8080/actuator/prometheus)
## Related Documentation
- Run an interactive lab: [Level Up your Spring Boot Java Application with GraalVM](https://luna.oracle.com/lab/268ea851-2f09-43e6-8d70-40a10cb4de03)
- [Maven Build Plugin for GraalVM Native Image](https://graalvm.github.io/native-build-tools/latest/maven-plugin.html/)
- [Spring Boot GraalVM Native Image Support](https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html)

287
mvnw vendored Normal file
View File

@@ -0,0 +1,287 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.1.1
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="`/usr/libexec/java_home`"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`\\unset -f command; \\command -v java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
printf '%s' "$(cd "$basedir"; pwd)"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=$(find_maven_basedir "$(dirname $0)")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) wrapperUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $wrapperUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
QUIET="--quiet"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
QUIET=""
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath"
fi
[ $? -eq 0 ] || rm -f "$wrapperJarPath"
elif command -v curl > /dev/null; then
QUIET="--silent"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
QUIET=""
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L
fi
[ $? -eq 0 ] || rm -f "$wrapperJarPath"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaSource="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=`cygpath --path --windows "$javaSource"`
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

187
mvnw.bat Normal file
View File

@@ -0,0 +1,187 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.1.1
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%

57
pom.xml Normal file
View File

@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>benchmark-jibber</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>benchmark-jibber</name>
<description>Demo project for Spring Boot with GraalVM Native Image</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.rednoise</groupId>
<artifactId>rita</artifactId>
<version>2.4.501</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,32 @@
/*
* Copyright © 2023, Oracle and/or its affiliates.
* Released under the Universal Permissive License v1.0 as shown at https://oss.oracle.com/licenses/upl/.
*/
package com.example.benchmarks.jibber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
@Autowired
Jabberwocky j;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(method = RequestMethod.GET, path = "/jibber")
ResponseEntity<String> jibber() {
return ResponseEntity.ok(j.generate());
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright © 2023, Oracle and/or its affiliates.
* Released under the Universal Permissive License v1.0 as shown at https://oss.oracle.com/licenses/upl/.
*/
package com.example.benchmarks.jibber;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import rita.RiMarkov;
@Service
@Scope("singleton")
public class Jabberwocky {
//
private RiMarkov r;
public Jabberwocky() {
loadModel();
}
private void loadModel() {
//
String text = "Twas brillig, and the slithy toves " +
"Did gyre and gimble in the wabe: " +
"All mimsy were the borogoves, " +
"And the mome raths outgrabe. " +
"Beware the Jabberwock, my son! " +
"The jaws that bite, the claws that catch! " +
"Beware the Jubjub bird, and shun " +
"The frumious Bandersnatch! " +
"He took his vorpal sword in hand; " +
"Long time the manxome foe he sought— " +
"So rested he by the Tumtum tree " +
"And stood awhile in thought. " +
"And, as in uffish thought he stood, " +
"The Jabberwock, with eyes of flame, " +
"Came whiffling through the tulgey wood, " +
"And burbled as it came! " +
"One, two! One, two! And through and through " +
"The vorpal blade went snicker-snack! " +
"He left it dead, and with its head " +
"He went galumphing back. " +
"And hast thou slain the Jabberwock? " +
"Come to my arms, my beamish boy! " +
"O frabjous day! Callooh! Callay! " +
"He chortled in his joy. " +
"Twas brillig, and the slithy toves " +
"Did gyre and gimble in the wabe: " +
"All mimsy were the borogoves, " +
"And the mome raths outgrabe.";
this.r = new RiMarkov(3);
this.r.addText(text);
}
public String generate() {
String[] lines = this.r.generate(10);
StringBuilder b = new StringBuilder();
//
for (String line : lines ) {
b.append(line);
b.append("<br/>\n");
}
//
return b.toString();
}
}

View File

@@ -0,0 +1 @@
management.endpoints.web.exposure.include=metrics,health,info,prometheus