Java Code Examples for org.apache.servicecomb.swagger.invocation.AsyncResponse#handle()

The following examples show how to use org.apache.servicecomb.swagger.invocation.AsyncResponse#handle() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZipkinTracingHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private AsyncResponse onResponse(Invocation invocation, AsyncResponse asyncResp, Span span) {
  return response -> {
    Throwable error = response.isFailed() ? response.getResult() : null;
    tracingDelegate.onResponse(span, response, error);

    LOGGER.debug("{}: Completed invocation on {}",
        tracingDelegate.name(),
        invocation.getOperationName(),
        error);

    asyncResp.handle(response);
  };
}
 
Example 2
Source File: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  AsyncResponse response = asyncResp;
  asyncResp = async -> {
    if (Boolean.TRUE.equals(invocation.getLocalContext(IsolationDiscoveryFilter.TRYING_INSTANCES_EXISTING))) {
      ServiceCombServerStats.releaseTryingChance();
    }
    response.handle(async);
  };

  if (handleSuppliedEndpoint(invocation, asyncResp)) {
    return;
  }

  String strategy = Configuration.INSTANCE.getRuleStrategyName(invocation.getMicroserviceName());
  if (!Objects.equals(strategy, this.strategy)) {
    //配置变化,需要重新生成所有的lb实例
    synchronized (lock) {
      clearLoadBalancer();
    }
  }
  this.strategy = strategy;

  LoadBalancer loadBalancer = getOrCreateLoadBalancer(invocation);

  if (!Configuration.INSTANCE.isRetryEnabled(invocation.getMicroserviceName())) {
    send(invocation, asyncResp, loadBalancer);
  } else {
    sendWithRetry(invocation, asyncResp, loadBalancer);
  }
}
 
Example 3
Source File: ProducerOperationHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void doCompletableFutureInvoke(Invocation invocation, SwaggerProducerOperation producerOperation,
    AsyncResponse asyncResp) {
  try {
    invocation.onBusinessMethodStart();

    Object[] args = invocation.toProducerArguments();
    for (ProducerInvokeExtension producerInvokeExtension : producerOperation.getProducerInvokeExtenstionList()) {
      producerInvokeExtension.beforeMethodInvoke(invocation, producerOperation, args);
    }

    Object result = producerOperation.getProducerMethod().invoke(producerOperation.getProducerInstance(), args);
    invocation.onBusinessMethodFinish();

    ((CompletableFuture<Object>) result).whenComplete((realResult, ex) -> {
      invocation.onBusinessFinish();
      if (ex == null) {
        asyncResp.handle(producerOperation.getResponseMapper().mapResponse(invocation.getStatus(), realResult));
        return;
      }

      asyncResp.handle(processException(invocation, ex));
    });
  } catch (Throwable e) {
    if (shouldPrintErrorLog(e)) {
      invocation.getTraceIdLogger().error(LOGGER, "unexpected error {},",
          invocation.getInvocationQualifiedName(), e);
    }
    invocation.onBusinessMethodFinish();
    invocation.onBusinessFinish();
    asyncResp.handle(processException(invocation, e));
  }
}
 
Example 4
Source File: InvokerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * This is an internal API, caller make sure already invoked SCBEngine.ensureStatusUp
 * @param invocation
 * @param asyncResp
 */
public static void reactiveInvoke(Invocation invocation, AsyncResponse asyncResp) {
  try {
    invocation.onStart(null, System.nanoTime());
    invocation.setSync(false);

    ReactiveResponseExecutor respExecutor = new ReactiveResponseExecutor();
    invocation.setResponseExecutor(respExecutor);

    invocation.getInvocationStageTrace().startHandlersRequest();
    invocation.next(ar -> {
      ContextUtils.setInvocationContext(invocation.getParentContext());
      try {
        invocation.getInvocationStageTrace().finishHandlersResponse();
        invocation.onFinish(ar);
        asyncResp.handle(ar);
      } finally {
        ContextUtils.removeInvocationContext();
      }
    });
  } catch (Throwable e) {
    invocation.getInvocationStageTrace().finishHandlersResponse();
    //if throw exception,we can use 500 for status code ?
    Response response = Response.createConsumerFail(e);
    invocation.onFinish(response);
    LOGGER.error("invoke failed, {}", invocation.getOperationMeta().getMicroserviceQualifiedName());
    asyncResp.handle(response);
  }
}
 
Example 5
Source File: TestLoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  ConfigUtil.installDynamicConfig();
  scbEngine = SCBBootstrap.createSCBEngineForTest().run();
  transportManager = scbEngine.getTransportManager();

  new MockUp<Invocation>(invocation) {
    @Mock
    String getMicroserviceName() {
      return microserviceName;
    }

    @Mock
    void next(AsyncResponse asyncResp) throws Exception {
      asyncResp.handle(sendResponse);
    }
  };

  new MockUp<TransportManager>(transportManager) {
    @Mock
    Transport findTransport(String transportName) {
      return restTransport;
    }
  };

  new Expectations(SPIServiceUtils.class) {
    {
      SPIServiceUtils.getSortedService(DiscoveryFilter.class);
      result = Collections.emptyList();
    }
  };

  BeansHolder holder = new BeansHolder();
  List<ExtensionsFactory> extensionsFactories = new ArrayList<>();
  extensionsFactories.add(new RuleNameExtentionsFactory());
  extensionsFactories.add(new DefaultRetryExtensionsFactory());
  Deencapsulation.setField(holder, "extentionsFactories", extensionsFactories);
  holder.init();

  handler = new LoadbalanceHandler();
  loadBalancerMap = Deencapsulation.getField(handler, "loadBalancerMap");
}
 
Example 6
Source File: ProducerOperationHandler.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public void syncInvoke(Invocation invocation, SwaggerProducerOperation producerOperation, AsyncResponse asyncResp) {
  ContextUtils.setInvocationContext(invocation);
  Response response = doInvoke(invocation, producerOperation);
  ContextUtils.removeInvocationContext();
  asyncResp.handle(response);
}