|
| 1 | +package io.kimmking.rpcfx.server; |
| 2 | + |
| 3 | +import com.alibaba.fastjson.JSON; |
| 4 | +import com.alibaba.fastjson.serializer.SerializerFeature; |
| 5 | +import io.kimmking.rpcfx.api.RpcfxRequest; |
| 6 | +import io.kimmking.rpcfx.api.RpcfxResolver; |
| 7 | +import io.kimmking.rpcfx.api.RpcfxResponse; |
| 8 | + |
| 9 | +import java.lang.reflect.InvocationTargetException; |
| 10 | +import java.lang.reflect.Method; |
| 11 | +import java.util.Arrays; |
| 12 | + |
| 13 | +public class RpcfxInvoker { |
| 14 | + |
| 15 | + private RpcfxResolver resolver; |
| 16 | + |
| 17 | + public RpcfxInvoker(RpcfxResolver resolver){ |
| 18 | + this.resolver = resolver; |
| 19 | + } |
| 20 | + |
| 21 | + public RpcfxResponse invoke(RpcfxRequest request) { |
| 22 | + RpcfxResponse response = new RpcfxResponse(); |
| 23 | + String serviceClass = request.getServiceClass(); |
| 24 | + |
| 25 | + // 作业1:改成泛型和反射 |
| 26 | + Object service = resolver.resolve(serviceClass);//this.applicationContext.getBean(serviceClass); |
| 27 | + |
| 28 | + try { |
| 29 | + Method method = resolveMethodFromClass(service.getClass(), request.getMethod()); |
| 30 | + Object result = method.invoke(service, request.getParams()); // dubbo, fastjson, |
| 31 | + // 两次json序列化能否合并成一个 |
| 32 | + response.setResult(JSON.toJSONString(result, SerializerFeature.WriteClassName)); |
| 33 | + response.setStatus(true); |
| 34 | + return response; |
| 35 | + } catch ( IllegalAccessException | InvocationTargetException e) { |
| 36 | + |
| 37 | + // 3.Xstream |
| 38 | + |
| 39 | + // 2.封装一个统一的RpcfxException |
| 40 | + // 客户端也需要判断异常 |
| 41 | + e.printStackTrace(); |
| 42 | + response.setException(e); |
| 43 | + response.setStatus(false); |
| 44 | + return response; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + private Method resolveMethodFromClass(Class<?> klass, String methodName) { |
| 49 | + return Arrays.stream(klass.getMethods()).filter(m -> methodName.equals(m.getName())).findFirst().get(); |
| 50 | + } |
| 51 | + |
| 52 | +} |
0 commit comments