简体   繁体   English

MonetaryException:未加载 MonetaryAmountsSingletonSpi

[英]MonetaryException: No MonetaryAmountsSingletonSpi loaded

Problem description问题描述

I have a java project with gradle dependency from org.javamoney:moneta:1.3 .我有一个 java 项目,它具有来自org.javamoney:moneta:1.3的 gradle 依赖项。

Also I have two Kubernetes clusters.我还有两个 Kubernetes 集群。 I deploy my java application using docker-container.我使用 docker-container 部署了我的 java 应用程序。

When I deploy my app in the first Kubernetes cluster everything is fine.当我在第一个Kubernetes 集群中部署我的应用程序时,一切都很好。 But when I deploy my app (the same docker-container) in the second Kubernetes cluster following error appears:但是当我在第二个Kubernetes 集群中部署我的应用程序(相同的 docker 容器)时,会出现以下错误:

javax.money.MonetaryException: No MonetaryAmountsSingletonSpi loaded.
    at javax.money.Monetary.lambda$getDefaultAmountFactory$13(Monetary.java:291)
    at java.base/java.util.Optional.orElseThrow(Optional.java:408)
    at javax.money.Monetary.getDefaultAmountFactory(Monetary.java:291)

It appears in the following code:它出现在以下代码中:

MonetaryAmount amount = javax.money.Monetary.getDefaultAmountFactory()
    .setCurrency("USD")
    .setNumber(1L)
    .create();

Software versions软件版本

  • Moneta : 1.3 .莫内塔1.3
  • Gradle: 6.0.1 . Gradle: 6.0.1
  • Base docker-image: openjdk:11.0.7-jdk-slim .基础 docker-image: openjdk:11.0.7-jdk-slim
  • Spring boot: 2.2.7.RELEASE . Spring 启动: 2.2.7.RELEASE
  • Kubernetes (the same version on both clusters): Server Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.3", GitCommit:"2d3c76f9091b6bec110a5e63777c332469e0cba2", GitTreeState:"clean", BuildDate:"2019-08-19T11:05:50Z", GoVersion:"go1.12.9", Compiler:"gc", Platform:"linux/amd64"} . Kubernetes(两个集群上的版本相同): Server Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.3", GitCommit:"2d3c76f9091b6bec110a5e63777c332469e0cba2", GitTreeState:"clean", BuildDate:"2019-08-19T11:05:50Z", GoVersion:"go1.12.9", Compiler:"gc", Platform:"linux/amd64"}
  • Java: java -version openjdk version "11.0.7" 2020-04-14 OpenJDK Runtime Environment 18.9 (build 11.0.7+10) OpenJDK 64-Bit Server VM 18.9 (build 11.0.7+10, mixed mode) . Java: java -version openjdk version "11.0.7" 2020-04-14 OpenJDK Runtime Environment 18.9 (build 11.0.7+10) OpenJDK 64-Bit Server VM 18.9 (build 11.0.7+10, mixed mode)

What I have tried我试过的

Declare gradle-dependency differently以不同的方式声明 gradle-dependency

I found this question and it gave me an idea try to declare gradle-dependency in some different way.我发现了这个问题,它给了我一个想法,尝试以某种不同的方式声明 gradle-dependency。 I have tried:我努力了:

  • implementation 'org.javamoney:moneta:1.3'
  • compile group: 'org.javamoney', name: 'moneta', version: '1.3', ext: 'pom'
  • compile 'org.javamoney:moneta:1.3'
  • runtimeOnly 'org.javamoney:moneta:1.3'

Unfortunately, it did not give any positive results.不幸的是,它没有给出任何积极的结果。

Copy-paste service loader configurations for Moneta Moneta 的复制粘贴服务加载器配置

As mentioned in this comment I've tried to copy service loader configuration from Moneta to following project directory: src/main/resources/META-INF/services .如此评论中提到的,我尝试将服务加载器配置从 Moneta复制到以下项目目录: src/main/resources/META-INF/services

Unfortunately, it didn't help.不幸的是,它没有帮助。

Init custom currency without spring初始化自定义货币没有 spring

I've tried to do it just in the Main-class, but it didn't solve the problem.我试图只在 Main-class 中这样做,但它并没有解决问题。

Questions问题

  1. What is the root-cause of this problem?这个问题的根本原因是什么?
  2. What is the proper solution to this problem?这个问题的正确解决方案是什么?

TL;DR TL;博士

The problem was in concurrent moneta SPI initialization within Java 11.问题在于 Java 11 中的并发 moneta SPI 初始化。

Problem solution问题方案

The problem can be solved by extracting MonetaryAmountFactory to spring-bean and injecting it where needed:这个问题可以通过将MonetaryAmountFactory提取到 spring-bean 并在需要的地方注入来解决:

@Bean
public MonetaryAmountFactory<?> money() {
    return Monetary.getDefaultAmountFactory();
}


