具有异步方法调用的 Java 服务

标签 java spring asynchronous akka executorservice

给定一个由存储库支持的具有读取写入操作的FooService,我想提供一个<它的异步变体用于 Spring REST Web 服务(可能使用Akka,因为它已经是其他问题的候选者......)。

到目前为止,我有冗长且有些笨重的变体

class AsyncFooService extends FooService {

    private final ExecutorService executor = Executors.newCachedThreadPool();
    private final FooService delegate = ...

    @Override
    public void writeSomeThing(Obj o) {
        executor.submit(new Runnable() {
           @Override
           public void run() {
               delegate.writeSomeThing(o);
           }
        });
    }

    // repeat same override & executor semantics for all write* routines
}

在实现服务的异步操作方面还有哪些其他好的变体?

为了限制范围,我们不要直接考虑代理,因为它们本身不提供解决方案。

最佳答案

由于涉及到一些 Spring,我只会使用 AOP 建议来稍微自动化您的“笨重”方法。建议类:

public class AsyncAdvice implements MethodInterceptor {

    @Inject
    private ExecutorService executorService;

    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                invocation.proceed();
            }
        });
    }
}

在applicationContext.xml中:

<!-- Synchronous instance -->
<bean id="fooService" class="FooService" scope="singleton">
    <!-- Whatever -->
</bean>

<!-- Asynchronous instance -->
<bean id="asyncFooService" parent="fooService" scope="singleton"/>

<bean id="asyncAdvice" class="AsyncAdvice" scope="singleton">
    <property name="executorService" ref="..."/>
</bean>

<aop:config>
    <aop:advice pointcut="bean(asyncFooService)" and execution=(* FooService.write*(..))"
                advice="asyncAdvice"/>
</aop:config>

这是一个非常轻量级的解决方案。不管怎样,你的最后一段让我觉得你想要一个更加自动化的解决方案。

关于具有异步方法调用的 Java 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298505/

相关文章:

java - Eclipse 中的交互式控制台

java.lang.IllegalArgumentException : Invalid format: "2018-08-24T��:��:��" is malformed at "��:��:��"

spring - 在 Spring Boot 应用程序中提取 docker secret 而不是使用属性文件

java - Spring Source Toolsuite (STS) - 使用 Java-Config 时的批处理图

node.js - 更新 async.each 中的请求参数?

java - 如何将数组字节转换为 org.w3c.dom.Document

java - 通过 Web 的 API : use 80 port or a custom one (like 8080)?

java - 在 sessionFactory 初始化之前更改实体模式名称

javascript - mongodb更新不会立即更新

c# - 从异步方法将字符串添加到 StringBuilder