Cassandra,Jersey rest api会根据每个休息请求增加线程,内存使用和端口

时间:2017-01-27 05:50:51

标签: java rest cassandra jersey

我已经创建了简单的泽西休息api来查询cassandra。 Ajax Long轮询也被使用。但是,即使请求完成后,每个请求内存,端口使用和线程都会增加,但这些内存不会减少。也关闭了cassandra会议,但没有运气。以下是其余代码

@Path("/pull")
@GET
@Produces(MediaType.APPLICATION_JSON)
public JSONArray get(@QueryParam("offset") String offset, @QueryParam("currentUser") String currentUser,
        @QueryParam("longPolling") boolean longPolling) {
    JSONArray messages = new JSONArray();
    JSONObject message = null;
    Session session = Connector.getSession();
    String query = "SELECT * FROM messages";
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    BoundStatement stmt = null;
    int timeOut = 0;
    try {
        while (messages.length() == 0 && timeOut++ < 30) {
            if (longPolling && !offset.equals("0")) {
                query = "SELECT * FROM messages WHERE id > ? ALLOW FILTERING";
                ps = session.prepare(query);
                stmt = ps.bind(UUID.fromString(offset));
                resultSet = session.execute(stmt);
            } else {
                resultSet = session.execute(query);
            }
            List<Row> ls = resultSet.all();
            ls.sort(new Sort<Row>());
            for (Row row : ls) {
                if ((!longPolling || !row.getString("sentby").equals(currentUser))) {
                    message = new JSONObject();
                    message.put("id", row.getUUID("id"));
                    message.put("sentby", row.getString("sentby"));
                    message.put("message", row.getString("message"));
                    messages.put(message);
                }
            }
            if (messages.length() == 0 && longPolling) {
                Thread.sleep(1000);
            }
        }
    } catch (JSONException | InterruptedException e) {
        e.printStackTrace();
    } finally {
        message = null;
        resultSet = null;
        session.close();
    }
    return messages;
}

1 个答案:

答案 0 :(得分:2)

我认为主要的问题是你每次都要初始化会话并将其删除。 Session是一个相对繁重的对象,每个应用程序只应使用一个。请将会话放到其他bean中,然后在代码中使用依赖注入来获取它。不要按要求打开和关闭会话。这肯定不会有效。

每次都不要准备陈述。在你的这个bean上只创建一个预准备语句并在请求中使用它。