如何从mongoDB中读取文档并通过java中的websockets发送文档?

时间:2017-08-29 11:24:42

标签: java mongodb websocket

我是java的新手,想要从mongoDB集合中读取随机数据,并通过websockets将其发送到一个简单的websocket客户端。实际上我运行了一个tomcat来部署我的java应用程序(websocketserver)。它是一个简单的websocket echo服务器,它回复来自客户端的消息。

      package websocket.chat;


        import com.mongodb.MongoClient;
        import javax.websocket.*;
        import javax.websocket.server.*;
        import java.io.IOException;


        @ServerEndpoint(value="/echo")
        public class EchoEndpoint {

            MongoAccess mongo;


            @OnOpen
            public void onOpen(Session session, EndpointConfig config) throws IOException {
               System.out.println("open");
    mongo = new MongoAccess(new MongoClient("localhost",27017));



   session.getBasicRemote().sendText(mongo.readNumberOfDocuments(10).toString());



            }

            @OnMessage
            public String echo(String message) {

                System.out.println("Server answer");
                return message + " (from your server)";

            }

            @OnError
            public void onError(Throwable t) {

                System.out.println("Error!!!");
                t.printStackTrace();
            }

            @OnClose
            public void onClose(Session session) {



                System.out.println("close");

            }
        }

现在我想在OnMessage事件中发送来自mongoDB的数据。为此,我创建了三个类。

Class Nr.1从集合中读取数据

package websocket.chat;


import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.net.UnknownHostException;


import java.util.ArrayList;
import java.util.List;

public class MongoAccess {


    private DBCollection collection;



    //Konstruktor
    public MongoAccess(MongoClient mongo)
    {
        this.collection = mongo.getDB("randomData").getCollection("random");
    }


    //read all datasets
    public List<Dataset> readAllDocuments(){

        List<Dataset> data = new ArrayList<Dataset>();

        //Cursor object to iterate over set of documents
        DBCursor cursor = collection.find();

            while(cursor.hasNext()){
                System.out.println(cursor.next());
                DBObject doc = cursor.next();
                Dataset d = DataConverter.convertDBobject(doc);
                data.add(d);

            }
        return data;

    }


    //read a number of datasets
    public List<Dataset> readNumberOfDocuments(int number) {


        //query, less then equal number
        BasicDBObject query = new BasicDBObject(("data_id"), new BasicDBObject("$lte", number));

        //Cursor object to iterate over set of documents that matched our query
        DBCursor cursor = collection.find(query);

        List<Dataset> data = new ArrayList<Dataset>();


            while (cursor.hasNext()) {
                System.out.println(cursor.next());
                DBObject doc = cursor.next();
                Dataset d = DataConverter.convertDBobject(doc);
                data.add(d);
            }

        return data;

    }

}

Class Nr.2:数据对象

 package websocket.chat;


public class Dataset {

    private Integer data_id;
    private Float X;
    private Float Y;
    private Float Z;

    public Integer getData_id() {
        return data_id;
    }

    public void setData_id(Integer data_id) {
        this.data_id = data_id;
    }

    public Float getX() {
        return X;
    }

    public void setX(Float x) {
        X = x;
    }

    public Float getY() {
        return Y;
    }

    public void setY(Float y) {
        Y = y;
    }

    public Float getZ() {
        return Z;
    }

    public void setZ(Float z) {
        Z = z;
    }


}

Class Nr.3:转换DBObject

import com.mongodb.BasicDBObjectBuilder;



public class DataConverter {

    //convert DBObject to Dataset Object
    public static Dataset convertDBobject(DBObject doc)
    {
        Dataset d = new Dataset();
        d.setData_id((int)doc.get("data_id"));
        d.setX((float)doc.get("x"));
        d.setY((float)doc.get("y"));
        d.setZ((float)doc.get("z"));
        return d;

    }

}

当我尝试连接到websocket服务器时,websocket连接抛出了这个错误:

    java.lang.NoClassDefFoundError: com/mongodb/DBObject
    at websocket.chat.EchoEndpoint.onOpen(EchoEndpoint.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.websocket.pojo.PojoEndpointBase.doOnOpen(PojoEndpointBase.java:65)
    at org.apache.tomcat.websocket.pojo.PojoEndpointServer.onOpen(PojoEndpointServer.java:64)
    at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.init(WsHttpUpgradeHandler.java:133)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:844)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.mongodb.DBObject
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
    ... 15 more

我试图找到错误,但我没有做过什么。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我发现了我的错误。我使用tomcat来部署应用程序。所以我忘了将mongo-java-driver.jar添加到tomcat lib文件夹中。因此,tomcat服务器在运行时间内无法找到类。