下面列出了怎么用com.alibaba.dubbo.rpc.Result的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public <T> Invoker<T> join(Directory<T> directory) throws RpcException {
return new AbstractClusterInvoker<T>(directory) {
@Override
public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
for (Invoker<T> invoker : invokers) {
if (invoker.isAvailable()) {
return invoker.invoke(invocation);
}
}
throw new RpcException("No provider available in " + invokers);
}
};
}
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
Map<String, String> attachments = invocation.getAttachments();
if (attachments != null) {
attachments = new HashMap<>(attachments);
attachments.remove(Constants.PATH_KEY);
attachments.remove(Constants.GROUP_KEY);
attachments.remove(Constants.VERSION_KEY);
attachments.remove(Constants.DUBBO_VERSION_KEY);
attachments.remove(Constants.TOKEN_KEY);
attachments.remove(Constants.TIMEOUT_KEY);
}
RpcContext.getContext()
.setInvoker(invoker)
.setInvocation(invocation)
.setAttachments(attachments)
.setLocalAddress(invoker.getUrl().getHost(),
invoker.getUrl().getPort());
if (invocation instanceof RpcInvocation) {
((RpcInvocation)invocation).setInvoker(invoker);
}
try {
return invoker.invoke(invocation);
} finally {
RpcContext.removeContext();
}
}
public Result consumerInvokeForJTA(Invoker<?> invoker, Invocation invocation) throws RpcException {
TransactionBeanRegistry beanRegistry = TransactionBeanRegistry.getInstance();
TransactionBeanFactory beanFactory = beanRegistry.getBeanFactory();
RemoteCoordinator transactionCoordinator = (RemoteCoordinator) beanFactory.getNativeParticipant();
Map<String, String> attachments = invocation.getAttachments();
attachments.put(RemoteCoordinator.class.getName(), transactionCoordinator.getIdentifier());
RpcResult result = (RpcResult) invoker.invoke(invocation);
Object value = result.getValue();
if (InvocationResult.class.isInstance(value)) {
InvocationResult wrapped = (InvocationResult) value;
result.setValue(null);
result.setException(null);
if (wrapped.isFailure()) {
result.setException(wrapped.getError());
} else {
result.setValue(wrapped.getValue());
}
} // end-if (InvocationResult.class.isInstance(value))
return result;
}
@Test
public void testInvokerNonJsonPojoSerialization() {
invocation = EasyMock.createMock(Invocation.class);
EasyMock.expect(invocation.getMethodName()).andReturn("echo").anyTimes();
EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { String.class }).anyTimes();
EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
EasyMock.replay(invocation);
invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
RpcResult result = new RpcResult();
result.setValue("hello");
EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
EasyMock.replay(invoker);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals("hello", filterResult.getValue());
}
@Test
public void testInvokerNonJsonNonPojoSerialization() {
invocation = EasyMock.createMock(Invocation.class);
EasyMock.expect(invocation.getMethodName()).andReturn("echo").anyTimes();
EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] {String.class }).anyTimes();
EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
EasyMock.replay(invocation);
invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
RpcResult result = new RpcResult();
result.setValue(new String[]{"High"});
EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
EasyMock.replay(invoker);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertArrayEquals(new String[]{"High"}, (String[])filterResult.getValue());
}
public Result invoke(final Invocation invocation) throws RpcException {
checkWheatherDestoried();
LoadBalance loadbalance;
List<Invoker<T>> invokers = list(invocation);
if (invokers != null && invokers.size() > 0) {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
.getMethodParameter(invocation.getMethodName(),Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));
} else {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE);
}
RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
return doInvoke(invocation, invokers, loadbalance);
}
@Test()
public void testInvokeWithRPCException() {
EasyMock.reset(invoker1);
EasyMock.expect(invoker1.invoke(invocation)).andThrow(new RpcException()).anyTimes();
EasyMock.expect(invoker1.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker1.getUrl()).andReturn(url).anyTimes();
EasyMock.expect(invoker1.getInterface()).andReturn(FailoverClusterInvokerTest.class).anyTimes();
EasyMock.replay(invoker1);
EasyMock.reset(invoker2);
EasyMock.expect(invoker2.invoke(invocation)).andReturn(result).anyTimes();
EasyMock.expect(invoker2.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker2.getUrl()).andReturn(url).anyTimes();
EasyMock.expect(invoker2.getInterface()).andReturn(FailoverClusterInvokerTest.class).anyTimes();
EasyMock.replay(invoker2);
FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<FailoverClusterInvokerTest>(dic);
for(int i=0;i<100;i++){
Result ret = invoker.invoke(invocation);
assertSame(result, ret);
}
}
@Test
public void testInvokerNonJsonPojoSerialization() {
invocation = EasyMock.createMock(Invocation.class);
EasyMock.expect(invocation.getMethodName()).andReturn("echo").anyTimes();
EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { String.class }).anyTimes();
EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
EasyMock.replay(invocation);
invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
RpcResult result = new RpcResult();
result.setValue("hello");
EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
EasyMock.replay(invoker);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals("hello", filterResult.getValue());
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
// do not record
if ("$echo".equals(invocation.getMethodName())) {
return invoker.invoke(invocation);
}
RpcContext rpcContext = RpcContext.getContext();
// get appName
if (StringUtils.isBlank(this.appName)) {
this.appName = SofaTracerConfiguration
.getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
}
// get span kind by rpc request type
String spanKind = spanKind(rpcContext);
Result result;
if (spanKind.equals(Tags.SPAN_KIND_SERVER)) {
result = doServerFilter(invoker, invocation);
} else {
result = doClientFilter(rpcContext, invoker, invocation);
}
return result;
}
public Result invoke(final Invocation invocation) throws RpcException {
checkWheatherDestoried();
LoadBalance loadbalance;
List<Invoker<T>> invokers = list(invocation);
if (invokers != null && invokers.size() > 0) {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
.getMethodParameter(invocation.getMethodName(),Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));
} else {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE);
}
RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
return doInvoke(invocation, invokers, loadbalance);
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
// 已经超过了tps不允许执行业务方法
if (!tpsLimiter.isAllowable(invoker.getUrl(), invocation)) {
throw new RpcException(
"Failed to invoke service " +
invoker.getInterface().getName() +
"." +
invocation.getMethodName() +
" because exceed max service tps.");
}
// 业务方法执行
return invoker.invoke(invocation);
}
@Test
public void testResulthasException() {
invocation = EasyMock.createMock(Invocation.class);
EasyMock.expect(invocation.getMethodName()).andReturn("enumlength").anyTimes();
EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Enum.class }).anyTimes();
EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
EasyMock.replay(invocation);
invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
RpcResult result = new RpcResult();
result.setException(new RuntimeException());
result.setValue("High");
EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
EasyMock.replay(invoker);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals(filterResult, result);
}
@Test
public void testInvokerJsonPojoSerialization() {
invocation = mock(Invocation.class);
given(invocation.getMethodName()).willReturn("enumlength");
given(invocation.getParameterTypes()).willReturn(new Class<?>[]{Type[].class});
given(invocation.getArguments()).willReturn(new Object[]{"hello"});
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
RpcResult result = new RpcResult();
result.setValue("High");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&serialization=json");
given(invoker.getUrl()).willReturn(url);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals(Type.High, filterResult.getValue());
}
@Test
public void testInvokerNonJsonNonPojoSerialization() {
invocation = EasyMock.createMock(Invocation.class);
EasyMock.expect(invocation.getMethodName()).andReturn("echo").anyTimes();
EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] {String.class }).anyTimes();
EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
EasyMock.replay(invocation);
invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
RpcResult result = new RpcResult();
result.setValue(new String[]{"High"});
EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
EasyMock.replay(invoker);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertArrayEquals(new String[]{"High"}, (String[])filterResult.getValue());
}
@Test
public void testInvokerNonJsonEnumSerialization() {
invocation = EasyMock.createMock(Invocation.class);
EasyMock.expect(invocation.getMethodName()).andReturn("enumlength").anyTimes();
EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[] { Type[].class }).anyTimes();
EasyMock.expect(invocation.getArguments()).andReturn(new Object[] { "hello" }).anyTimes();
EasyMock.replay(invocation);
invoker = EasyMock.createMock(Invoker.class);
EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
RpcResult result = new RpcResult();
result.setValue("High");
EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
EasyMock.replay(invoker);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals(Type.High, filterResult.getValue());
}
@Override
protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException {
Result result = (Result) data;
// currently, the version value in Response records the version of Request
boolean attach = Version.isSupportResponseAttatchment(version);
Throwable th = result.getException();
if (th == null) {
Object ret = result.getValue();
if (ret == null) {
out.writeByte(attach ? RESPONSE_NULL_VALUE_WITH_ATTACHMENTS : RESPONSE_NULL_VALUE);
} else {
out.writeByte(attach ? RESPONSE_VALUE_WITH_ATTACHMENTS : RESPONSE_VALUE);
out.writeObject(ret);
}
} else {
out.writeByte(attach ? RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS : RESPONSE_WITH_EXCEPTION);
out.writeObject(th);
}
if (attach) {
// returns current version of Response to consumer side.
result.getAttachments().put(Constants.DUBBO_VERSION_KEY, Version.getProtocolVersion());
out.writeObject(result.getAttachments());
}
}
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
final URL u = url;
return new Invoker<T>(){
public Class<T> getInterface(){
return null;
}
public URL getUrl(){
return u;
}
public boolean isAvailable(){
return true;
}
public Result invoke(Invocation invocation) throws RpcException{
return null;
}
public void destroy(){
}
};
}
@Override
public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
// 检查invoker是否可用
checkInvokers(invokers, invocation);
// 执行负载均衡策略
Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
try {
return invoker.invoke(invocation);
} catch (Throwable e) {
if (e instanceof RpcException && ((RpcException) e).isBiz()) { // biz exception.
throw (RpcException) e;
}
throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : 0, "Failfast invoke providers " + invoker.getUrl() + " " + loadbalance.getClass().getSimpleName() + " select from all providers " + invokers + " for service " + getInterface().getName() + " method " + invocation.getMethodName() + " on consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e.getCause() != null ? e.getCause() : e);
}
}
/**
* 测试mock策略是否正常-fail-mock
*/
@Test
public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2(){
URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
.addParameter("mock","fail")
.addParameter("invoke_return_error", "true" );
Invoker<IHelloService> cluster = getClusterInvoker(url);
//方法配置了mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assert.assertEquals("somethingmock", ret.getValue());
}
@Test
public void testMockInvokerFromOverride_Invoke_check_String(){
URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
.addParameter("getSomething.mock","force:return 1688")
.addParameter("invoke_return_error", "true" );
Invoker<IHelloService> cluster = getClusterInvoker(url);
//方法配置了mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assert.assertTrue("result type must be String but was : " + ret.getValue().getClass(), ret.getValue() instanceof String);
Assert.assertEquals("1688", (String)ret.getValue());
}
public Result invoke(Invocation invocation) throws RpcException {
Result result = null;
String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim();
if (value.length() == 0 || value.equalsIgnoreCase("false")){
//no mock
result = this.invoker.invoke(invocation);
} else if (value.startsWith("force")) {
if (logger.isWarnEnabled()) {
logger.info("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
}
//force:direct mock
result = doMockInvoke(invocation, null);
} else {
//fail-mock
try {
result = this.invoker.invoke(invocation);
}catch (RpcException e) {
if (e.isBiz()) {
throw e;
} else {
if (logger.isWarnEnabled()) {
logger.info("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
}
result = doMockInvoke(invocation, e);
}
}
}
return result;
}
public Object create(Request req, Response res) throws JsonProcessingException {
Map<String, String> headerMap = new HashMap<String, String>();
for (String each : req.getHeaderNames()) {
headerMap.put(each, req.getHeader(each));
}
String serviceName = headerMap.remove(RestExpressProtocol.SERVICE_KEY);
String methodName = headerMap.remove(RestExpressProtocol.METHOD_KEY);
InvokerBean<?> invokerBean = SERVICE_MAPPING.get(serviceName);
Result dubboResult = invokerBean.invoke(methodName, req, headerMap);
if (dubboResult.hasException()) {
return MAPPER.writeValueAsString(dubboResult.getException());
}
return MAPPER.writeValueAsString(dubboResult.getValue());
}
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers,
LoadBalance loadbalance) throws RpcException {
Invoker<T> invoker = select(loadbalance, invocation, invokers, null);
selectedInvoker = invoker;
return null;
}
@Test
public void testMockInvokerFromOverride_Invoke_check_Boolean(){
URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
.addParameter("getBoolean2.mock","force:return true")
.addParameter("invoke_return_error", "true" );
Invoker<IHelloService> cluster = getClusterInvoker(url);
//方法配置了mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean2");
Result ret = cluster.invoke(invocation);
Assert.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString()));
}
public Result invoke(String methodName, Request req, Map<String, String> attachments) {
Object[] arguments = new Object[1];
Class<?>[] argumentsClass = METHOD_MAPPING.get(methodName);
if (argumentsClass.length > 0)
arguments[0] = req.getBodyAs(argumentsClass[0]);
return invoker
.invoke(new RpcInvocation(methodName, METHOD_MAPPING.get(methodName), arguments, attachments, null));
}
public void handleReceive(Result rpcResult, Span span) {
if (span.isNoop()) return;
Tracer.SpanInScope ws = tracer.withSpanInScope(span);
try {
parser.response(adapter, rpcResult, span);
} finally {
ws.close();
span.finish();
}
}
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
long start = System.currentTimeMillis();
Result result = invoker.invoke(invocation);
long elapsed = System.currentTimeMillis() - start;
if (invoker.getUrl() != null
&& elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(),
"timeout", Integer.MAX_VALUE)) {
if (logger.isWarnEnabled()) {
logger.warn("invoke time out. method: " + invocation.getMethodName()
+ "arguments: " + Arrays.toString(invocation.getArguments()) + " , url is "
+ invoker.getUrl() + ", invoke elapsed " + elapsed + " ms.");
}
}
return result;
}
/**
* Test if mock policy works fine: fail-mock
*/
@Test
public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter("mock", "fail")
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
//Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Result ret = cluster.invoke(invocation);
Assert.assertEquals("somethingmock", ret.getValue());
}
@Test
public void testMockInvokerFromOverride_Invoke_check_boolean(){
URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
.addParameter("getBoolean1.mock","force:return true")
.addParameter("invoke_return_error", "true" );
Invoker<IHelloService> cluster = getClusterInvoker(url);
//方法配置了mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean1");
Result ret = cluster.invoke(invocation);
Assert.assertTrue("result type must be Boolean but was : " + ret.getValue().getClass(), ret.getValue() instanceof Boolean);
Assert.assertEquals(true, Boolean.parseBoolean(ret.getValue().toString()));
}
@SuppressWarnings("unchecked")
@Test
public void testMockInvokerFromOverride_Invoke_check_ListPojo_empty(){
URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
.addParameter("getUsers.mock","force:return empty")
.addParameter("invoke_return_error", "true" );
Invoker<IHelloService> cluster = getClusterInvoker(url);
//方法配置了mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getUsers");
Result ret = cluster.invoke(invocation);
Assert.assertEquals(0, ((List<User>)ret.getValue()).size());
}