注意:该内容使用chatgpt实现,准确性待定,不过可以成为学习素材。
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedAbstractActor;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoDBActor extends UntypedAbstractActor {
private MongoClient mongoClient;
private MongoDatabase mongoDatabase;
private MongoCollection<Document> mongoCollection;
public MongoDBActor(String host, int port, String dbName, String collectionName) {
mongoClient = new MongoClient(host, port);
mongoDatabase = mongoClient.getDatabase(dbName);
mongoCollection = mongoDatabase.getCollection(collectionName);
}
public static Props props(String host, int port, String dbName, String collectionName) {
return Props.create(MongoDBActor.class, () -> new MongoDBActor(host, port, dbName, collectionName));
}
@Override
public void onReceive(Object message) throws Throwable {
if (message instanceof String) {
String query = (String) message;
Document result = mongoCollection.find(Document.parse(query)).first();
if (result != null) {
System.out.println(result.toJson());
} else {
System.out.println("No result found.");
}
} else {
unhandled(message);
}
}
@Override
public void postStop() throws Exception {
mongoClient.close();
}
public static void main(String[] args) {
ActorSystem system = ActorSystem.create("MongoDBExample");
ActorRef mongoDBActor = system.actorOf(MongoDBActor.props("localhost", 27017, "myDatabase", "myCollection"));
// 查询集合中id为1的文档
mongoDBActor.tell("{id: 1}", ActorRef.noSender());
system.terminate();
}
}
上面的代码演示了如何在一个 Actor 中使用 Java 驱动程序连接 MongoDB 并从集合中查询文档。首先,在 MongoDBActor 中创建一个 MongoClient 和 MongoDatabase 实例,并在构造函数中设置集合名称。然后在 onReceive 方法中接收消息,查询指定条件的文档,并将结果打印到控制台。最后,使用 ActorSystem 创建一个 ActorRef 并发送消息进行测试。