从DUBBO的2.7.22版本升级到了3.x的版本后,发现invoke失灵了
首先是启动报错,注释掉配置 dubbo.protocol.telnet=invoke后程序可运行,但是invoke失效。
通过对比源码
示例:
tag-3.0.10
tag-2.7.22
发现3.0.2之后的版本都移除了invoke指令。
那么问题就很简单了,把这部分拿回来就好了!!
此时参考下面文章和源码
Dubbo3 Telnet 命令扩展_w3cschool
添加如下内容
首先在 resource/META-INF下添加文件
文件名称:org.apache.dubbo.remoting.telnet.TelnetHandler
我的目录是
填充内容
# xxx替换为任意包路径
invoke=xxx.InvokeTelnetHandler
在xxx目录(和上面的包路径保持一致)下添加如下两个类
InvokeTelnetHandler
package xxx;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.legacy.ChangeTelnetHandler;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.utils.PojoUtils.realize;
/**
* InvokeTelnetHandler
*/
@Activate
@Help(parameter = "[service.]method(args) ", summary = "Invoke the service method.",
detail = "Invoke the service method.")
public class InvokeTelnetHandler implements TelnetHandler {
public static final String INVOKE_MESSAGE_KEY = "telnet.invoke.method.message";
public static final String INVOKE_METHOD_LIST_KEY = "telnet.invoke.method.list";
public static final String INVOKE_METHOD_PROVIDER_KEY = "telnet.invoke.method.provider";
@Override
@SuppressWarnings("unchecked")
public String telnet(Channel channel, String message) {
if (StringUtils.isEmpty(message)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" +
"invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" +
"invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})";
}
String service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY);
int i = message.indexOf("(");
if (i < 0 || !message.endsWith(")")) {
return "Invalid parameters, format: service.method(args)";
}
String method = message.substring(0, i).trim();
String args = message.substring(i + 1, message.length() - 1).trim();
i = method.lastIndexOf(".");
if (i >= 0) {
service = method.substring(0, i).trim();
method = method.substring(i + 1).trim();
}
List<Object> list;
try {
list = JsonUtils.getJson().toJavaList("[" + args + "]", Object.class);
} catch (Throwable t) {
return "Invalid json argument, cause: " + t.getMessage();
}
StringBuilder buf = new StringBuilder();
Method invokeMethod = null;
ProviderModel selectedProvider = null;
if (isInvokedSelectCommand(channel)) {
selectedProvider = (ProviderModel) channel.getAttribute(INVOKE_METHOD_PROVIDER_KEY);
invokeMethod = (Method) channel.getAttribute(SelectTelnetHandler.SELECT_METHOD_KEY);
} else {
for (ProviderModel provider : ApplicationModel.allProviderModels()) {
if (!isServiceMatch(service, provider)) {
continue;
}
selectedProvider = provider;
List<Method> methodList = findSameSignatureMethod(provider.getAllMethods(), method, list);
if (CollectionUtils.isEmpty(methodList)) {
break;
}
if (methodList.size() == 1) {
invokeMethod = methodList.get(0);
} else {
List<Method> matchMethods = findMatchMethods(methodList, list);
if (CollectionUtils.isEmpty(matchMethods)) {
break;
}
if (matchMethods.size() == 1) {
invokeMethod = matchMethods.get(0);
} else { //exist overridden method
channel.setAttribute(INVOKE_METHOD_PROVIDER_KEY, provider);
channel.setAttribute(INVOKE_METHOD_LIST_KEY, matchMethods);
channel.setAttribute(INVOKE_MESSAGE_KEY, message);
printSelectMessage(buf, matchMethods);
return buf.toString();
}
}
break;
}
}
if (!StringUtils.isEmpty(service)) {
buf.append("Use default service ").append(service).append(".");
}
if (selectedProvider == null) {
buf.append("\r\nNo such service ").append(service);
return buf.toString();
}
if (invokeMethod == null) {
buf.append("\r\nNo such method ").append(method).append(" in service ").append(service);
return buf.toString();
}
try {
Object[] array = realize(list.toArray(), invokeMethod.getParameterTypes(),
invokeMethod.getGenericParameterTypes());
long start = System.currentTimeMillis();
AppResponse result = new AppResponse();
try {
Object o = invokeMethod.invoke(selectedProvider.getServiceInstance(), array);
result.setValue(o);
} catch (Throwable t) {
result.setException(t);
}
long end = System.currentTimeMillis();
buf.append("\r\nresult: ");
buf.append(JsonUtils.getJson().toJson(result.recreate()));
buf.append("\r\nelapsed: ");
buf.append(end - start);
buf.append(" ms.");
} catch (Throwable t) {
return "Failed to invoke method " + invokeMethod.getName() + ", cause: " + StringUtils.toString(t);
}
return buf.toString();
}
private boolean isServiceMatch(String service, ProviderModel provider) {
return provider.getServiceKey().equalsIgnoreCase(service)
|| provider.getServiceInterfaceClass().getSimpleName().equalsIgnoreCase(service)
|| provider.getServiceInterfaceClass().getName().equalsIgnoreCase(service)
|| StringUtils.isEmpty(service);
}
private List<Method> findSameSignatureMethod(Set<MethodDescriptor> methods, String lookupMethodName, List<Object> args) {
List<Method> sameSignatureMethods = new ArrayList<>();
for (MethodDescriptor model : methods) {
Method method = model.getMethod();
if (method.getName().equals(lookupMethodName) && method.getParameterTypes().length == args.size()) {
sameSignatureMethods.add(method);
}
}
return sameSignatureMethods;
}
private List<Method> findMatchMethods(List<Method> methods, List<Object> args) {
List<Method> matchMethod = new ArrayList<>();
for (Method method : methods) {
if (isMatch(method, args)) {
matchMethod.add(method);
}
}
return matchMethod;
}
private static boolean isMatch(Method method, List<Object> args) {
Class<?>[] types = method.getParameterTypes();
if (types.length != args.size()) {
return false;
}
for (int i = 0; i < types.length; i++) {
Class<?> type = types[i];
Object arg = args.get(i);
if (arg == null) {
if (type.isPrimitive()) {
return false;
}
// if the type is not primitive, we choose to believe what the invoker want is a null value
continue;
}
if (ReflectUtils.isPrimitive(arg.getClass())) {
// allow string arg to enum type, @see PojoUtils.realize0()
if (arg instanceof String && type.isEnum()) {
continue;
}
if (!ReflectUtils.isPrimitive(type)) {
return false;
}
if (!ReflectUtils.isCompatible(type, arg)) {
return false;
}
} else if (arg instanceof Map) {
String name = (String) ((Map<?, ?>) arg).get("class");
if (StringUtils.isNotEmpty(name)) {
Class<?> cls = ReflectUtils.forName(name);
if (!type.isAssignableFrom(cls)) {
return false;
}
} else {
return true;
}
} else if (arg instanceof Collection) {
if (!type.isArray() && !type.isAssignableFrom(arg.getClass())) {
return false;
}
} else {
if (!type.isAssignableFrom(arg.getClass())) {
return false;
}
}
}
return true;
}
private void printSelectMessage(StringBuilder buf, List<Method> methods) {
buf.append("Methods:\r\n");
for (int i = 0; i < methods.size(); i++) {
Method method = methods.get(i);
buf.append(i + 1).append(". ").append(method.getName()).append("(");
Class<?>[] parameterTypes = method.getParameterTypes();
for (int n = 0; n < parameterTypes.length; n++) {
buf.append(parameterTypes[n].getSimpleName());
if (n != parameterTypes.length - 1) {
buf.append(",");
}
}
buf.append(")\r\n");
}
buf.append("Please use the select command to select the method you want to invoke. eg: select 1");
}
private boolean isInvokedSelectCommand(Channel channel) {
if (channel.hasAttribute(SelectTelnetHandler.SELECT_KEY)) {
channel.removeAttribute(SelectTelnetHandler.SELECT_KEY);
return true;
}
return false;
}
}
SelectTelnetHandler
package xxx;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
import java.lang.reflect.Method;
import java.util.List;
/**
* SelectTelnetHandler
*/
@Activate
@Help(parameter = "[index]", summary = "Select the index of the method you want to invoke.",
detail = "Select the index of the method you want to invoke.")
public class SelectTelnetHandler implements TelnetHandler {
public static final String SELECT_METHOD_KEY = "telnet.select.method";
public static final String SELECT_KEY = "telnet.select";
private InvokeTelnetHandler invokeTelnetHandler = new InvokeTelnetHandler();
@Override
@SuppressWarnings("unchecked")
public String telnet(Channel channel, String message) {
if (message == null || message.length() == 0) {
return "Please input the index of the method you want to invoke, eg: \r\n select 1";
}
List<Method> methodList = (List<Method>) channel.getAttribute(InvokeTelnetHandler.INVOKE_METHOD_LIST_KEY);
if (CollectionUtils.isEmpty(methodList)) {
return "Please use the invoke command first.";
}
if (!StringUtils.isNumber(message) || Integer.parseInt(message) < 1 || Integer.parseInt(message) > methodList.size()) {
return "Illegal index ,please input select 1~" + methodList.size();
}
Method method = methodList.get(Integer.parseInt(message) - 1);
channel.setAttribute(SELECT_METHOD_KEY, method);
channel.setAttribute(SELECT_KEY, Boolean.TRUE);
String invokeMessage = (String) channel.getAttribute(InvokeTelnetHandler.INVOKE_MESSAGE_KEY);
return invokeTelnetHandler.telnet(channel, invokeMessage);
}
}
此时在启动,测试 telnet 下invoke调用就可以啦!
( 这两个类是我基于3.0.1的版本和我的版本做过适配的,如果有报错请自行解决。)