@Component
@RequiredArgsConstructor
public static class Runner implements CommandLineRunner {

    private final MonetaryAmountFactory<?> amountFactory;

    @Override
    public void run(String... args) {
        var monetaryAmount = this.amountFactory
            .setCurrency("EUR")
            .setNumber(1)
            .create();

        System.out.println("monetaryAmount = " + monetaryAmount);
    }
}

instead of using this factory directly:而不是直接使用这个工厂:

public static class Runner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        var monetaryAmount = Monetary.getDefaultAmountFactory()
            .setCurrency("EUR")
            .setNumber(1)
            .create();

        System.out.println("monetaryAmount = " + monetaryAmount);
    }
}

Why problem occurs on Kubernetes-clusters?为什么 Kubernetes 集群会出现问题?

I discovered that there were diferrent resource limit configuration on above-mentioned Kubernetes-clusters.我发现上面提到的 Kubernetes 集群上存在不同的资源限制配置

Cluster with exception:集群异常:

Limits:
  cpu:     6
  memory:  20G
Requests:
  cpu:      3
  memory:   20G

Cluster without exception:集群无一例外:

Limits:
  cpu:     2
  memory:  2G
Requests:
  cpu:      2
  memory:   128Mi

Seems that cluster with more resources gives more opportunity to concurrent moneta initialization happened.似乎具有更多资源的集群为发生并发 moneta 初始化提供了更多机会。

Minimal reproducible example最小的可重现示例

The minimal reproducible example can be found in this github-repository .可以在这个 github-repository中找到最小的可重现示例。

It is worth mentioned that the bug is not reproduced on Java 8.值得一提的是,该错误在 Java 8 上没有重现。

as a workaround you can create a service provider like作为一种解决方法,您可以创建一个服务提供商,例如

public class MyServiceLoader implements ServiceProvider {
/**
 * List of services loaded, per class.
 */
private final ConcurrentHashMap<Class<?>, List<Object>> servicesLoaded = new ConcurrentHashMap<>();
private static final int PRIORITY = 10;

/**
 * Returns a priority value of 10.
 *
 * @return 10, overriding the default provider.
 */
@Override
public int getPriority() {
    return PRIORITY;
}

/**
 * Loads and registers services.
 *
 * @param serviceType The service type.
 * @param <T>         the concrete type.
 * @return the items found, never {@code null}.
 */
@Override
public <T> List<T> getServices(final Class<T> serviceType) {
    @SuppressWarnings("unchecked")
    List<T> found = (List<T>) servicesLoaded.get(serviceType);
    if (found != null) {
        return found;
    }

    return loadServices(serviceType);
}

public static int compareServices(Object o1, Object o2) {
    int prio1 = 0;
    int prio2 = 0;
    Priority prio1Annot = o1.getClass().getAnnotation(Priority.class);
    if (prio1Annot != null) {
        prio1 = prio1Annot.value();
    }
    Priority prio2Annot = o2.getClass().getAnnotation(Priority.class);
    if (prio2Annot != null) {
        prio2 = prio2Annot.value();
    }
    if (prio1 < prio2) {
        return 1;
    }
    if (prio2 < prio1) {
        return -1;
    }
    return o2.getClass().getSimpleName().compareTo(o1.getClass().getSimpleName());
}

/**
 * Loads and registers services.
 *
 * @param serviceType The service type.
 * @param <T>         the concrete type.
 * @return the items found, never {@code null}.
 */
private <T> List<T> loadServices(final Class<T> serviceType) {
    List<T> services = new ArrayList<>();
    try {
        for (T t : ServiceLoader.load(serviceType, Monetary.class.getClassLoader())) {
            services.add(t);
        }
        services.sort(CbplMonetaServiceProvider::compareServices);
        @SuppressWarnings("unchecked") final List<T> previousServices = (List<T>) servicesLoaded.putIfAbsent(serviceType, (List<Object>) services);
        return Collections.unmodifiableList(previousServices != null ? previousServices : services);
    } catch (Exception e) {
        Logger.getLogger(CbplMonetaServiceProvider.class.getName()).log(Level.WARNING,
                "Error loading services of type " + serviceType, e);
        services.sort(CbplMonetaServiceProvider::compareServices);
        return services;
    }
}
}

and before using any money library class call在使用任何货币库 class 之前调用

Bootstrap.init(new CbplMonetaServiceProvider());

this will fix the Currency error too.这也将修复货币错误。

the only changed line on the provider we added compared to the PriorityAwareServiceProvider is this line与 PriorityAwareServiceProvider 相比,我们添加的提供程序上唯一更改的行是这一行

for(T service:ServiceLoader.load(serviceType, Monetary.class.getClassLoader())){

we just specified the class loader so instead of Thread.getCurrentThread().getClassLoader() it is using the class loader we provide.我们刚刚指定了 class 加载程序,所以它使用的是我们提供的 class 加载程序,而不是 Thread.getCurrentThread().getClassLoader()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM