MongoDB-spring data和morphia有什么异同点
发布网友
发布时间:2022-04-24 05:00
我来回答
共1个回答
热心网友
时间:2022-04-07 20:06
首先我们需要一个生成和配置mongodb的工厂类:
1 public class MongoFactoryBean extends AbstractFactoryBean<Mongo> {
2
3 // 表示服务器列表(主从复制或者分片)的字符串数组
4 private String[] serverStrings;
5 // mongoDB配置对象
6 private MongoOptions mongoOptions;
7 // 是否主从分离(读取从库),默认读写都在主库
8 private boolean readSecondary = false;
9 // 设定写策略(出错时是否抛异常),默认采用SAFE模式(需要抛异常)
10 private WriteConcern writeConcern = WriteConcern.SAFE;
11
12 @Override
13 public Class<?> getObjectType() {
14 return Mongo.class;
15 }
16
17 @Override
18 protected Mongo createInstance() throws Exception {
19 Mongo mongo = initMongo();
20
21 // 设定主从分离
22 if (readSecondary) {
23 mongo.setReadPreference(ReadPreference.secondaryPreferred());
24 }
25
26 // 设定写策略
27 mongo.setWriteConcern(writeConcern);
28 return mongo;
29 }
30
31 /**
32 * 初始化mongo实例
33 * @return
34 * @throws Exception
35 */
36 private Mongo initMongo() throws Exception {
37 // 根据条件创建Mongo实例
38 Mongo mongo = null;
39 List<ServerAddress> serverList = getServerList();
40
41 if (serverList.size() == 0) {
42 mongo = new Mongo();
43 }else if(serverList.size() == 1){
44 if (mongoOptions != null) {
45 mongo = new Mongo(serverList.get(0), mongoOptions);
46 }else{
47 mongo = new Mongo(serverList.get(0));
48 }
49 }else{
50 if (mongoOptions != null) {
51 mongo = new Mongo(serverList, mongoOptions);
52 }else{
53 mongo = new Mongo(serverList);
54 }
55 }
56 return mongo;
57 }
58
59
60 /**
61 * 根据服务器字符串列表,解析出服务器对象列表
62 * <p>
63 *
64 * @Title: getServerList
65 * </p>
66 *
67 * @return
68 * @throws Exception
69 */
70 private List<ServerAddress> getServerList() throws Exception {
71 List<ServerAddress> serverList = new ArrayList<ServerAddress>();
72 try {
73 for (String serverString : serverStrings) {
74 String[] temp = serverString.split(":");
75 String host = temp[0];
76 if (temp.length > 2) {
77 throw new IllegalArgumentException(
78 "Invalid server address string: " + serverString);
79 }
80 if (temp.length == 2) {
81 serverList.add(new ServerAddress(host, Integer
82 .parseInt(temp[1])));
83 } else {
84 serverList.add(new ServerAddress(host));
85 }
86 }
87 return serverList;
88 } catch (Exception e) {
89 throw new Exception(
90 "Error while converting serverString to ServerAddressList",
91 e);
92 }
93 }
94
95 /* ------------------- setters --------------------- */
96 }