如何在一次请求中访问多个接口(方法)并获取多个返回值

假如要访问同一个类的不同方法,或者不同类的方法,并且要同时获取返回值。可以JSON格式的参数,以及组装多个结果返回值为JSON格式。例如:

package com.river.web.function.smartrequst.serivce.impl;

import com.river.web.function.smartrequst.model.User;
import com.river.web.function.smartrequst.serivce.UserSerivce;
import org.springframework.stereotype.Service;

/**
 * @Author river66
 * @Date 2021/1/1 21:25
 */
@Service
public class UserServiceImpl implements UserSerivce {

    @Override
    public User getUserByName(String userName) {
        if (null != userName && userName.equals("river")) {
            return new User("river66", "惠州市惠阳区");
        }
        return null;
    }

    @Override
    public String dealUserInfo(String userName, String password, Integer age) {
        return "delUserInfo(" + userName + ":" + password + ":" + age + ") success, return!";
    }
}

一起访问这两个方法并获取返回值一同返回,如入参为:

{
  "webClassList": [
    {
      "functionList": [
        {
          "functionName": "getUserByName",
          "functionParam": {
            "userName": "river"
          },
          "functionJSONResult": ""
        },
        {
          "functionName": "dealUserInfo",
          "functionParam": {
            "password": "xxxxxxxx",
            "userName": "river",
            "age": 25
          },
          "functionJSONResult": ""
        }
      ],
      "webClassName": "UserServiceImpl"
    },
    {
      "functionList": [
        {
          "functionName": "xxxxxx",
          "functionParam": {
            "name": "xxxxxx"
          }
        }
      ],
      "webClassName": "xxxxxx"
    }
  ]
}

返回结果为:

{
  "webClassList": [
    {
      "functionList": [
        {
          "functionName": "getUserByName",
          "functionParam": {
            "userName": "river"
          },
          "functionJSONResult": "{\"address\":\"惠州市惠阳区\",\"userName\":\"river66\"}"
        },
        {
          "functionName": "dealUserInfo",
          "functionParam": {
            "password": "xxxxxxxx",
            "userName": "river",
            "age": 25
          },
          "functionJSONResult": "\"delUserInfo(river:xxxxxxxx:25) success, return!\""
        }
      ],
      "webClassName": "UserServiceImpl"
    },
    {
      "functionList": [
        {
          "functionName": "xxxxxx",
          "functionParam": {
            "name": "xxxxxx"
          }
        }
      ],
      "webClassName": "xxxxxx"
    }
  ]
}

可以通过java反射机制,将functionParam参数用上,调用Method.invoke方法获取返回值,并组装结果即可。

package com.river.web.function.smartrequst.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.river.web.function.smartrequst.model.WebClass;
import com.river.web.function.smartrequst.model.WebFunction;
import com.river.web.function.smartrequst.model.WebParameter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;

/**
 * @Author river66
 * @Date 2021/1/1 21:40
 */
public class WebManager {
    public static  JSONObject getWebResult(T t, String webJSONParam) {
        WebParameter webParameter = JSONObject.parseObject(webJSONParam, WebParameter.class);
        if (null == webJSONParam) {
            return null;
        }
        List webClassList = webParameter.getWebClassList();
        if (null == webClassList || webClassList.size() == 0) {
            return null;
        }
        Class serviceClass = t.getClass();
        webClassList.forEach(webClass -> {
            String webClassName = webClass.getWebClassName();
            if (serviceClass.getSimpleName().equals(webClassName)) {
                List webFunctions = webClass.getFunctionList();
                if (null != webFunctions && 0 < webFunctions.size()) {
                    Method[] methods = serviceClass.getMethods();
                    webFunctions.forEach(webFunction -> {
                        String functionName = webFunction.getFunctionName();
                        JSONObject functionParam = webFunction.getFunctionParam();
                        if (functionParam != null) {
                            for (Method method : methods) {
                                if (functionName != null && functionName.equals(method.getName())) {
                                    Object result = invoke(t, method, functionParam);
                                    webFunction.setFunctionJSONResult(JSONObject.toJSONString(result));
                                }
                            }
                        }
                    });
                }
            }
        });
        return JSON.parseObject(JSONObject.toJSONString(webParameter));
    }

