public List<User> pageList(int page,int pageSize){
DB myMongo = MongoManager.getDB("myMongo");
DBCollection userCollection = myMongo.getCollection("user");
DBCursor limit = userCollection.find().skip((page - 1) * 10).sort(new BasicDBObject()).limit(pageSize); List<User> userList = new ArrayList<User>();
while (limit.hasNext()) {
User user = new User();
user.parse(limit.next());
userList.add(user);
}
return userList;
---------------------
作者:褚金辉
来源:CSDN
原文:https://blog.csdn.net/maosijunzi/article/details/42082703
版权声明:本文为博主原创文章,转载请附上博文链接!
//===========================================================
@Autowired ConversationRepository conversationRepository;
@Autowired private MongoTemplate mongoTemplate;
@GetMapping("conversation")
public String getConversationByFromIdAndToIdAndTimeInBeginAndEnd(Integer begin,Integer end,String fromId,String toId){ BasicDBObject timestampGt = new BasicDBObject("timestamp",new BasicDBObject("$gt", begin));
BasicDBObject timestampLt = new BasicDBObject("timestamp", new BasicDBObject("$lt", end));
BasicDBObject fromIdObject = new BasicDBObject("fromId", fromId);
BasicDBObject toIdObject = new BasicDBObject("toId", toId);
BasicDBList andList = new BasicDBList();
andList.add(timestampGt);
andList.add(timestampLt);
andList.add(fromIdObject);
andList.add(toIdObject);
BasicDBObject queryCondition = new BasicDBObject("$and",andList);
List<Conversation> conversations = mongoTemplate.find(new BasicQuery(queryCondition), Conversation.class);
StringBuffer result = new StringBuffer("");
Gson gson = new Gson();
String s = gson.toJson(conversations); return s; }
//====================================================================
public class MongoUtils {
/**
* 日志
*/
private static Logger logger = LoggerFactory.getLogger(MongoUtils.class);
/**
* mongo
*/
private static Mongo mongo = null;
private MongoUtils() {
}
/**
*
* 过去连接
*
* @param dbName
* @return DB
* @exception/throws
*/
public static DB getDB(String dbName) {
if (mongo == null) {
synchronized (MongoUtils.class) {
if (mongo == null) {
init();
}
}
}
DB db = mongo.getDB(dbName);
synchronized (MongoUtils.class) {
if (!db.isAuthenticated()) {
boolean auth = db.authenticate(ConfigUtils.config.getMongodbUser(), ConfigUtils.config.getMongodbPassword().toCharArray());
logger.info("auth=" + auth);
}
}
return db;
}
/**
*
* 初始化参�?
*
* void
*
* @exception/throws
*/
private static void init() {
Config config = ConfigUtils.config;
String host = config.getMongodbIp();
int port = config.getMongodbPort();
int poolSize = config.getMongodbPoolSize();
int blockSize = config.getMongodbBlockSize();
try {
MongoOptions options = new MongoOptions();
options.autoConnectRetry = true;
options.connectionsPerHost = poolSize;
options.maxWaitTime = 5000;
options.socketTimeout = 0;
options.connectTimeout = 15000;
options.threadsAllowedToBlockForConnectionMultiplier = blockSize;
mongo = new Mongo(new ServerAddress(host, port), options);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 关闭连接
*
* void
*
* @exception/throws
*/
public static void close() {
if (mongo != null) {
mongo.close();
mongo = null;
}
}
/**
*
* 删除某个�?
*
* @param dbName
* @param tableName
* void
* @exception/throws
*/
public static void drop(String dbName, String tableName) {
getCollection(dbName, tableName).drop();
}
/**
*
* 获取DBCollection
*
* @param dbName
* @param tableName
* @return DBCollection
* @exception/throws
*/
public static DBCollection getCollection(String dbName, String tableName) {
DBCollection collection = MongoUtils.getDB(dbName).getCollection(tableName);
return collection;
}
}
//=======================================================================
/**
* 分类工人
* @version V0.1 2015年5月23日[版本号, YYYY-MM-DD]
* @see [相关类/方法]
* @since iCategory
*/
public class CategoryWorker implements Runnable {
/**
* 日志
*/
protected Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 缺少分类文件的分类记录的文件路径
*/
private String filePath = System.getProperty("user.dir") + "/logs/errorCategory.txt";
/**
* 配置
*/
private Config config;
public CategoryWorker(Config config) {
this.config = config;
}
/**
* 此方法覆盖父类的方法
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (true) {
try {
Map<String, String> categoryAlias = getCategoryAliasMap();
Map<String, Category> utlCategory = getUrlInfoCategory();
process(categoryAlias, utlCategory);
} catch (Exception e) {
log.warn(null, e);
} finally {
try {
log.info("暂停任务" + config.getInterval() + "秒");
Thread.sleep(config.getInterval() * 1000);
} catch (Exception e) {
log.warn(null, e);
}
}
}
}
/**
*
* 获取实际分类的分类库
*
* @return Map<String,Category>
* @exception/throws
*/
private Map<String, Category> getUrlInfoCategory() {
Map<String, Category> urlCategoryAlias = getCategoryMap();
Iterator<String> it = urlCategoryAlias.keySet().iterator();
while (it.hasNext()) {
String categoryId = it.next();
Category category = urlCategoryAlias.get(categoryId);
category.setCategoryFullPath(getFullPatht(categoryId, urlCategoryAlias));
}
return urlCategoryAlias;
}
/**
*
* 获取分类完整路径
*
* @param categoryId
* @param map
* @return String
* @exception/throws
*/
private String getFullPatht(String categoryId, Map<String, Category> map) {
String categoryName = null;
Category category = map.get(categoryId);
if (category != null) {
String parentId = category.getParentId();
categoryName = category.getCategoryName();
if (StringUtils.isNotEmpty(parentId)) {
return (getFullPatht(parentId, map)) + config.getCategorySymbol() + categoryName;
}
} else {
log.warn("没有对应分类:" + categoryId);
}
return categoryName;
}
/**
*
* 处理数据
*
* @param categoryAlias
* @param utlCategoryAlias
* void
* @exception/throws
*/
private void process(Map<String, String> categoryAlias, Map<String, Category> utlCategoryAlias) {
DBObject condition1 = new BasicDBObject();
condition1.put("CATEGORY_ID", null);
condition1.put("ALIAS_STATUS", null);
DBObject condition2 = new BasicDBObject();
condition2.put("CATEGORY_ID", null);
condition2.put("ALIAS_STATUS", 0);
DBObject queryCondition = new BasicDBObject();
queryCondition = new BasicDBObject();
BasicDBList values = new BasicDBList();
values.add(condition1);
values.add(condition2);
queryCondition.put("$or", values);
DBCollection collection = MongoUtils.getCollection("DWH", "URL_INFO");
boolean isOver = false;
while (!isOver) {
DBCursor cursor = collection.find(queryCondition).limit(config.getNum()).sort(new BasicDBObject("_id", -1));
int num = cursor.size();
log.info("num:" + num);
if (num <= 0) {
isOver = true;
} else {
while (cursor.hasNext()) {
DBObject object = cursor.next();
String urlHash = object.get("URL_HASH").toString().trim();
String parentId = object.get("PARENT_ID").toString().trim();
String siteId = object.get("SITE_ID").toString().trim();
if (parentId == null) {
log.info(urlHash);
}
Category category = utlCategoryAlias.get(parentId);
if (category == null) {
log.info(parentId);
}
String categoryName = category.getCategoryName();
String mainCategoryId = categoryAlias.get(categoryName);
if (StringUtils.isEmpty(mainCategoryId)) {
categoryName = utlCategoryAlias.get(parentId).getCategoryFullPath();
mainCategoryId = categoryAlias.get(categoryName);
}
StringBuffer loginfo = new StringBuffer();
loginfo.append(siteId+" "+categoryName+"\r\n");
if (StringUtils.isEmpty(mainCategoryId)) {
FileUtils.appendFile(filePath, loginfo.toString(), "UTF-8");
updateError(urlHash, mainCategoryId);
} else {
log.info(urlHash + ":" + mainCategoryId);
update(urlHash, mainCategoryId);
}
}
}
}
}
/**
*
* 获取主站分类别名库
*
* @return Map<String,String>
* @exception/throws
*/
private Map<String, String> getCategoryAliasMap() {
Map<String, String> map = new HashMap<String, String>();
DBCollection collection = MongoUtils.getCollection("DWH", "GEIHUI_CATEGORY_ALIAS");
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
DBObject object = cursor.next();
String categoryId = object.get("CATEGORY_ID").toString().trim();
String categoryName = object.get("CATEGORY_NAME").toString().trim();
if (StringUtils.isNotEmpty(categoryName)) {
map.put(categoryName, categoryId);
}
}
return map;
}
/**
*
* 获取urlInfo实际分类
*
* @return Map<String,Category>
* @exception/throws
*/
private Map<String, Category> getCategoryMap() {
Map<String, Category> map = new HashMap<String, Category>();
DBCollection dbCollection = MongoUtils.getCollection("DWH", "GOODS_CATEGORY");
DBCursor cursor = dbCollection.find();
while (cursor.hasNext()) {
try {
DBObject dBObject = cursor.next();
String categoryId = dBObject.get("CATEGORY_ID").toString();
String categoryName = dBObject.get("CATEGORY_NAME").toString();
String parentId = dBObject.get("PARENT_ID").toString();
Category category = new Category();
category.setCategoryId(categoryId);
category.setCategoryName(categoryName);
category.setParentId(parentId);
map.put(categoryId, category);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return map;
}
/**
*
* 更新urlInfo的主站分类id
*
* @param urlHash
* @param categoryId
* void
* @exception/throws
*/
private void update(String urlHash, String categoryId) {
DBObject query = new BasicDBObject();
query.put("URL_HASH", urlHash);
DBObject updatedValue = new BasicDBObject();
updatedValue.put("CATEGORY_ID", categoryId);
DBCollection dbCollection = MongoUtils.getCollection("DWH", "URL_INFO");
dbCollection.update(query, new BasicDBObject("$set", updatedValue), false, true);
}
/**
*
* 没有分类别名时,更新urlInfo的ALIAS_STATUS为-1
*
* @param urlHash
* @param categoryId
* void
* @exception/throws
*/
private void updateError(String urlHash, String categoryId) {
DBObject query = new BasicDBObject();
query.put("URL_HASH", urlHash);
DBObject updatedValue = new BasicDBObject();
updatedValue.put("ALIAS_STATUS", -1);
DBCollection dbCollection = MongoUtils.getCollection("DWH", "URL_INFO");
dbCollection.update(query, new BasicDBObject("$set", updatedValue), false, true);
}
}
private Map<String, Category> getCategoryMap() {
Map<String, Category> map = new HashMap<String, Category>();
DBCollection dbCollection = MongoUtils.getCollection("DWH", "GEIHUI_CATEGORY");
DBObject obj = new BasicDBObject("WEIGHT.UPDATED", new BasicDBObject("$gte", 0));
DBCursor cursor = dbCollection.find(obj);
while (cursor.hasNext()) {
try {
DBObject dBObject = cursor.next();
String categoryId = dBObject.get("CATEGORY_ID").toString();
Category category = getCategory(dBObject);
map.put(categoryId, category);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return map;
}
private static List<SiteInfo> getSiteInfoList() {
List<SiteInfo> list = new ArrayList<SiteInfo>();
DBCollection dbCollection = MongoUtils.getCollection("DWH", "SITE_INFO");
DBObject query = new BasicDBObject();
query.put("SITE_STATUS", 1);
DBCursor cursor = dbCollection.find(query);//11个商城
while (cursor.hasNext()) {
try {
DBObject dBObject = cursor.next();
SiteInfo siteInfo = getSiteInfo(dBObject);
list.add(siteInfo);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return list;
}
private List<DBObject> selectUrlInfo(String id, int num, String CATEGORY) {
List<DBObject> list = new ArrayList<DBObject>();
DBCollection collection = MongoUtils.getCollection("DWH", "URL_INFO");
try {
DBObject obj = new BasicDBObject("STATUS", 0);
obj.put("CATEGORY_ID", id);
if ("category".equals(CATEGORY)) {
obj.put("URL_TYPE", "CATEGORY");
} else {
obj.put("URL_TYPE", "DETAIL");
}
DBCursor cursor = collection.find(obj).limit(num).sort(new BasicDBObject("UPDATE_TIME", -1));
while (cursor.hasNext()) {
try {
DBObject dBObject = cursor.next();
dBObject.put("HANDLE_TYPE", 1);
dBObject.removeField("_id");
list.add(dBObject);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} catch (Exception e) {
log.warn(null, e);
}
return list;
}
MongoCursor<Document> dbCursor = collGoodsCategory.find(findDbObject).projection(keys).batchSize(1000).iterator();//优化
public class QueryOperators {
public static final String OR = "$or";
public static final String AND = "$and";
public static final String GT = "$gt";
public static final String GTE = "$gte";
public static final String LT = "$lt";
public static final String LTE = "$lte";
public static final String NE = "$ne";
public static final String IN = "$in";
public static final String NIN = "$nin";
public static final String MOD = "$mod";
public static final String ALL = "$all";
public static final String SIZE = "$size";
public static final String EXISTS = "$exists";
public static final String ELEM_MATCH = "$elemMatch";
public static final String WHERE = "$where";
public static final String NOR = "$nor";
public static final String TYPE = "$type";
public static final String NOT = "$not";
public static final String WITHIN = "$within";
public static final String NEAR = "$near";
public static final String NEAR_SPHERE = "$nearSphere";
public static final String BOX = "$box";
public static final String CENTER = "$center";
public static final String POLYGON = "$polygon";
public static final String CENTER_SPHERE = "$centerSphere";
public static final String MAX_DISTANCE = "$maxDistance";
public static final String UNIQUE_DOCS = "$uniqueDocs";
public static final String TEXT = "$text";
public static final String SEARCH = "$search";
public static final String LANGUAGE = "$language";
public static final String RETURN_KEY = "$returnKey";
public static final String MAX_SCAN = "$maxScan";
public static final String ORDER_BY = "$orderby";
public static final String EXPLAIN = "$explain";
public static final String SNAPSHOT = "$snapshot";
public static final String MIN = "$min";
public static final String MAX = "$max";
public static final String SHOW_DISK_LOC = "$showDiskLoc";
public static final String HINT = "$hint";
public static final String COMMENT = "$comment";
}
public static void main(String[] args) {
// 取出满足条件的数据,包含“&page=1”,然后进一步确定是否是“&page=1”,最后更新数据
// BasicDBObject query=new BasicDBObject();
// query.append("id", new BasicDBObject(QueryOperators.ELEM_MATCH, "page=1$"));
ConfigInfo configInfo;
try {
configInfo = ConfigUtils.getConfigInfo();
MongoDB mongoDB = new MongoDB(configInfo.getDbIP(),configInfo.getDbPort(),configInfo.getDbUser(),configInfo.getDbPassword());
MongoCollection<Document> collUrlInfo = mongoDB.getCollection("xxy", "URL_INFO");
BasicDBObject findDBObject = new BasicDBObject();
//"SITE_ID": "76E9A452DF0A6A13E7BA305C955FE4A1",
//"SITE_ID": "222759A4AB646D6CF1C0BFE0AD858B5D"
findDBObject.put("SITE_ID", "3D593D893BEE2DA12520A2DEA4413628");
Pattern pattern = Pattern.compile("page=1$", Pattern.CASE_INSENSITIVE);
findDBObject.put("URL", pattern);
BasicDBObject keys = new BasicDBObject();
keys.put("URL", 1);
keys.put("URL_HASH", 1);
List<Document> cursor = collUrlInfo.find(findDBObject).projection(keys).batchSize(500).into(new ArrayList<Document>());//27894/500=56
String url;