第一阶段的弱联网游戏已基本完成,截至今天下午,测试也基本差很少了,前端还有一些小bug须要优化,接下来会接入小米,360,百度,腾讯等平台,而后推广一波,年前公司还能赚一笔,而我,也即将准备作下一款SLG。上一次,我第一次尝试了Netty,而且也着实感觉到了Nio的魅力,Netty的魅力,在作的过程当中也学到了不少有用的东西,这一次,在数据持久化方面,我思考了好久,我愈加的以为,我即将作的这款游戏的数据用nosql来存储更合适,甚至是以前作的那款弱联网游戏的存储,我也认为彷佛应该使用nosql来作存储,由于游戏数据的扩展性太强了,也不须要传统关系型数据库那些复杂的约束,彷佛是高性能的mongo更适合这类数据的存储,以前由于项目比较急,没敢在数据库这块作尝试,而此次,我准备尝试使用Mongo作数据层的持久化,之前作Web开发的时候,项目中用过Mongo,可是当时对它了解并很少,最多了解到它是一种文档型数据库,和传统数据库有较大区别,但我并无太多的了解,而当我开始作游戏以后,却愈来愈以为这种Nosql数据库彷佛更加适合游戏数据存储的需求。最终我仍是准备使用mongo来作数据持久化,而后开始了个人mongo之旅,心中不禁说了一句——你好,mongo!javascript
众多nosql数据库中,我为何要用mongo呢?实际上,我还会用到memcache和redis,memcached用来作缓存,memcache的缓存性能相信你们也清楚,用它来配合mongo来作缓存再适合不过了,把玩家完整的游戏数据都放在缓存中,读取所有数据直接读取缓存(具体哪些数据缓存到时候看状况而定),而使用redis,主要是看中它多样的数据类型和数据本地化的功能,而且redis的性能也没必要memcache差多少,而mongo,更是一种高性能的文档型数据库,不了解的同窗能够去官网逛逛,mongo的官网地址:http://www.mongo.org Mongo主要特下以下:前端
仅凭以上4点,我认为,像我作的这种数据类型复杂多变的游戏数据用mongo来存储再合适不过了。固然mongo还有更多的优势如复制和故障恢复,支持彻底索引等。java
mongo自己是由C++编写的,可它却也支持不少语言,固然,最重要的是,它有提供Java api,如下是mongo java api官方文档:http://api.mongodb.org/java/2.11.2/ 固然,既然有官方api,那就必定有人封装了更方便更好用的框架出来,像morphia,就是一款相似于关系型数据库ORM的Hibernate同样,方便易用,另外,spring也提供了mongo的封装,有兴趣的均可以去了解一下,毕竟每一个人有本身的习惯,本身喜欢的才是最好的。使用官方提供的java api,操做mongo也是很是的方便,举例,好比如下保存对象的方法:redis
//第一:实例化mongo对象,链接mongodb服务器 包含全部的数据库 //默认构造方法,默认是链接本机,端口号,默认是27017 //至关于Mongo mongo =new Mongo("localhost",27017) Mongo mongo =new Mongo(); //第二:链接具体的数据库 //其中参数是具体数据库的名称,若服务器中不存在,会自动建立 DB db=mongo.getDB("myMongo"); //第三:操做具体的表 //在mongodb中没有表的概念,而是指集合 //其中参数是数据库中表,若不存在,会自动建立 DBCollection collection=db.getCollection("user"); //添加操做 //在mongodb中没有行的概念,而是指文档 BasicDBObject document=new BasicDBObject(); document.put("id", 1); document.put("name", "小明"); //而后保存到集合中 //collection.insert(document); //固然我也能够保存这样的json串 /* { "id":1, "name","小明", "address": { "city":"beijing", "code":"065000" } }*/ //实现上述json串思路以下: //第一种:相似xml时,不断添加 BasicDBObject addressDocument=new BasicDBObject(); addressDocument.put("city", "beijing"); addressDocument.put("code", "065000"); document.put("address", addressDocument); //而后保存数据库中 collection.insert(document); //第二种:直接把json存到数据库中 /* String jsonTest="{'id':1,'name':'小明',"+ "'address':{'city':'beijing','code':'065000'}"+ "}"; DBObject dbobjct=(DBObject)JSON.parse(jsonTest); collection.insert(dbobjct);*/
其他方法我就不赘述了,想了解的能够查官方文档。spring
既然决定使用mongo,那就要着手开始写工具类,按照官方文档,我写了MongoUtil和DBObjectUtil两个工具类,MongoUtil负责数据库的链接和操做,DBObjectUtil则是Mongo中的操做对象DBObject与Javabean之间的相互转换。首先,我要在个人maven的pom.xml文件中依赖mongo的jar包sql
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.11.2</version> </dependency>
而后是个人MongoUtil类,其中简单作了数据库的链接管理,MC是Memcache缓存,这部分代码就不贴出来了,上篇文章已贴出过Memcache部分代码:mongodb
/** * @ClassName: MongoUtil * @Description: mongo * @author 何金成 * @date 2016年1月19日 下午3:35:25 * */ public class MongoUtil { private MongoClient mongo = null; private DB db = null; private static Logger logger = LoggerFactory.getLogger(MongoUtil.class); private static final Map<String, MongoUtil> instances = new ConcurrentHashMap<String, MongoUtil>(); private static final String CONF_PATH = "/spring-mongodb/mongodb.properties"; public static final String DB_ID = "id";// DB中id字段名 /** * 实例化 * * @return MongoDBManager对象 */ static { getInstance("db");// 初始化默认的MongoDB数据库 } public static MongoUtil getInstance() { return getInstance("db");// 配置文件默认数据库前缀为db } public static MongoUtil getInstance(String dbName) { MongoUtil mongoMgr = instances.get(dbName); if (mongoMgr == null) { mongoMgr = buildInstance(dbName); if (mongoMgr == null) { return null; } instances.put(dbName, mongoMgr); } return mongoMgr; } private static synchronized MongoUtil buildInstance(String dbName) { MongoUtil mongoMgr = new MongoUtil(); try { mongoMgr.mongo = new MongoClient(getServerAddress(dbName), getMongoCredential(dbName), getDBOptions(dbName)); mongoMgr.db = mongoMgr.mongo.getDB(getProperty(CONF_PATH, dbName + ".database")); logger.info("connect to MongoDB success!"); boolean flag = mongoMgr.db.authenticate( getProperty(CONF_PATH, dbName + ".username"), getProperty(CONF_PATH, dbName + ".password").toCharArray()); if (!flag) { logger.error("MongoDB auth failed"); return null; } } catch (Exception e) { logger.info("Can't connect " + dbName + " MongoDB! {}", e); return null; } return mongoMgr; } /** * 根据properties文件的key获取value * * @param filePath * properties文件路径 * @param key * 属性key * @return 属性value */ private static String getProperty(String filePath, String key) { Properties props = new Properties(); try { InputStream in = MongoUtil.class.getResourceAsStream(filePath); props.load(in); String value = props.getProperty(key); return value; } catch (Exception e) { logger.info("load mongo properties exception {}", e); System.exit(0); return null; } } /** * 获取集合(表) * * @param collection */ public DBCollection getCollection(String collection) { DBCollection collect = db.getCollection(collection); return collect; } /** * 插入 * * @param collection * @param o */ public void insert(String collection, DBObject o) { getCollection(collection).insert(o); // 添加到MC控制 MC.add(o, o.get(DB_ID)); } /** * 批量插入 * * @param collection * @param list */ public void insertBatch(String collection, List<DBObject> list) { if (list == null || list.isEmpty()) { return; } getCollection(collection).insert(list); // 批量插入MC for (DBObject o : list) { MC.add(o, o.get(DB_ID)); } } /** * 删除 * * @param collection * @param q * 查询条件 */ public List<DBObject> delete(String collection, DBObject q) { getCollection(collection).remove(q); List<DBObject> list = find(collection, q); // MC中删除 for (DBObject tmp : list) { DBObject dbObject = MC.<DBObject> get(DBObject.class, (Long) tmp.get(DB_ID)); if (null != dbObject) { MC.delete(DBObject.class, (Long) dbObject.get(DB_ID)); } } return list; } /** * 批量删除 * * @param collection * @param list * 删除条件列表 */ public void deleteBatch(String collection, List<DBObject> list) { if (list == null || list.isEmpty()) { return; } for (int i = 0; i < list.size(); i++) { // 批量条件删除 delete(collection, list.get(i)); } } /** * 计算集合总条数 * * @param collection */ public int getCount(String collection) { int count = (int) getCollection(collection).find().count(); return count; } /** * 计算知足条件条数 * * @param collection * @param q * 查询条件 */ public long getCount(String collection, DBObject q) { return getCollection(collection).getCount(q); } /** * 更新 * * @param collection * @param q * 查询条件 * @param setFields * 更新对象 * @return List<DBObject> 更新后的对象列表 */ public List<DBObject> update(String collection, DBObject q, DBObject setFields) { getCollection(collection).updateMulti(q, new BasicDBObject("$set", setFields)); List<DBObject> list = find(collection, q); // 遍历 for (DBObject dbObject : list) { // MC 中修改 DBObject tmp = MC.<DBObject> get(DBObject.class, (Long) dbObject.get(DB_ID)); if (null != tmp) { MC.update(dbObject, (Long) tmp.get(DB_ID)); } } return list; } /** * 查找集合全部对象 * * @param collection */ public List<DBObject> findAll(String collection) { List<DBObject> list = getCollection(collection).find().toArray(); return list; } /** * 按顺序查找集合全部对象 * * @param collection * 数据集 * @param orderBy * 排序 */ public List<DBObject> findAll(String collection, DBObject orderBy) { return getCollection(collection).find().sort(orderBy).toArray(); } /** * 查找(返回一个对象) * * @param collection * @param q * 查询条件 */ public DBObject findOne(String collection, DBObject q) { return findOne(collection, q, null); } /** * 查找(返回一个对象) * * @param collection * @param q * 查询条件 * @param fileds * 返回字段 */ public DBObject findOne(String collection, DBObject q, DBObject fields) { if (q.containsField(DB_ID)) {// 若是根据id来查询,先从缓存取数据 DBObject tmp = MC.<DBObject> get(DBObject.class, (Long) q.get(DB_ID)); if (tmp != null) {// 缓存没有数据,从数据库取 if (fields != null) {// 留下须要返回的字段 for (String key : tmp.keySet()) { if (!fields.containsField(key)) { tmp.removeField(key); } } } return tmp; } } return fields == null ? getCollection(collection).findOne(q) : getCollection(collection).findOne(q, fields); } /** * 查找返回特定字段(返回一个List<DBObject>) * * @param collection * @param q * 查询条件 * @param fileds * 返回字段 */ public List<DBObject> findLess(String collection, DBObject q, DBObject fileds) { DBCursor c = getCollection(collection).find(q, fileds); if (c != null) return c.toArray(); else return null; } /** * 查找返回特定字段(返回一个List<DBObject>) * * @param collection * @param q * 查询条件 * @param fileds * 返回字段 * @param orderBy * 排序 */ public List<DBObject> findLess(String collection, DBObject q, DBObject fileds, DBObject orderBy) { DBCursor c = getCollection(collection).find(q, fileds).sort(orderBy); if (c != null) return c.toArray(); else return null; } /** * 分页查找集合对象,返回特定字段 * * @param collection * @param q * 查询条件 * @param fileds * 返回字段 * @pageNo 第n页 * @perPageCount 每页记录数 */ public List<DBObject> findLess(String collection, DBObject q, DBObject fileds, int pageNo, int perPageCount) { return getCollection(collection).find(q, fileds) .skip((pageNo - 1) * perPageCount).limit(perPageCount) .toArray(); } /** * 按顺序分页查找集合对象,返回特定字段 * * @param collection * 集合 * @param q * 查询条件 * @param fileds * 返回字段 * @param orderBy * 排序 * @param pageNo * 第n页 * @param perPageCount * 每页记录数 */ public List<DBObject> findLess(String collection, DBObject q, DBObject fileds, DBObject orderBy, int pageNo, int perPageCount) { return getCollection(collection).find(q, fileds).sort(orderBy) .skip((pageNo - 1) * perPageCount).limit(perPageCount) .toArray(); } /** * 查找(返回一个List<DBObject>) * * @param collection * @param q * 查询条件 */ public List<DBObject> find(String collection, DBObject q) { DBCursor c = getCollection(collection).find(q); if (c != null) return c.toArray(); else return null; } /** * 按顺序查找(返回一个List<DBObject>) * * @param collection * @param q * 查询条件 * @param orderBy * 排序 */ public List<DBObject> find(String collection, DBObject q, DBObject orderBy) { DBCursor c = getCollection(collection).find(q).sort(orderBy); if (c != null) return c.toArray(); else return null; } /** * 分页查找集合对象 * * @param collection * @param q * 查询条件 * @pageNo 第n页 * @perPageCount 每页记录数 */ public List<DBObject> find(String collection, DBObject q, int pageNo, int perPageCount) { return getCollection(collection).find(q) .skip((pageNo - 1) * perPageCount).limit(perPageCount) .toArray(); } /** * 按顺序分页查找集合对象 * * @param collection * 集合 * @param q * 查询条件 * @param orderBy * 排序 * @param pageNo * 第n页 * @param perPageCount * 每页记录数 */ public List<DBObject> find(String collection, DBObject q, DBObject orderBy, int pageNo, int perPageCount) { return getCollection(collection).find(q).sort(orderBy) .skip((pageNo - 1) * perPageCount).limit(perPageCount) .toArray(); } /** * distinct操做 * * @param collection * 集合 * @param field * distinct字段名称 */ public Object[] distinct(String collection, String field) { return getCollection(collection).distinct(field).toArray(); } /** * distinct操做 * * @param collection * 集合 * @param field * distinct字段名称 * @param q * 查询条件 */ public Object[] distinct(String collection, String field, DBObject q) { return getCollection(collection).distinct(field, q).toArray(); } /** * group分组查询操做,返回结果少于10,000keys时可使用 * * @param collection * 集合 * @param key * 分组查询字段 * @param q * 查询条件 * @param reduce * reduce Javascript函数,如:function(obj, * out){out.count++;out.csum=obj.c;} * @param finalize * reduce * function返回结果处理Javascript函数,如:function(out){out.avg=out.csum * /out.count;} */ public BasicDBList group(String collection, DBObject key, DBObject q, DBObject initial, String reduce, String finalize) { return ((BasicDBList) getCollection(collection).group(key, q, initial, reduce, finalize)); } /** * group分组查询操做,返回结果大于10,000keys时可使用 * * @param collection * 集合 * @param map * 映射javascript函数字符串,如:function(){ for(var key in this) { * emit(key,{count:1}) } } * @param reduce * reduce Javascript函数字符串,如:function(key,emits){ total=0; for(var * i in emits){ total+=emits[i].count; } return {count:total}; } * @param q * 分组查询条件 * @param orderBy * 分组查询排序 */ public Iterable<DBObject> mapReduce(String collection, String map, String reduce, DBObject q, DBObject orderBy) { // DBCollection coll = db.getCollection(collection); // MapReduceCommand cmd = new MapReduceCommand(coll, map, reduce, null, // MapReduceCommand.OutputType.INLINE, q); // return coll.mapReduce(cmd).results(); MapReduceOutput out = getCollection(collection).mapReduce(map, reduce, null, q); return out.getOutputCollection().find().sort(orderBy).toArray(); } /** * group分组分页查询操做,返回结果大于10,000keys时可使用 * * @param collection * 集合 * @param map * 映射javascript函数字符串,如:function(){ for(var key in this) { * emit(key,{count:1}) } } * @param reduce * reduce Javascript函数字符串,如:function(key,emits){ total=0; for(var * i in emits){ total+=emits[i].count; } return {count:total}; } * @param q * 分组查询条件 * @param orderBy * 分组查询排序 * @param pageNo * 第n页 * @param perPageCount * 每页记录数 */ public List<DBObject> mapReduce(String collection, String map, String reduce, DBObject q, DBObject orderBy, int pageNo, int perPageCount) { MapReduceOutput out = getCollection(collection).mapReduce(map, reduce, null, q); return out.getOutputCollection().find().sort(orderBy) .skip((pageNo - 1) * perPageCount).limit(perPageCount) .toArray(); } /** * group分组查询操做,返回结果大于10,000keys时可使用 * * @param collection * 集合 * @param map * 映射javascript函数字符串,如:function(){ for(var key in this) { * emit(key,{count:1}) } } * @param reduce * reduce Javascript函数字符串,如:function(key,emits){ total=0; for(var * i in emits){ total+=emits[i].count; } return {count:total}; } * @param outputCollectionName * 输出结果表名称 * @param q * 分组查询条件 * @param orderBy * 分组查询排序 */ public List<DBObject> mapReduce(String collection, String map, String reduce, String outputCollectionName, DBObject q, DBObject orderBy) { if (!db.collectionExists(outputCollectionName)) { getCollection(collection).mapReduce(map, reduce, outputCollectionName, q); } return getCollection(outputCollectionName) .find(null, new BasicDBObject("_id", false)).sort(orderBy) .toArray(); } /** * group分组分页查询操做,返回结果大于10,000keys时可使用 * * @param collection * 集合 * @param map * 映射javascript函数字符串,如:function(){ for(var key in this) { * emit(key,{count:1}) } } * @param reduce * reduce Javascript函数字符串,如:function(key,emits){ total=0; for(var * i in emits){ total+=emits[i].count; } return {count:total}; } * @param outputCollectionName * 输出结果表名称 * @param q * 分组查询条件 * @param orderBy * 分组查询排序 * @param pageNo * 第n页 * @param perPageCount * 每页记录数 */ public List<DBObject> mapReduce(String collection, String map, String reduce, String outputCollectionName, DBObject q, DBObject orderBy, int pageNo, int perPageCount) { if (!db.collectionExists(outputCollectionName)) { getCollection(collection).mapReduce(map, reduce, outputCollectionName, q); } return getCollection(outputCollectionName) .find(null, new BasicDBObject("_id", false)).sort(orderBy) .skip((pageNo - 1) * perPageCount).limit(perPageCount) .toArray(); } /** * @Title: getServerAddress * @Description: 获取数据库服务器列表 * @param dbName * @return * @throws UnknownHostException * @return List<ServerAddress> * @throws */ private static List<ServerAddress> getServerAddress(String dbName) throws UnknownHostException { List<ServerAddress> list = new ArrayList<ServerAddress>(); String hosts = getProperty(CONF_PATH, dbName + ".host"); for (String host : hosts.split("&")) { String ip = host.split(":")[0]; String port = host.split(":")[1]; list.add(new ServerAddress(ip, Integer.parseInt(port))); } return list; } /** * @Title: getMongoCredential * @Description: 获取数据库安全验证信息 * @param dbName * @return * @return List<MongoCredential> * @throws */ private static List<MongoCredential> getMongoCredential(String dbName) { String username = getProperty(CONF_PATH, dbName + ".username"); String password = getProperty(CONF_PATH, dbName + ".password"); String database = getProperty(CONF_PATH, dbName + ".database"); MongoCredential credentials = MongoCredential.createMongoCRCredential( username, database, password.toCharArray()); List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); credentialsList.add(credentials); return credentialsList; } /** * @Title: getDBOptions * @Description: 获取数据参数设置 * @return * @return MongoClientOptions * @throws */ private static MongoClientOptions getDBOptions(String dbName) { MongoClientOptions.Builder build = new MongoClientOptions.Builder(); build.connectionsPerHost(Integer.parseInt(getProperty(CONF_PATH, dbName + ".connectionsPerHost"))); // 与目标数据库可以创建的最大connection数量为50 build.threadsAllowedToBlockForConnectionMultiplier(Integer .parseInt(getProperty(CONF_PATH, dbName + ".threadsAllowedToBlockForConnectionMultiplier"))); // 若是当前全部的connection都在使用中,则每一个connection上能够有50个线程排队等待 build.maxWaitTime(Integer.parseInt(getProperty(CONF_PATH, dbName + ".maxWaitTime"))); build.connectTimeout(Integer.parseInt(getProperty(CONF_PATH, dbName + ".connectTimeout"))); MongoClientOptions myOptions = build.build(); return myOptions; } public static void main(String[] args) { try { // getInstance().insert( // "user", // new BasicDBObject().append("name", "admin3") // .append("type", "2").append("score", 70) // .append("level", 2) // .append("inputTime", new Date().getTime())); // getInstance().update("user", // new BasicDBObject().append("status", 1), // new BasicDBObject().append("status", 2)); // === group start ============= // StringBuilder sb = new StringBuilder(100); // sb.append("function(obj, out){out.count++;out.").append("scoreSum") // .append("+=obj.").append("score").append(";out.") // .append("levelSum").append("+=obj.").append("level") // .append('}'); // String reduce = sb.toString(); // BasicDBList list = getInstance().group( // "user", // new BasicDBObject("type", true), // new BasicDBObject(), // new BasicDBObject().append("count", 0) // .append("scoreSum", 0).append("levelSum", 0) // .append("levelAvg", (Double) 0.0), reduce, // "function(out){ out.levelAvg = out.levelSum / out.count }"); // for (Object o : list) { // DBObject obj = (DBObject) o; // System.out.println(obj); // } // ======= group end========= // === mapreduce start ============= // Iterable<DBObject> list2 = getInstance() // .mapReduce( // "user", // "function(){emit( {type:this.type}, {score:this.score, level:this.level} );}", // "function(key,values){var result={score:0,level:0};var count = 0;values.forEach(function(value){result.score += value.score;result.level += value.level;count++});result.level = result.level / count;return result;}", // new BasicDBObject(), new BasicDBObject("score", 1)); // for (DBObject o : list2) { // System.out.println(o); // } // List<DBObject> list3 = getInstance().mapReduce("user", // "function(){emit({type:this.type},{type:this.type,score:this.score,level:this.level});}", // "function(key,values){var result={type:key.type,score:0,level:0};var count=0;values.forEach(function(value){result.score+=value.score;result.level+=value.level;count++});result.level=result.level/count;return result;}", // "group_temp_user", // new BasicDBObject(), // new BasicDBObject("score",1)); // for (DBObject o : list3) { // System.out.println(o); // } // ======= mapreduce end========= // System.out.print(getInstance().findAll("user")); // System.out.print(getInstance().find( // "user", // new BasicDBObject("inputTime", new BasicDBObject("$gt", // 1348020002890L)), // new BasicDBObject().append("_id", "-1"), 1, 2)); // getInstance().delete("user", new BasicDBObject()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
如下是mongo的链接配置properties文件shell
#ip和端口,多个主机用&相连 db.host=127.0.0.1:27017 #数据库名字 db.database=war #用户名 db.username=root #密码 db.password=123456 #每一个主机的最大链接数 db.connectionsPerHost=50 #线程容许最大等待链接数 db.threadsAllowedToBlockForConnectionMultiplier=50 #链接超时时间1分钟 db.connectTimeout=60000 #一个线程访问数据库的时候,在成功获取到一个可用数据库链接以前的最长等待时间为2分钟 #这里比较危险,若是超过maxWaitTime都没有获取到这个链接的话,该线程就会抛出Exception #故这里设置的maxWaitTime应该足够大,以避免因为排队线程过多形成的数据库访问失败 db.maxWaitTime=120000
DBObject和Javabean之间的转换就容易多了,能够经过json为中介来转换。数据库
public class DBObjectUtil { /** * 把实体bean对象转换成DBObject * * @param bean * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static <T> DBObject bean2DBObject(T bean) { if (bean == null) { return null; } DBObject dbObject = new BasicDBObject(); String json = JsonUtils.objectToJson(bean); dbObject = (DBObject) JSON.parse(json); return dbObject; } /** * 把DBObject转换成bean对象 * * @param dbObject * @param bean * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ @SuppressWarnings("unchecked") public static <T> T dbObject2Bean(DBObject dbObject, T bean) { if (bean == null) { return null; } String json = JSON.serialize(dbObject); bean = (T) JsonUtils.jsonToBean(json, bean.getClass()); return bean; } }
至此,mongo搭建基本完成,更多关于mongo的探索,仍是要在实践中完成,实践是检验真理的惟一标准,nosql现在煊赫一时,但咱们也要保持理性的态度看待问题,传统数据库和nosql究竟谁更胜一筹,不妨咱们都动手试一试,是骡子是马,都拉出来溜溜!以上代码可直接用过工具类,欢迎交流探讨!json