使用AsynRestTemplate开发服务消费者

概念阐述

AsyncRestTemplate 开发方式允许用户异步的进行服务调用。具体的业务流程和 RestTemplate 类似,只是这里以异步的形式进行服务的调用。

示例代码

AsyncRestTemplate 实例通过 new CseAsyncRestTemplate()来创建和获取,再使用该实例通过自定义的 URL 进行服务调用。

  • Spring MVC 客户端代码示例
  1. @Component
  2. public class SpringmvcConsumerMain {
  3. private static final Logger LOG = LoggerFactory.getLogger(SpringmvcConsumerMain.class);
  4. public static void main(String[] args) throws Exception {
  5. init();
  6. Person person = new Person();
  7. person.setName("ServiceComb/Java Chassis");
  8. //AsyncRestTemplate Consumer
  9. CseAsyncRestTemplate cseAsyncRestTemplate = new CseAsyncRestTemplate();
  10. ListenableFuture<ResponseEntity<String>> responseEntityListenableFuture = cseAsyncRestTemplate
  11. .postForEntity("cse://springmvc/springmvchello/sayhi?name=Java Chassis", null, String.class);
  12. ResponseEntity<String> responseEntity = responseEntityListenableFuture.get();
  13. System.out.println("AsyncRestTemplate Consumer sayHi services: " + responseEntity.getBody());
  14. HttpEntity<Person> entity = new HttpEntity<>(person);
  15. ListenableFuture<ResponseEntity<String>> listenableFuture = cseAsyncRestTemplate
  16. .exchange("cse://springmvc/springmvchello/sayhello", HttpMethod.POST, entity, String.class);
  17. // ResponseEntity<String> responseEntity1 = listenableFuture.get();
  18. // System.out.println("AsyncRestTemplate Consumer sayHello services: " + responseEntity1.getBody());
  19. //设置回调函数
  20. listenableFuture.addCallback(
  21. new ListenableFutureCallback<ResponseEntity<String>>() {
  22. @Override
  23. public void onFailure(Throwable ex) {
  24. LOG.error("AsyncResTemplate Consumer catched exception when sayHello, ", ex);
  25. }
  26. @Override
  27. public void onSuccess(ResponseEntity<String> result) {
  28. System.out.println("AsyncRestTemplate Consumer sayHello services: " + result.getBody());
  29. }
  30. });
  31. }
  32. public static void init() throws Exception {
  33. Log4jUtils.init();
  34. BeanUtils.init();
  35. }
  36. }

说明 :

  • URL 的格式和 RestTemplate 一样,具体可以参考 restTemplate
  • 这里用自定义的 ListenableFuture 类来作为占位符,获取远程调用结束后可能获取的结果。同时也可以自定义回调函数,对可能返回的结果进行分批处理。