0

我有DefferedResult<Foo>在几秒钟内返回的服务方法,但我需要我的代码将等到该方法完成并返回带有设置结果的延迟结果。

这是示例代码:

@Service
public class FooService {
   // ...
   public DeferredResult<Foo> fetchFoo(long id) throws InterruptedException {
       DeferredResult<Foo> fooDeferredResult = new DeferredResult<>();
       concurrentMap.put(id, fooDeferredResult);
       return fooDeferredResult;
   }

   // this you can figure out as some handler or scheduler which receive messages and is called
   public void anotherMethod(Foo foo) {
       DeferredResult<Foo> remove = concurrentMap.remove(foo.getId());
       remove.setResult(foo);
   }
   // ...
}

我想在另一个服务中调用它:

@Service
public class AnotherService {

    @Autowired
    FooService fooService;

    public Foo bar(long id) {
        // some logic
        Foo foo = fooService.fetchFoo(id).getResult();
        // another logic which depends on received foo
        // there I need wait for result of fetchFoo method

        return foo;
    }

}

你能告诉我如何确保这种行为吗?谢谢你的建议。

4

1 回答 1

0

您可以CountDownLatch用于同步。例子:

public class Main {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(1);

        CountDownLatch latch = new CountDownLatch(1);
        getResult()
                .setResultHandler(result -> {
                    System.out.println(2 + " " + result);
                    latch.countDown();
                });

        latch.await();
        System.out.println(3);
    }

    public static DeferredResult<String> getResult() {
        DeferredResult<String> result = new DeferredResult<>();
        
        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result.setResult("Hello");
        })
                .start();
        return result;
    }
}
于 2021-10-04T08:46:13.580 回答