package com.lolaage.dals.dbfactory.mongodb;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.*;
import org.apache.log4j.Logger;
import com.lolaage.config.Configure;
import com.lolaage.config.IConfigure;
import com.lolaage.entity.newdata.TLogin;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.mongodb.morphia.mapping.Mapper;
/**
*
* @ClassName: MongoFactory
* @Description: MongoFactory
* @date 2018
*
*/
public class MongoFactory {
private static final Logger logger = Logger.getLogger(MongoFactory.class);
private static Datastore ds = null;
private MongoFactory() {
}
/**
* 根据名称获取DB,相当于是连接
*
* @param
* @return
*/
public static Datastore getDatastore() {
if (ds == null) {
init();// 初始化
}
return ds;
}
/**
* 初始化连接池,设置参数。
*/
private static void init() {
IConfigure config = Configure.getInstance();
String host = config.readString("mongodb", "ip");
short port = config.readShort("mongodb", "port");
String uname = config.readString("mongodb", "uname");
String pwd = config.readString("mongodb", "pwd");
int poolSize = config.readInt("mongodb", "pool_size"); // 连接数量
int minpoolsize = config.readInt("mongodb", "min_pool_size"); // 最小连接数量
minpoolsize = minpoolsize>0 ? minpoolsize : 20;
int maxidletimems = config.readInt("mongodb", "maxidletimems"); //最大空闲时间
maxidletimems = maxidletimems>0 ? maxidletimems : 1000*10;
int maxWaitTime = config.readInt("mongodb", "maxWaitTime"); //最大等待时间
maxWaitTime = maxWaitTime>0 ? maxWaitTime : 1000*15;
int socketTimeout = config.readInt("mongodb", "socketTimeout");//连接超时时间
socketTimeout = socketTimeout>0 ? socketTimeout : 1000*15;
int connectTimeout = config.readInt("mongodb", "connectTimeout"); //超时
connectTimeout = connectTimeout>0 ? connectTimeout : 1000*15;
int blockSize = config.readInt("mongodb", "block_size"); // 等待队列长度
String databaseName = config.readString("mongodb", "database_name");
Morphia morphia = new Morphia();
Mapper mapper = morphia.getMapper();
mapper.addMappedClass(TLogin.class);
mapper.createEntityCache();
// 其他参数根据实际情况进行添加
try {
//1.连接池相关选项配置
MongoClientOptions options=MongoClientOptions.builder()
.connectionsPerHost(poolSize)
.minConnectionsPerHost(minpoolsize)
.maxConnectionIdleTime(maxidletimems)
.threadsAllowedToBlockForConnectionMultiplier(blockSize)
.maxWaitTime(maxWaitTime)
.socketTimeout(socketTimeout)
.connectTimeout(connectTimeout)
.build();
//2.鉴权配置
MongoCredential credential = MongoCredential.createScramSha1Credential(uname, "admin", pwd.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
//3.mongodb服务器相关配置
List<ServerAddress> addresses=new ArrayList<ServerAddress>();
addresses.add(new ServerAddress(host, port));
//4.创建客户实例,获取数据库存储对象。
MongoClient mongoClient = new MongoClient(addresses,credentials, options);
morphia.mapPackage("com.lolaage");// 告诉morphia到哪个包下面去找实体类
logger.warn("获取数据库连接对象>>>>>>>>>>>>>>>>>");
ds = morphia.createDatastore(mongoClient, databaseName);// 构建Datastore对象,其中`databaseName`是数据库名称
ds.ensureIndexes();//确保索引生效
//} catch (UnknownHostException e) {
// logger.error(e.getMessage());
} catch (MongoException e) {
logger.error(e.getMessage());
}
}
}
--------------------------------------------使用样例-------------------------------------------------------
1.对象配置
@Entity
public class TLogin extends LongPKMongoEO {
private int sessionId;
private long userId;
public int getSessionId() {
return sessionId;
}
public void setSessionId(int sessionId) {
this.sessionId = sessionId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
public abstract class LongPKMongoEO {
@Id
Long _id;
@Transient
protected Datastore ds;
public void setDs(Datastore ds) {
this.ds = ds;
}
@PrePersist
void prePersist() {
//自增性主键的处理
if (_id == null) {
String collName = ds.getCollection(getClass()).getName();
Query<StoredSeqence> q = ds.find(StoredSeqence.class, "_id", collName);
StoredSeqence ss = ds.findAndModify(q, ds.createUpdateOperations(StoredSeqence.class).inc("value"));
if(ss == null) {
ss = new StoredSeqence(collName);
ss.setValue(1l);
ds.save(ss);
}
_id = ss.getValue();
}
}
public Long getId() {
return _id;
}
}
@Entity(noClassnameStored = true)
public class StoredSeqence implements Serializable {
private static final long serialVersionUID = 1L;
@Id
String collName;
Long value;
public StoredSeqence() {
}
public StoredSeqence(String collName) {
this.collName = collName;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
public String getCollName() {
return collName;
}
public void setCollName(String collName) {
this.collName = collName;
}
}
2.对象存储:
Datastore datastore = MongoFactory.getDatastore();
Datastore ds = getDatastore();
ds.save(loginVO);
3.对象查询:
Datastore ds = getDatastore();
Query<TLogin> q = ds.createQuery(TLogin.class);
q.filter("userId", ((Long)userId));
TLogin login = q.get();