压力测试JSON-RPC服务

/**
 * 压力测试JSON-RPC服务
 * 
 * @author zhiqiang.zhu
 * @version $Id: LoadRunnerRPCService.java, v 0.1 2011-6-9 下午08:43:11 zhiqiang.zhu Exp $
 */
public class LoadRunnerRPCService {

    /** logger */
    private static final Logger      logger     = Logger.getLogger(LoadRunnerRPCService.class);

    /** 端口号 */
    private static final int         PROT       = 9091;

    /** 最大线程数 */
    private static final int         NTHREADS   = 150;

    /** 线城池 */
    private static final Executor    threadPool = Executors.newFixedThreadPool(NTHREADS);

    /** 异步服务外部接口 */
    private TestXXXXServiceFacade testXXXXServiceFacade ;

    /**
     * Spring初始化方法,启动一个服务端口的守护进程并开启服务
     */
    public void init() {
        try {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        initServer();
                    } catch (Exception e) {
                        logger.error(e);
                        throw new RuntimeException(e);
                    }
                }
            }).start();

            if (logger.isInfoEnabled()) {
                logger.info("====================================");
                logger.info("异步服务接口压力测试服务启动成功!");
                logger.info("====================================");
            }

        } catch (Exception e) {
            logger.error("服务启动失败", e);
        }
    }

    /**
     * 初始化服务
     */
    private void initServer() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(PROT));
        } catch (Exception e) {
            logger.error("服务启动失败", e);
            throw new RuntimeException(e);
        }

        try {
            while (true) {
                final Socket socket = serverSocket.accept();
                threadPool.execute(new Runnable() {
                    public void run() {
                        PrintWriter pw = null;
                        InputStream is = null;
                        try {
                            if (logger.isInfoEnabled()) {
                                logger.info("接受到来自" + socket.getInetAddress().getHostAddress()
                                            + "的请求!");
                            }
                            process(socket);
                            is = socket.getInputStream();
                            pw = new PrintWriter(socket.getOutputStream());
                            pw.print("true\r\n");
                            pw.flush();
                        } catch (Exception e) {
                            logger.error("处理指定的任务时出现异常", e);
                            try {
                                if (socket != null) {
                                    pw = new PrintWriter(socket.getOutputStream());
                                    pw.print("false\r\n");
                                    pw.flush();
                                }
                            } catch (IOException e1) {
                                logger.error("处理指定的任务时出现异常", e);
                            }
                        } finally {
                            if (is != null) {
                                IOUtils.closeQuietly(is);
                            }
                            
                            if (pw != null) {
                                IOUtils.closeQuietly(pw);
                            }
                            
                            if(socket != null) {
                                try {
                                    socket.close();
                                } catch (IOException e) {
                                    logger.error("处理指定的任务时出现异常", e);
                                }
                            }
                        }
                    }
                });
            }
        } catch (Exception e) {
            logger.error("处理任务时出现异常", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Socket服务处理
     * 
     * @param socket      请求
     * @throws Exception  异常
     */
    private void process(Socket socket) throws Exception {
        ChargeEvent chargeEvent = resolveParam(socket.getInputStream());
        
        if(logger.isInfoEnabled()) {
            logger.info("JSON格式转换ChargeEvent,chargeEvent=" + chargeEvent);
        }
        
        testXXXXServiceFacade.async(chargeEvent);
    }

    /**
     * 解析参数
     * 
     * @param inputStream   Socket输入流
     * @return              
     * @throws Exception
     */
    private ChargeEvent resolveParam(InputStream inputStream) throws Exception {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int size = -1;
        while ((size = inputStream.read(buffer)) > -1) {
            bos.write(buffer, 0, size);
            String params = new String(bos.toByteArray());
            if (params.endsWith("}")) {
                break;
            }
        }

        String params = new String(bos.toByteArray());
        return splitJson(params);
    }

    /**
     * 解析JSON数据
     * 
     * @param params       JSON数据
     * @return             
     * @throws Exception
     */
    private ChargeEvent splitJson(String params) throws Exception {

        params = params.substring(1);
        params = params.substring(0, params.length() - 1);

        String properties = null;
        if (params.indexOf("[") != -1) {
            properties = params
                .substring(params.substring(0, params.indexOf("[")).lastIndexOf(",") + 1);
            params = params.substring(0, params.substring(0, params.indexOf("[")).lastIndexOf(","));
        }

        String[] arr = params.split(",");

        ChargeEvent chargeEvent = new ChargeEvent();
        for (String s : arr) {
            String[] values = s.split(":");
            values[0] = values[0].trim();
            values[1] = values[1].trim();
            String method = "get" + values[0].substring(0, 1).toUpperCase()
                            + values[0].substring(1);

            Method getMethod = ChargeEvent.class.getMethod(method, new Class[0]);
            Class<?> returnType = getMethod.getReturnType();

            Object value = getValue(values[1], returnType);
            method = "set" + values[0].substring(0, 1).toUpperCase() + values[0].substring(1);

            Method setMethod = ChargeEvent.class.getMethod(method, new Class[] { returnType });
            setMethod.invoke(chargeEvent, new Object[] { value });
        }

        if (properties != null) {
            Map<String, String> props = new HashMap<String, String>();
            properties = properties.substring(properties.indexOf("[") + 1);
            properties = properties.substring(0, properties.indexOf("]"));

            arr = properties.split(",");
            for (String s : arr) {
                String[] values = s.split(":");
                props.put(values[0].trim(), values[1].trim());
            }

            chargeEvent.setProperties(props);
        }

        return chargeEvent;
    }

    /**
     * 取得对应的数据
     * 
     * @param value String形式的值
     * @param clazz 值的类型
     * @return      真正的值
     */
    private Object getValue(String value, Class<?> clazz) {

        if (String.class.equals(clazz)) {
            return value;
        } else if (Money.class.equals(clazz)) {
            return new Money(value);
        } else if (BigDecimal.class.equals(clazz)) {
            return new BigDecimal(value);
        } else if (EventStatusEnum.class.equals(clazz)) {
            return EventStatusEnum.getEventStatusEnum(value);
        } else if (Date.class.equals(clazz)) {
            //yyyyMMddHHmmss
            return DateUtil.parseDateLongFormat(value);
        }

        return null;
    }

}

 

你可能感兴趣的:(json)