java webassembly 集成试用

发布时间 2023-11-01 09:32:50作者: 荣锋亮

wasmerio 这个组织实现了不少webassembly 周边的工具,以下是一个简单的java 集成试用

安装命令

因为java 包默认没有发布到中央仓库,需要自己本地安装

  • local maven
mvn install:install-file -Dfile=./wasmer-jni-amd64-darwin-0.3.0.jar -DgroupId=org.wasmer -DartifactId=wasmer-jni-amd64-darwin -Dversion=0.3.0 -Dpackaging=jar -DgeneratePom=true -DlocalRepositoryPath=..../local-maven/repo

wasm 生成

就是一个基于rust 的简单项目,试用了wasm-bingen

  • lib.rs
    注意因为不同版本wasm 对于其他扩展类型支持的问题,此方法使用了标准类型
 
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(age:i32) ->i32 {
   age
}
  • 构建
    使用了wasm-pack
 
wasm-pack build --target nodejs
  • 效果

java 项目集成

  • pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.dalong</groupId>
    <artifactId>wasm-app</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.wasmer</groupId>
            <artifactId>wasmer-jni-amd64-darwin</artifactId>
            <version>0.3.0</version>
        </dependency>
    </dependencies>
 
    <repositories>
        <repository>
            <id>local-maven-repo</id>
            <url>file:///xxxx/local-maven/repo</url> // 使用本地模式
        </repository>
    </repositories>
 
</project>
  • 代码加载wasm
package com.dalong;
 
import org.wasmer.Instance;
 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class Main {
    public static void main(String[] args) throws IOException {
        Path wasmPath = Paths.get(new Main().getClass().getClassLoader().getResource("app_bg.wasm").getPath());
 
        // Reads the WebAssembly module as bytes.
        byte[] wasmBytes = Files.readAllBytes(wasmPath);
 
        // Instantiates the WebAssembly module.
        Instance instance = new Instance(wasmBytes);
 
        // Calls an exported function, and returns an object array.
        Object[] results = instance.exports.getFunction("greet").apply(100);
 
        System.out.println((int) results[0]);
 
        // Drops an instance object pointer which is stored in Rust.
        instance.close();
    }
}
  • 运行

因为我使用了mac系统,但是似乎在启动的是否native jni 对于os 的架构识别有问题,需要自己配置下

 

  • 效果

 

说明

以上是一个简单的试用,实际上目前wasmer-java 活跃度一般,简单场景够用,webassembly 做为一个方便可跨平台的模式还是很不错的

参考资料

https://github.com/wasmerio/wasmer-java
https://github.com/rustwasm/wasm-pack
https://medium.com/wasmer/announcing-the-first-java-library-to-run-webassembly-wasmer-jni-89e319d2ac7c