给定一个由存储库
支持的具有读取
和写入
操作的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/