当前位置:   article > 正文

Sequoiadb操作

Sequoiadb操作
  1. package com.iminido.nosql;
  2. import com.google.gson.Gson;
  3. import com.iminido.constant.Const;
  4. import com.iminido.instruction.core.IstRequ;
  5. import com.iminido.log.Log;
  6. import com.iminido.util.SU;
  7. import static com.iminido.util.SU.parseJSON2Map;
  8. import com.iminido.util.TL;
  9. import com.sequoiadb.base.CollectionSpace;
  10. import com.sequoiadb.base.DBCollection;
  11. import com.sequoiadb.base.DBCursor;
  12. import com.sequoiadb.base.Sequoiadb;
  13. import com.sequoiadb.base.SequoiadbDatasource;
  14. import com.sequoiadb.base.SequoiadbOption;
  15. import com.sequoiadb.exception.BaseException;
  16. import com.sequoiadb.net.ConfigOptions;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import java.util.concurrent.Semaphore;
  20. import java.util.concurrent.TimeUnit;
  21. import java.util.logging.Level;
  22. import java.util.logging.Logger;
  23. import org.bson.BSONObject;
  24. import org.bson.BasicBSONObject;
  25. import org.bson.util.JSON;
  26. /**
  27. *
  28. * @author JadeLuo
  29. */
  30. public class NoSQLDb {
  31. private static SequoiadbDatasource sequoiadbDatasource;
  32. private static final Log log = Log.init(NoSQLDb.class);
  33. private static Semaphore semaphore = new Semaphore(1);
  34. static {
  35. initSequoiadbDatasource();
  36. }
  37. public static void initSequoiadbDatasource() {
  38. ArrayList<String> urls = new ArrayList<>();
  39. ConfigOptions nwOpt = new ConfigOptions(); // 定义连接选项
  40. SequoiadbOption dsOpt = new SequoiadbOption(); // 定义连接池选项
  41. urls.add(Const.SEQUOIADB_HOST + ":" + Const.SEQUOIADB_PORT);
  42. // urls.add("ubuntu-dev2:11810");
  43. // urls.add("ubuntu-dev3:11810");
  44. nwOpt.setConnectTimeout(500); // 设置若连接失败,超时时间(ms)
  45. nwOpt.setMaxAutoConnectRetryTime(0); // 设置若连接失败,重试次数
  46. // 以下设置的都是 SequoiadbOption 的默认值
  47. dsOpt.setMaxConnectionNum(500); // 设置连接池最大连接数
  48. dsOpt.setInitConnectionNum(10); // 初始化连接池时,创建连接的数量
  49. dsOpt.setDeltaIncCount(10); // 当池中没有可用连接时,增加连接的数量
  50. dsOpt.setMaxIdeNum(10); // 周期清理多余的空闲连接时,应保留连接的数量
  51. dsOpt.setTimeout(5 * 1000); // 当已使用的连接数到达设置的最大连接数时(500),请求连接的等待时间。
  52. dsOpt.setAbandonTime(10 * 60 * 1000); // 连接存活时间,当连接空闲时间超过连接存活时间,将被连接池丢弃
  53. dsOpt.setRecheckCyclePeriod(1 * 60 * 1000); // 清除多余空闲连接的周期
  54. dsOpt.setRecaptureConnPeriod(10 * 60 * 1000); // 检测并取回异常地址的周期
  55. sequoiadbDatasource = new SequoiadbDatasource(urls, Const.SEQUOIADB_USERNAME, Const.SEQUOIADB_PASSWORD, nwOpt, dsOpt); // 创建连接池
  56. }
  57. public static synchronized Sequoiadb getSequoiadb() {
  58. Sequoiadb sdb = null;
  59. try {
  60. sdb = sequoiadbDatasource.getConnection();
  61. } catch (BaseException ex) {
  62. System.out.println("getIdleConnNum1 " + sequoiadbDatasource.getIdleConnNum());
  63. System.out.println("getUsedConnNum" + sequoiadbDatasource.getUsedConnNum());
  64. Logger.getLogger(NoSQLDb.class.getName()).log(Level.SEVERE, null, ex);
  65. } catch (InterruptedException ex) {
  66. System.out.println("getIdleConnNum2 " + sequoiadbDatasource.getIdleConnNum());
  67. System.out.println("getUsedConnNum" + sequoiadbDatasource.getUsedConnNum());
  68. Logger.getLogger(NoSQLDb.class.getName()).log(Level.SEVERE, null, ex);
  69. }
  70. if (sdb == null) {
  71. while (sdb == null) {
  72. try {
  73. semaphore.tryAcquire(1, 2, TimeUnit.SECONDS);
  74. } catch (InterruptedException ex) {
  75. System.out.println("getIdleConnNum3 " + sequoiadbDatasource.getIdleConnNum());
  76. System.out.println("getUsedConnNum" + sequoiadbDatasource.getUsedConnNum());
  77. Logger.getLogger(NoSQLDb.class.getName()).log(Level.SEVERE, null, ex);
  78. }
  79. try {
  80. sdb = sequoiadbDatasource.getConnection();
  81. } catch (BaseException | InterruptedException ex) {
  82. System.out.println("getIdleConnNum4 " + sequoiadbDatasource.getIdleConnNum());
  83. System.out.println("getUsedConnNum" + sequoiadbDatasource.getUsedConnNum());
  84. Logger.getLogger(NoSQLDb.class.getName()).log(Level.SEVERE, null, ex);
  85. }
  86. }
  87. semaphore.release();
  88. return sdb;
  89. }
  90. return sdb;
  91. }
  92. public static CollectionSpace initCollectionSpace(String csName) {
  93. try {
  94. Sequoiadb sdb = getSequoiadb();
  95. CollectionSpace cs;
  96. if (sdb.isCollectionSpaceExist(csName)) {
  97. cs = sdb.getCollectionSpace(csName);
  98. } else {
  99. cs = sdb.createCollectionSpace(csName);
  100. }
  101. return cs;
  102. } catch (BaseException ex) {
  103. Logger.getLogger(NoSQLDb.class.getName()).log(Level.SEVERE, null, ex);
  104. log.debug("D:\\working\\workspace\\LF_S_SignalProc\\src\\com\\iminido\\nosql\\NoSQLDb.java initCollectionSpace 方法获取 Sequoiadb 为空");
  105. return null;
  106. }
  107. }
  108. public static DBCollection initCollection(String collectionName) {
  109. CollectionSpace cs = initCollectionSpace(Const.SEQUOIADB_DATABASE);
  110. DBCollection cl;
  111. if (cs.isCollectionExist(collectionName)) {
  112. cl = cs.getCollection(collectionName);
  113. } else {
  114. cl = cs.createCollection(collectionName);
  115. }
  116. return cl;
  117. }
  118. public static void removeAll(String collectionName) {
  119. DBCollection cl = initCollection(collectionName);
  120. cl.delete(new BasicBSONObject());
  121. sequoiadbDatasource.close(cl.getSequoiadb());
  122. }
  123. public static void remove(String collectionName) {
  124. DBCollection cl = initCollection(collectionName);
  125. cl.delete(new BasicBSONObject());
  126. sequoiadbDatasource.close(cl.getSequoiadb());
  127. }
  128. public static boolean delete(String cl, String matcher) {
  129. try {
  130. DBCollection dbc = initCollection(cl);
  131. dbc.delete(matcher);
  132. sequoiadbDatasource.close(dbc.getSequoiadb());
  133. return true;
  134. } catch (Exception e) {
  135. log.error("delete " + cl + "matcher=>" + matcher + "失败", e);
  136. return false;
  137. }
  138. }
  139. public static void delete(String cl, String matcher, String hint) {
  140. DBCollection dbc = initCollection(cl);
  141. dbc.delete(matcher, hint);
  142. sequoiadbDatasource.close(dbc.getSequoiadb());
  143. }
  144. public static boolean insert(String collectionName, String... key_val) {
  145. String strJson = strs2json(key_val);
  146. log.debug("D:\\working\\workspace\\LF_S_SignalProc\\src\\com\\iminido\\nosql\\NoSQLDb.java save=>" + strJson);
  147. if (strJson != null) {
  148. BSONObject dbo;
  149. try {
  150. dbo = (BasicBSONObject) JSON.parse(strJson); //添加异常处理
  151. } catch (Exception e) {
  152. log.error("解析json字符串异常,传入的字符串为:" + strJson, e);
  153. return false;
  154. }
  155. try {
  156. DBCollection dbc = initCollection(collectionName);
  157. dbc.insert(dbo);
  158. sequoiadbDatasource.close(dbc.getSequoiadb());
  159. return true;
  160. } catch (Exception e) {
  161. return false;
  162. }
  163. }
  164. return false;
  165. }
  166. public static boolean insert(String collectionName, String strJson) {
  167. BSONObject dbo = null;
  168. try {
  169. dbo = (BasicBSONObject) JSON.parse(strJson); //添加异常处理
  170. } catch (Exception e) {
  171. log.error("解析json字符串异常,传入的字符串为:" + strJson, e);
  172. return false;
  173. }
  174. DBCollection dBCollection = initCollection(collectionName);
  175. Object object = dBCollection.insert(dbo);
  176. sequoiadbDatasource.close(dBCollection.getSequoiadb());
  177. return true;
  178. }
  179. public static boolean insertNestJson(String collectionName, String strJson, String strJson2, String nameOfNest) {
  180. BSONObject dbo = null;
  181. try {
  182. dbo = (BasicBSONObject) JSON.parse(strJson); //添加异常处理
  183. } catch (Exception e) {
  184. log.error("解析json字符串异常,传入的字符串为:" + strJson, e);
  185. return false;
  186. }
  187. BSONObject dbo2 = null;
  188. try {
  189. dbo2 = (BasicBSONObject) JSON.parse(strJson2); //添加异常处理
  190. } catch (Exception e) {
  191. log.error("解析json字符串异常,传入的字符串为:" + strJson, e);
  192. return false;
  193. }
  194. dbo.put(nameOfNest, dbo2);
  195. DBCollection dBCollection = initCollection(collectionName);
  196. Object object = dBCollection.insert(dbo);
  197. sequoiadbDatasource.close(dBCollection.getSequoiadb());
  198. return true;
  199. }
  200. public static boolean insert(String collectionName, IstRequ requ) {
  201. String strJson = TL.requ2json(requ);
  202. BSONObject dbo = null;
  203. try {
  204. dbo = (BasicBSONObject) JSON.parse(strJson); //添加异常处理
  205. } catch (Exception e) {
  206. log.error("解析json字符串异常,传入的字符串为:" + strJson, e);
  207. return false;
  208. }
  209. DBCollection dBCollection = initCollection(collectionName);
  210. dBCollection.insert(dbo);
  211. sequoiadbDatasource.close(dBCollection.getSequoiadb());
  212. return true ;
  213. }
  214. public static Object insert(String collectionName, IstRequ requ, String args) {
  215. String strJson = TL.requ2json(requ, args);
  216. BSONObject dbo = null;
  217. try {
  218. dbo = (BasicBSONObject) JSON.parse(strJson); //添加异常处理
  219. } catch (Exception e) {
  220. log.error("解析json字符串异常,传入的字符串为:" + strJson, e);
  221. }
  222. DBCollection dBCollection = initCollection(collectionName);
  223. Object object = dBCollection.insert(dbo);
  224. sequoiadbDatasource.close(dBCollection.getSequoiadb());
  225. return object;
  226. }
  227. // public static void savej(String collectionName, IstRequ req) {
  228. // String strJson = req.get("j");
  229. // strJson = strJson.replaceAll("\'", "\""); //把单引号替换成双引号,不用这句也可以执行成功。加这句是为了让我记住json应用中存在单双引号问题,在jquery中,如果json是用单引号的话,就会出错,在php中json用单引号也会出错。
  230. // insert(collectionName, strJson);
  231. // }
  232. public static boolean isExist(String collectionName, String matcher) {
  233. if (null == queryOne(collectionName, matcher, matcher, matcher, null)) {
  234. return false;
  235. } else {
  236. return true;
  237. }
  238. }
  239. public static BSONObject queryOne(String collectionName, String matcher, String selector, String orderBy, String hint) {
  240. DBCollection dBCollection = initCollection(collectionName);
  241. BSONObject bSONObject = dBCollection.queryOne(str2BSONObject(matcher), str2BSONObject(selector), str2BSONObject(orderBy), str2BSONObject(hint), 0);
  242. sequoiadbDatasource.close(dBCollection.getSequoiadb());
  243. return bSONObject;
  244. }
  245. public static DBCursor findandclose(String collectionName, String... key_val) {
  246. DBCollection dBCollection = initCollection(collectionName);
  247. DBCursor dBCursor = dBCollection.query();
  248. sequoiadbDatasource.close(dBCollection.getSequoiadb());
  249. return dBCursor;
  250. }
  251. public static DBCursor query(String collectionName, String... key_val) {
  252. return initCollection(collectionName).query();
  253. }
  254. public static DBCursor query(String collectionName) {
  255. return initCollection(collectionName).query();
  256. }
  257. public static DBCursor query(String collectionName, String matcher, String selector, String orderBy, String hint, int limitNum) {
  258. return initCollection(collectionName).query(matcher, selector, orderBy, hint);
  259. }
  260. public static BasicBSONObject str2BSONObject(String jsonString) {
  261. return (BasicBSONObject) JSON.parse(jsonString);
  262. }
  263. public static List exec(String sql) {
  264. DBCursor c = null;
  265. Sequoiadb seq = null;
  266. try {
  267. seq = sequoiadbDatasource.getConnection();
  268. c = seq.exec(sql);
  269. } catch (BaseException e) {
  270. e.printStackTrace();
  271. } catch (InterruptedException ex) {
  272. Logger.getLogger(NoSQLDb.class.getName()).log(Level.SEVERE, null, ex);
  273. }
  274. if (c != null && c.hasNext()) {
  275. List list = new ArrayList();
  276. while (c.hasNext()) {
  277. list.add(c.getNext());
  278. }
  279. if (seq != null) {
  280. sequoiadbDatasource.close(seq);
  281. }
  282. return list;
  283. } else {
  284. if (seq != null) {
  285. sequoiadbDatasource.close(seq);
  286. }
  287. return null;
  288. }
  289. }
  290. public static String exeSql(String sql) {
  291. return list2String(exec(sql));
  292. }
  293. public static String exe(String sql) {
  294. return list2String(exec(sql));
  295. }
  296. public static boolean execUpdate(String sql) {
  297. try {
  298. Sequoiadb seq = sequoiadbDatasource.getConnection();
  299. seq.execUpdate(sql);
  300. sequoiadbDatasource.close(seq);
  301. return true;
  302. } catch (BaseException e) {
  303. e.printStackTrace();
  304. log.warn(sql, e);
  305. return false;
  306. } catch (InterruptedException ex) {
  307. Logger.getLogger(NoSQLDb.class.getName()).log(Level.SEVERE, null, ex);
  308. return false;
  309. }
  310. }
  311. //matcher test
  312. public static List query(String cl, String matcher) {
  313. DBCollection dbc = initCollection(cl);
  314. DBCursor c = dbc.query(matcher, null, null, null, 0L, 100L);
  315. List<String> list = null;//new ArrayList<>();
  316. if (c != null && c.hasNext()) {
  317. list = cur2list(c);
  318. } else {
  319. sequoiadbDatasource.close(dbc.getSequoiadb());
  320. return list;
  321. }
  322. sequoiadbDatasource.close(dbc.getSequoiadb());
  323. return list;
  324. }
  325. //matcher test
  326. public static List query(String cl, String matcher,String selector) {
  327. DBCollection dbc = initCollection(cl);
  328. DBCursor c = dbc.query(matcher, selector, null, null, 0L, 100L);
  329. List<String> list = null;//new ArrayList<>();
  330. if (c != null && c.hasNext()) {
  331. list = cur2list(c);
  332. } else {
  333. sequoiadbDatasource.close(dbc.getSequoiadb());
  334. return list;
  335. }
  336. sequoiadbDatasource.close(dbc.getSequoiadb());
  337. return list;
  338. }
  339. //returnRows test
  340. public static DBCursor query(String cl, String matcher, long returnRows) {
  341. return initCollection(cl).query(matcher, null, null, null, 0L, returnRows);
  342. }
  343. // selector {filed:1}
  344. public static DBCursor query(String cl, String matcher, String selector, long returnRows) {
  345. return initCollection(cl).query(matcher, selector, null, null, 0L, returnRows);
  346. }
  347. //orderBy {filed:1/-1}
  348. public static DBCursor query(String cl, String matcher, String selector, String orderBy, long returnRows) {
  349. return initCollection(cl).query(matcher, selector, orderBy, null, 0L, returnRows);
  350. }
  351. //hint (index) {}
  352. public static DBCursor query(String cl, String matcher, String selector, String orderBy, String hint, long returnRows) {
  353. DBCollection dbc = initCollection(cl);
  354. DBCursor dbcu = dbc.query(matcher, selector, orderBy, hint, 0L, returnRows);
  355. sequoiadbDatasource.close(dbc.getSequoiadb());
  356. return dbcu;
  357. }
  358. public static List query2(String cl, String matcher, String selector, String orderBy, String hint, long returnRows,List<String> list ) {
  359. DBCollection dbc = initCollection(cl);
  360. DBCursor c = dbc.query(matcher, selector, orderBy, hint, 0L, returnRows);
  361. if (c != null && c.hasNext()) {
  362. while (c.hasNext()) {
  363. String str1 = (String) c.getNext().get("acc");
  364. for (int j = 0; j < list.size(); j++) {
  365. String str2 = list.get(j);
  366. if (str2.equals(str1)) {
  367. list.remove(str1);
  368. }
  369. }
  370. }
  371. } else {
  372. sequoiadbDatasource.close(dbc.getSequoiadb());
  373. return list;//直接返回生成的推荐号
  374. }
  375. sequoiadbDatasource.close(dbc.getSequoiadb());
  376. return list;
  377. }
  378. public static DBCursor query(String cl, String matcher, long returnRows, long skipRows) {
  379. return initCollection(cl).query(matcher, null, null, null, skipRows, returnRows);
  380. }
  381. public static String query(String cl, String matcher, String selector, String orderBy, String hint, long skipRows, long returnRows) {
  382. DBCollection dbc = initCollection(cl);
  383. String jsonString = cur2jsonstr(dbc.query(matcher, selector, orderBy, hint, skipRows, returnRows));
  384. sequoiadbDatasource.close(dbc.getSequoiadb());
  385. return jsonString;
  386. }
  387. public static void update(String cl, String matcher, String modifier, String hint) {
  388. DBCollection dbc = initCollection(cl);
  389. dbc.update(matcher, modifier, hint);
  390. sequoiadbDatasource.close(dbc.getSequoiadb());
  391. }
  392. public static void update$unsetAll(String cl, String matcher, String field, String hint) {
  393. DBCollection dbc = initCollection(cl);
  394. dbc.update(matcher, "{$unset:" + field + ":[]}", hint); // NoSQLDb.update("friend", "{}", "{$unset:{label:[]}}", "{}");
  395. sequoiadbDatasource.close(dbc.getSequoiadb());
  396. }
  397. public static void update$unset(String cl, String matcher, String modifier, String hint) {
  398. DBCollection dbc = initCollection(cl);
  399. dbc.update(matcher, "{$unset:" + modifier + "}", hint); // NoSQLDb.update("friend", "{}", "{$unset:{label:[33,44,55]}}", "{}");
  400. sequoiadbDatasource.close(dbc.getSequoiadb());
  401. }
  402. public static void update$addtoset(String cl, String matcher, String modifier, String hint) {
  403. DBCollection dbc = initCollection(cl);
  404. dbc.update(matcher, "{$addtoset:" + modifier + "}", hint); // NoSQLDb.upsert("friend", "{}", "{$addtoset:{label:[33,44,55]}}", "{}");
  405. sequoiadbDatasource.close(dbc.getSequoiadb());
  406. }
  407. /**
  408. * 不存在会自动插入新记录
  409. *
  410. * @param cl
  411. * @param matcher
  412. * @param modifier
  413. * @param hint
  414. */
  415. public static void upsert(String cl, String matcher, String modifier, String hint) {
  416. DBCollection dbc = initCollection(cl);
  417. BSONObject ma = null;
  418. BSONObject mo = null;
  419. BSONObject hi = null;
  420. if (matcher != null) {
  421. ma = (BSONObject) JSON.parse(matcher);
  422. }
  423. if (modifier != null) {
  424. mo = (BSONObject) JSON.parse(modifier);
  425. }
  426. if (hint != null) {
  427. hi = (BSONObject) JSON.parse(hint);
  428. }
  429. dbc.upsert(ma, mo, hi);
  430. sequoiadbDatasource.close(dbc.getSequoiadb());
  431. }
  432. public static String strs2json(String... key_val) {
  433. String strJson = null;
  434. if (key_val != null) {
  435. StringBuilder sb = new StringBuilder();
  436. sb.append("{");
  437. int i = 0;
  438. while (key_val[i] != null) {
  439. sb.append(key_val[i]).append(":'").append(key_val[++i]).append("'");
  440. if (i < key_val.length - 1) {
  441. sb.append(",");
  442. i++;
  443. } else {
  444. key_val[i] = null;
  445. }
  446. }
  447. sb.append("}");
  448. strJson = sb.toString();
  449. }
  450. return strJson;
  451. }
  452. public static List cur2list(DBCursor c) {
  453. if (c != null && c.hasNext()) {
  454. List list = new ArrayList();
  455. while (c.hasNext()) {
  456. list.add(c.getNext());
  457. }
  458. return list;
  459. }
  460. return null;
  461. }
  462. public static String cur2jsonstr(DBCursor c) {
  463. String jsonString = "";
  464. if (c != null && c.hasNext()) {
  465. while (c.hasNext()) {
  466. jsonString = jsonString + (c.getNext().toString());
  467. }
  468. c.close();
  469. return jsonString;
  470. }
  471. return "{}";
  472. }
  473. private static String list2String(List list) {
  474. if (list != null) {
  475. StringBuilder sb = new StringBuilder();
  476. list.stream().forEach((Object s) -> {
  477. sb.append(s).append(",");
  478. });
  479. return sb.toString();
  480. } else {
  481. return null;
  482. }
  483. }
  484. public static void main(String[] args) {
  485. // NoSQLDb.insertNestJson(Const.TEST, "{a:'a'}","{cc:'dd'}","nestJson");
  486. String s = "{ \"_id\": { \"$oid\": \"544634608e849c2f20465015\" }, \"a\": \"a\", \"nestJson\": { \"cc\": \"dd\" } }";
  487. s = s.replace("\\", "");
  488. SU.parseJSON2Map(s);
  489. }
  490. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/615794
推荐阅读
相关标签
  

闽ICP备14008679号