目前我正在使用带有java的mongodb。我不想每次都重新打开与数据存储的连接,所以我想我应该创建一个静态变量:
package Config;
import java.net.UnknownHostException;
import com.google.code.morphia.*;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class Config {
static String dbUrl = "url";
static int dbPort = portnumber;
static String username = "user";
static String password = "pw";
static String dbName = "dbname";
public static Datastore ds;
public static Datastore getDatastore() throws UnknownHostException,
MongoException {
if (ds == null) {
ds = connect();
}
return ds;
}
public static Datastore connect() throws UnknownHostException,
MongoException {
Mongo m = new Mongo(dbUrl, dbPort);
Datastore ds = new Morphia().createDatastore(m, dbName);
boolean con = ds.getDB().authenticate(username, password.toCharArray());// todo
return ds;
}
}
我会这样使用它:
Config.getDatastore().doSomthing();
除了那些未处理的异常,这是使用static
变量的正确方法吗?