0


JAVA反射机制实现调用类的方法

NmsMonitorDrillController

package com.nrxt.nms.mon.ms.controller;

import com.nrxt.nms.mon.ms.service.impl.NmsMonitorDrillService;
import com.nrxt.nms.mon.ms.utils.ByteArrayUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping(value = "/monitor/interface")
public class NmsMonitorDrillController {

    @Resource
    NmsMonitorDrillService nmsMonitorDrillService;

    private static final Logger logger = Logger.getLogger(NmsMonitorDrillController.class);

    @ResponseBody
    @RequestMapping(value = "/queryByDrillReceive", method = RequestMethod.POST)
    public byte[] queryByDrillReceive(HttpServletRequest request, HttpServletResponse response) {
        String param;
        try {
            param = ByteArrayUtil.inputStreamToObject(request.getInputStream(), logger).toString();
            if (param == null) {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        String responseStr = nmsMonitorDrillService.queryByDrillReceive(param);
        return ByteArrayUtil.objectToByteArray(responseStr, logger);
    }

    
    @ResponseBody
    @RequestMapping(value = "/queryByDrillSend", method = RequestMethod.POST)
    public String queryByDrillSend(HttpServletRequest request, @RequestBody String param) {
        return nmsMonitorDrillService.queryByDrillSend(param);
    }
}

NmsMonitorDrillService

package com.nrxt.nms.mon.ms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nrxt.nms.mon.ms.dao.NmsAppConfDao;
import com.nrxt.nms.mon.ms.utils.ByteArrayUtil;
import com.nrxt.nms.mon.ms.utils.DrillUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Service
public class NmsMonitorDrillService {
    @Resource
    NmsAppConfDao nmsAppConfDao;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ApplicationContext applicationContext;

    private static final Logger logger = Logger.getLogger(NmsMonitorDrillService.class);

    public String queryByDrillSend(String param) {
        JSONObject requestParam = JSONObject.parseObject(param);
        JSONObject requestHead = requestParam.getJSONObject("head");
        String bgId = requestHead.getString("bgId");
        if (StringUtils.isEmpty(bgId)) {
            return "bgId can not be null";
        }
        String corpCode = requestHead.getString("corpCode");
        if (StringUtils.isEmpty(corpCode)) {
            return "corpCode can not be null";
        }
        String drillUrl = "http://127.0.0.1:30098/monitor/interface/queryByDrillReceive";
        drillUrl = nmsAppConfDao.queryBgPathByBgCode(corpCode);

        byte[] compressedDatas = ByteArrayUtil.objectToByteArray(param, logger);

        String uploadResult = DrillUtils.tryUpload(compressedDatas, drillUrl,restTemplate ,logger).toString();

        return uploadResult;
    }

    public String queryByDrillReceive(String param){
        JSONObject requestParam = JSONObject.parseObject(param);
        JSONObject requestHead = requestParam.getJSONObject("head");

        String result = null;
        // 获取类的全路径以及名称
        String className = requestHead.get("className").toString();
        if(!className.contains(".")){
            className = "com.nrxt.nms.mon.ms.controller." + className;
        }
        // 获取方法名
        String functionName = requestHead.get("functionName").toString();
        try {
            Object classBean = applicationContext.getBean(Class.forName(className));
            // 获取class文件
            Class<?> clazz = classBean.getClass();
            // 获取该类所需求的方法
            Method method = clazz.getMethod(functionName, HttpServletResponse.class,String.class);

            result = method.invoke(classBean,null,param).toString();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return result;
    }
}

DrillUtils

package com.nrxt.nms.mon.ms.utils;

import com.xxl.job.core.log.XxlJobLogger;
import org.apache.log4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class DrillUtils {
    public static Object tryUpload(byte[] compressedDatas, String url, RestTemplate restTemplate, Logger logger) {
        Object result = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Content-Encoding", "gzip");
        headers.add("Accept", "application/json");
        HttpEntity<byte[]> entity = new HttpEntity(compressedDatas, headers);

        ResponseEntity<byte[]> exchange;
        for (int i = 0; i < 3; i++) {//重连3次
            exchange = postByteMsg(url, restTemplate,entity);
            if (exchange != null) {
                byte[] returnResult = exchange.getBody();
                if (returnResult != null) {
                    return com.nrxt.nms.mon.ms.utils.ByteArrayUtil.byteArrayToObject(exchange.getBody(), logger);
                }
                break;
            } else {
                XxlJobLogger.log("尝试第" + (i + 1) + "次发送");
            }
        }
        return result;
    }

    private static ResponseEntity<byte[]> postByteMsg(String url, RestTemplate restTemplate, HttpEntity<byte[]> entity) {
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, byte[].class);
        } catch (Exception e) {
            XxlJobLogger.log("发送错误:");
            XxlJobLogger.log(e);
            return null;
        }
    }
}

ByteArrayUtil

package com.nrxt.nms.mon.ms.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import javax.servlet.ServletInputStream;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class ByteArrayUtil {

    /**
     * Object转为byte[]
     * 
     * @param obj
     * @return
     * @throws IOException
     */
    public static byte[] objectToByteArray(Object obj, Logger logger) {
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        GZIPOutputStream gzipOutputStream = null;
        ObjectOutputStream objectOutputSream = null;
        byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            objectOutputSream = new ObjectOutputStream(gzipOutputStream);
            objectOutputSream.writeObject(obj);
            objectOutputSream.flush();
            objectOutputSream.close();
            objectOutputSream = null;
            gzipOutputStream.close();
            gzipOutputStream = null;
            bytes = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            byteArrayOutputStream = null;
        } catch (IOException e) {
            e.printStackTrace();
            if (logger != null)
                logger.error("消息序列化+压缩失败", e);
        } finally {
            if (objectOutputSream != null) {
                try {
                    objectOutputSream.close();
                } catch (IOException e) {

                }
            }
            if (gzipOutputStream != null) {
                try {
                    gzipOutputStream.close();
                } catch (IOException e) {

                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {

                }
            }
        }
        return bytes;
    }

    /**
     * byte[]转为Object
     * 
     * @param bytes
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object byteArrayToObject(byte[] bytes, Logger logger) {
        Object obj = null;
        ByteArrayInputStream inputStream = null;
        GZIPInputStream gzin = null;
        ObjectInputStream objInt = null;
        try {
            inputStream = new ByteArrayInputStream(bytes);
            gzin = new GZIPInputStream(inputStream);
            objInt = new ObjectInputStream(gzin);
            obj = objInt.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            if (logger != null)
                logger.error("消息解压缩+反序列化失败", e);
        } finally {
            if (objInt != null)
                try {
                    objInt.close();
                } catch (IOException e) {

                }
            if (gzin != null)
                try {
                    gzin.close();
                } catch (IOException e) {

                }
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {

                }
        }
        return obj;
    }

    public static Object inputStreamToObject(ServletInputStream inputStream, Logger logger) {
        Object obj = null;
        GZIPInputStream gzin = null;
        ObjectInputStream objInt = null;
        try {
            gzin = new GZIPInputStream(inputStream);
            objInt = new ObjectInputStream(gzin);
            obj = objInt.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            if (logger != null)
                logger.error("消息解压缩+反序列化失败", e);
        } finally {
            if (objInt != null)
                try {
                    objInt.close();
                } catch (IOException e) {

                }
            if (gzin != null)
                try {
                    gzin.close();
                } catch (IOException e) {

                }
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {

                }
        }
        return obj;
    }
}
标签: java 开发语言

本文转载自: https://blog.csdn.net/qq_41482600/article/details/134328045
版权归原作者 qq_41482600 所有, 如有侵权,请联系我们删除。

“JAVA反射机制实现调用类的方法”的评论:

还没有评论