use of com.alipay.sofa.rpc.core.invoke.SofaResponseCallback in project sofa-rpc by sofastack.
the class CallbackClientMain method main.
public static void main(String[] args) throws InterruptedException {
ApplicationConfig applicationConfig = new ApplicationConfig().setAppName("future-server");
ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>().setApplication(applicationConfig).setInterfaceId(HelloService.class.getName()).setInvokeType(RpcConstants.INVOKER_TYPE_CALLBACK).setTimeout(5000).setOnReturn(new SofaResponseCallback() {
@Override
public void onAppResponse(Object appResponse, String methodName, RequestBase request) {
LOGGER.info("Interface get result: {}", appResponse);
}
@Override
public void onAppException(Throwable throwable, String methodName, RequestBase request) {
LOGGER.info("Interface get app exception: {}", throwable);
}
@Override
public void onSofaException(SofaRpcException sofaException, String methodName, RequestBase request) {
LOGGER.info("Interface get sofa exception: {}", sofaException);
}
}).setDirectUrl("bolt://127.0.0.1:22222?appName=future-server");
HelloService helloService = consumerConfig.refer();
LOGGER.warn("started at pid {}", RpcRuntimeContext.PID);
try {
for (int i = 0; i < 100; i++) {
try {
String s = helloService.sayHello("xxx", 22);
LOGGER.warn("{}", s);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
} catch (Exception e) {
LOGGER.error("", e);
}
synchronized (CallbackClientMain.class) {
while (true) {
CallbackClientMain.class.wait();
}
}
}
use of com.alipay.sofa.rpc.core.invoke.SofaResponseCallback in project sofa-rpc by sofastack.
the class AbstractHttp2ClientTransport method doInvokeAsync.
/**
* 异步调用
*
* @param request 请求对象
* @param rpcContext RPC内置上下文
* @param timeoutMillis 超时时间(毫秒)
*/
protected ResponseFuture doInvokeAsync(SofaRequest request, RpcInternalContext rpcContext, int timeoutMillis) {
SofaResponseCallback listener = request.getSofaResponseCallback();
if (listener != null) {
AbstractHttpClientHandler callback = new CallbackInvokeClientHandler(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), listener, request, rpcContext, ClassLoaderUtils.getCurrentClassLoader());
doSend(request, callback, timeoutMillis);
return null;
} else {
HttpResponseFuture future = new HttpResponseFuture(request, timeoutMillis);
AbstractHttpClientHandler callback = new FutureInvokeClientHandler(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), future, request, rpcContext, ClassLoaderUtils.getCurrentClassLoader());
doSend(request, callback, timeoutMillis);
future.setSentTime();
return future;
}
}
use of com.alipay.sofa.rpc.core.invoke.SofaResponseCallback in project sofa-rpc by sofastack.
the class AbstractCluster method doSendMsg.
/**
* 调用客户端
*
* @param transport 客户端连接
* @param request Request对象
* @return 调用结果
* @throws SofaRpcException rpc异常
*/
protected SofaResponse doSendMsg(ProviderInfo providerInfo, ClientTransport transport, SofaRequest request) throws SofaRpcException {
RpcInternalContext context = RpcInternalContext.getContext();
// 添加调用的服务端远程地址
RpcInternalContext.getContext().setRemoteAddress(providerInfo.getHost(), providerInfo.getPort());
try {
// 根据服务端版本特殊处理
checkProviderVersion(providerInfo, request);
String invokeType = request.getInvokeType();
int timeout = resolveTimeout(request, consumerConfig, providerInfo);
SofaResponse response = null;
// 同步调用
if (RpcConstants.INVOKER_TYPE_SYNC.equals(invokeType)) {
long start = RpcRuntimeContext.now();
try {
response = transport.syncSend(request, timeout);
} finally {
if (RpcInternalContext.isAttachmentEnable()) {
long elapsed = RpcRuntimeContext.now() - start;
context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed);
}
}
} else // 单向调用
if (RpcConstants.INVOKER_TYPE_ONEWAY.equals(invokeType)) {
long start = RpcRuntimeContext.now();
try {
transport.oneWaySend(request, timeout);
response = buildEmptyResponse(request);
} finally {
if (RpcInternalContext.isAttachmentEnable()) {
long elapsed = RpcRuntimeContext.now() - start;
context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed);
}
}
} else // Callback调用
if (RpcConstants.INVOKER_TYPE_CALLBACK.equals(invokeType)) {
// 调用级别回调监听器
SofaResponseCallback sofaResponseCallback = request.getSofaResponseCallback();
if (sofaResponseCallback == null) {
SofaResponseCallback methodResponseCallback = consumerConfig.getMethodOnreturn(request.getMethodName());
if (methodResponseCallback != null) {
// 方法的Callback
request.setSofaResponseCallback(methodResponseCallback);
}
}
// 记录发送开始时间
context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now());
// 开始调用
transport.asyncSend(request, timeout);
response = buildEmptyResponse(request);
} else // Future调用
if (RpcConstants.INVOKER_TYPE_FUTURE.equals(invokeType)) {
// 记录发送开始时间
context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now());
// 开始调用
ResponseFuture future = transport.asyncSend(request, timeout);
// 放入线程上下文
RpcInternalContext.getContext().setFuture(future);
response = buildEmptyResponse(request);
} else {
throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Unknown invoke type:" + invokeType);
}
return response;
} catch (SofaRpcException e) {
throw e;
} catch (Throwable e) {
// 客户端其它异常
throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, e);
}
}
use of com.alipay.sofa.rpc.core.invoke.SofaResponseCallback in project sofa-rpc by sofastack.
the class JacksonSerializerTest method buildRequest.
private SofaRequest buildRequest(String methodName, Object[] args) throws NoSuchMethodException {
SofaRequest request = new SofaRequest();
request.setInterfaceName(DemoService.class.getName());
request.setMethodName(methodName);
Method method = null;
for (Method m : DemoService.class.getMethods()) {
if (m.getName().equals(methodName)) {
method = m;
}
}
request.setMethod(method);
request.setMethodArgs(args);
List<String> argSigs = new ArrayList<String>();
for (Object req : args) {
argSigs.add(req.getClass().getName());
}
request.setMethodArgSigs(argSigs.toArray(new String[argSigs.size()]));
request.setTargetServiceUniqueName(DemoService.class.getName() + ":1.0");
request.setTargetAppName("targetApp");
request.setSerializeType((byte) 12);
request.setTimeout(1024);
request.setInvokeType(RpcConstants.INVOKER_TYPE_SYNC);
Map<String, String> map = new HashMap<String, String>();
map.put("a", "xxx");
map.put("b", "yyy");
request.addRequestProp(RemotingConstants.RPC_TRACE_NAME, map);
request.setSofaResponseCallback(new SofaResponseCallback() {
@Override
public void onAppResponse(Object appResponse, String methodName, RequestBase request) {
}
@Override
public void onAppException(Throwable throwable, String methodName, RequestBase request) {
}
@Override
public void onSofaException(SofaRpcException sofaException, String methodName, RequestBase request) {
}
});
return request;
}
use of com.alipay.sofa.rpc.core.invoke.SofaResponseCallback in project sofa-boot by sofastack.
the class ConsumerConfigHelper method getConsumerConfig.
/**
* 获取 ConsumerConfig
*
* @param contract the Contract
* @param binding the RpcBinding
* @return the ConsumerConfig
*/
public ConsumerConfig getConsumerConfig(Contract contract, RpcBinding binding) {
RpcBindingParam param = binding.getRpcBindingParam();
String id = binding.getBeanId();
String interfaceId = contract.getInterfaceType().getName();
String uniqueId = contract.getUniqueId();
Integer timeout = param.getTimeout();
Integer retries = param.getRetries();
String type = param.getType();
Integer addressWaitTime = param.getAddressWaitTime();
Object callbackHandler = param.getCallbackHandler();
String genericInterface = param.getGenericInterface();
String loadBalancer = param.getLoadBalancer();
Boolean lazy = param.getLazy();
Boolean check = param.getCheck();
String mockMode = param.getMockMode();
String serialization = param.getSerialization();
List<Filter> filters = param.getFilters();
List<MethodConfig> methodConfigs = convertToMethodConfig(param.getMethodInfos());
String targetUrl = param.getTargetUrl();
String referenceLimit = sofaBootRpcProperties.getConsumerRepeatedReferenceLimit();
ConsumerConfig consumerConfig = new ConsumerConfig();
if (StringUtils.hasText(appName)) {
consumerConfig.setApplication(new ApplicationConfig().setAppName(appName));
}
if (StringUtils.hasText(id)) {
consumerConfig.setId(id);
}
if (StringUtils.hasText(genericInterface)) {
consumerConfig.setGeneric(true);
consumerConfig.setInterfaceId(genericInterface);
} else if (StringUtils.hasText(interfaceId)) {
consumerConfig.setInterfaceId(interfaceId);
}
if (StringUtils.hasText(uniqueId)) {
consumerConfig.setUniqueId(uniqueId);
}
if (timeout != null) {
consumerConfig.setTimeout(timeout);
}
if (retries != null) {
consumerConfig.setRetries(retries);
}
if (StringUtils.hasText(type)) {
consumerConfig.setInvokeType(type);
}
if (addressWaitTime != null) {
consumerConfig.setAddressWait(addressWaitTime);
}
if (StringUtils.hasText(loadBalancer)) {
consumerConfig.setLoadBalancer(loadBalancer);
}
if (lazy != null) {
consumerConfig.setLazy(lazy);
}
if (check != null) {
consumerConfig.setCheck(check);
}
if (mockMode != null) {
consumerConfig.setMockMode(mockMode);
}
if (callbackHandler != null) {
if (callbackHandler instanceof SofaResponseCallback) {
consumerConfig.setOnReturn((SofaResponseCallback) callbackHandler);
} else {
throw new SofaBootRpcRuntimeException("callback handler must implement SofaResponseCallback [" + callbackHandler + "]");
}
}
if (!CollectionUtils.isEmpty(filters)) {
consumerConfig.setFilterRef(filters);
}
if (!CollectionUtils.isEmpty(methodConfigs)) {
consumerConfig.setMethods(methodConfigs);
}
if (StringUtils.hasText(targetUrl)) {
consumerConfig.setDirectUrl(targetUrl);
consumerConfig.setLazy(true);
consumerConfig.setSubscribe(false);
consumerConfig.setRegister(false);
}
if (StringUtils.hasText(referenceLimit)) {
consumerConfig.setRepeatedReferLimit(Integer.valueOf(referenceLimit));
}
String protocol = binding.getBindingType().getType();
consumerConfig.setBootstrap(protocol);
if (protocol.equals(SofaBootRpcConfigConstants.RPC_PROTOCOL_DUBBO)) {
consumerConfig.setInJVM(false);
}
if (param.getRegistrys() != null && param.getRegistrys().size() > 0) {
List<String> registrys = param.getRegistrys();
for (String registryAlias : registrys) {
RegistryConfig registryConfig = registryConfigContainer.getRegistryConfig(registryAlias);
consumerConfig.setRegistry(registryConfig);
}
} else if (registryConfigContainer.isMeshEnabled(protocol)) {
RegistryConfig registryConfig = registryConfigContainer.getRegistryConfig(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH);
consumerConfig.setRegistry(registryConfig);
} else {
RegistryConfig registryConfig = registryConfigContainer.getRegistryConfig();
consumerConfig.setRegistry(registryConfig);
}
if (StringUtils.hasText(serialization)) {
consumerConfig.setSerialization(serialization);
}
if (Boolean.TRUE.toString().equals(sofaBootRpcProperties.getHystrixEnable())) {
consumerConfig.setParameter(HystrixConstants.SOFA_HYSTRIX_ENABLED, Boolean.TRUE.toString());
}
// after sofaBootRpcProperties#getHystrixEnable for override global config
if (param.getParameters() != null) {
consumerConfig.setParameters(param.getParameters());
}
return consumerConfig.setProtocol(protocol);
}
Aggregations