如何编程处理来自不同客户端的多个同时请求?

时间:2017-01-16 07:25:55

标签: java servlets cassandra

public class CassandraData {

    private static Session cassandraSession = null;
    private static Cluster cluster = null;

    CassandraData() {
        // Do nothing
    }

    static {

        if (cassandraSession == null) {
            QueryOptions qs = new QueryOptions().setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);

            PoolingOptions poolingOptions = new PoolingOptions();
            poolingOptions.setConnectionsPerHost(HostDistance.LOCAL, 2, 10).setConnectionsPerHost(HostDistance.REMOTE,
                    10, 20);

            SocketOptions socketOptions = new SocketOptions();
            socketOptions.setConnectTimeoutMillis(60000);
            socketOptions.setReadTimeoutMillis(600000);

            cluster = Cluster.builder().addContactPoints("***.***.***.***").withQueryOptions(qs)
                    .withPoolingOptions(poolingOptions).withSocketOptions(socketOptions)
                    .withLoadBalancingPolicy(new RoundRobinPolicy()).build();

            cassandraSession = cluster.connect("sf");
        }
        // monitor();
    }

    public Session getSession() {

        return cassandraSession;

    }
    public Data findOne(PK pk) {

        Data mc = null;

        Statement statement = new SimpleStatement(getCqlString(pk));

        ResultSet results = getSession().execute(statement);


        List<Row> rowList = results.all();

        if (rowList != null && rowList.size() > 0) {
            Row row = rowList.get(0);
            mc = EntityConvert.ConvertToMC(row);
        }

        return mc;
    }
}
    private String getCqlString(PK pk) {
    String cqlStr = "select * from table" + " where E='"
            + pk.E + "' and D=" + pk.D + " and M="
            + pk.M;
    return cqlStr;
}

的Servlet

public class OneServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = LogManager.getLogger(OneServlet.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OneServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        long start = System.currentTimeMillis();

        PK pk = ValidData.getOnePk();

        CassandraData dataAccess = new CassandraData();
        long end2 = System.currentTimeMillis();
        Data mc = dataAccess.findOne(pk);

        String rsJson = JSON.toJSONString(mc);
        long end = System.currentTimeMillis();

        logger.info("Create CassandraData:" + (end2 - start)/1000.0 +"s elapsed." + "Show One:" + (end - start)/1000.0 +"s elapsed.");

        OutputStream out = response.getOutputStream();
        out.write(rsJson.getBytes("UTF-8"));
        out.flush();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

在我的Servlet应用程序中,我想使用上面的代码来访问cassandra。 当用户访问Servlet时,获取数据平均需要0.1秒。 当多个用户(如60)访问Servlet时,每个请求平均需要20秒才能获取数据 由于有多个用户,我应该如何修改此代码以减少请求时间?

1 个答案:

答案 0 :(得分:0)

private Select getCqlSelect(PK pk) {

    Select select = QueryBuilder.select().from("table");
    select.where(QueryBuilder.eq("E", pk.E))
            .and(QueryBuilder.eq("D", pk.D))
            .and(QueryBuilder.eq("M", pk.M)).limit(1)

    return select;
}

我使用了Prepared语句并将性能提高了20多倍。

  

Prepared statements

     

使用预准备语句可提供多种好处。准备好的语句在Cassandra节点上进行解析和准备,从而为将来的执行做好准备。绑定参数时,只通过线路发送这些(和查询ID)。当重复使用相同的查询(具有不同的参数)时,这些性能提升将会增加。

     

请记住使用预准备语句的规则很简单:准备一次,绑定并执行多次。