    private static  Object invoke(T t, Method method, JSONObject param) {
        try {
            return method.invoke(t, getParams(param, method.getParameters()));
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Object[] getParams(JSONObject param, Parameter[] parameters) {
        int size = parameters.length;
        Object[] paramObjects = new Object[size];
        for (int i = 0; i < size; i++) {
            paramObjects[i] = param.get(parameters[i].getName());
        }
        return paramObjects;
    }
}

对应的测试类如下:

package com.river.web.function.smartrequst;

import com.river.web.function.smartrequst.manager.WebManager;
import com.river.web.function.smartrequst.serivce.UserSerivce;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SmartrequstApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    UserSerivce userSerivce;

    @Test
    public void testRequest() {
        String param = "{\"webClassList\":[{\"functionList\":[{\"functionName\":\"getUserByName\",\"functionParam\":{\"userName\":\"river\"},\"functionJSONResult\":\"\"},{\"functionName\":\"dealUserInfo\",\"functionParam\":{\"password\":\"xxxxxxxx\",\"userName\":\"river\",\"age\":25},\"functionJSONResult\":\"\"}],\"webClassName\":\"UserServiceImpl\"},{\"functionList\":[{\"functionName\":\"xxxxxx\",\"functionParam\":{\"name\":\"xxxxxx\"}}],\"webClassName\":\"xxxxxx\"}]}";
        System.out.println(WebManager.getWebResult(userSerivce, param));
    }

}

运行结果如下:

如何在一次请求中访问多个接口(方法)并获取多个返回值_第1张图片

其余的代码如下:

package com.river.web.function.smartrequst.model;

/**
 * @Author river66
 * @Date 2021/1/1 21:23
 */
public class User {
    private String userName;
    private String address;

    public User() {

    }

    public User(String userName, String address) {
        this.userName = userName;
        this.address = address;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
package com.river.web.function.smartrequst.model;

import java.util.List;

/**
 * @Author river66
 * @Date 2021/1/1 16:08
 */
public class WebClass {
    private List functionList;
    private String webClassName;

    public String getWebClassName() {
        return webClassName;
    }

    public void setWebClassName(String webClassName) {
        this.webClassName = webClassName;
    }

    public List getFunctionList() {
        return functionList;
    }

    public void setFunctionList(List functionList) {
        this.functionList = functionList;
    }
}
package com.river.web.function.smartrequst.model;

import com.alibaba.fastjson.JSONObject;

/**
 * @Author river66
 * @Date 2021/1/1 16:29
 */
public class WebFunction {
    private String functionName;
    private JSONObject functionParam;
    private String functionJSONResult;

    public String getFunctionName() {
        return functionName;
    }

    public void setFunctionName(String functionName) {
        this.functionName = functionName;
    }

    public JSONObject getFunctionParam() {
        return functionParam;
    }

    public void setFunctionParam(JSONObject functionParam) {
        this.functionParam = functionParam;
    }

    public String getFunctionJSONResult() {
        return functionJSONResult;
    }

    public void setFunctionJSONResult(String functionJSONResult) {
        this.functionJSONResult = functionJSONResult;
    }
}
package com.river.web.function.smartrequst.model;

import java.util.List;

/**
 * @Author river66
 * @Date 2021/1/1 16:32
 */
public class WebParameter {
    private List webClassList;

    public List getWebClassList() {
        return webClassList;
    }

    public void setWebClassList(List webClassList) {
        this.webClassList = webClassList;
    }
}

代码写得比较粗糙,没写注释,有些地方需要说明一下的:

1、类名可以使用加密解密处理,防止暴露。

2、WebManager.getWebResult的参数应该是只传一个JSON格式字符串为入参的,泛型类入参只是示范作用,实际可以根据类名到Spring容器中取出对应的类,然后依次调用有需要被方法的类即可。

3、如果代码有遗漏或者需要代码的朋友,可以评论下,我再上传下GitHub哈。

你可能感兴趣的:(进阶篇,java)