dubbo项目中,需要定义一个dubboService注解完成类的调用
@DubboService(group = "net-hospital", version = "1.0.0", interfaceClass = ReflectionService.class)
如果每个需要调用的类都要定义的话显得很复杂,很麻烦
优化方式,一个service服务只需要定义一个反射类,所有的接口请求都通过这个反射类的dubbo serive来通过反射的方式调用到service的各个方法中
先定义一个反射配置类,包括需要调用的bean名称,方法名称跟方法参数
public class ReflectConfig implements Serializable { private static final long serialVersionUID = -5658969389322144625L; private String beanName; private String methodName; private List<Object> params = new ArrayList(); public ReflectConfig() { } public ReflectConfig(String beanName, String methodName) { this.beanName = beanName; this.methodName = methodName; } public ReflectConfig(String beanName, String methodName, List<Object> params) { this.beanName = beanName; this.methodName = methodName; this.params.addAll(params); } public String getBeanName() { return this.beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getMethodName() { return this.methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public List<Object> getParams() { return this.params; } public void setParam(Object param) { this.params.add(param); } public void setParams(List<Object> params) { this.params = params; } }
然后再定义一个反射调用类执行反射操作
public static Object excutor(ReflectConfig config) throws Exception { logger.info("反射调用服务信息:{}", JSON.toJSONString(config)); Object obj = SpringUtil.getBean(config.getBeanName()); Object result = ReflectUtil.invokeMethod(obj, config.getMethodName(), config.getParams().toArray(new Object[0])); if (isPrintResponse.equals("1")) { logger.info("反射调用结束返回:{}", JSON.toJSONString(result)); } else { logger.info("isPrintResponse:" + isPrintResponse + ",数据已返回,请自行打印返回值!!!"); } return result; }
最后在配置dubboservice的类中执行通过反射器调用需要执行的方法
ReflectContext.excutor(config)