LemonSnm 2016-09-09
Datastore接口把Java对象保存到MongoDB或从MongoDB中访问Java对象提供了安全类型的方法。它提供了get/find/save/delete方法为你操作Java对象。
来看代码吧。
配置文件xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="order" value="1" /> <property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="locations"> <list> <value>classpath:demo-provider-module.properties</value> </list> </property> </bean> <!-- writeConcern --> <bean id="writeConcern" class="com.mongodb.WriteConcern"> <!-- 对应全局的WriteConcern中的w,默认为0 --> <constructor-arg name="w" value="0" /> <!-- 对应全局的WriteConcern中的wtimeout,默认为0 --> <constructor-arg name="wTimeoutMS" value="0" /> <!-- 对应全局的WriteConcern.FSYNC_SAFE,如果为真,每次写入要等待写入磁盘,默认为false --> <constructor-arg name="fsync" value="false" /> <!-- 对应全局的WriteConcern.JOURNAL_SAFE,如果为真,每次写入要等待日志文件写入磁盘,默认为false --> <constructor-arg name="journal" value="false" /> </bean> <bean id="mongoClientOption" class="demo.dcn.mongodb.MongoClientOption"> <property name="minConnectionsPerHost" value="50" /> <property name="maxConnectionsPerHost" value="200" /> <property name="threadsAllowedToBlockForConnectionMultiplier" value="20" /> <property name="maxWaitTime" value="12000" /> <property name="maxConnectionIdleTime" value="0" /> <property name="maxConnectionLifeTime" value="0" /> <property name="connectTimeout" value="3000" /> <property name="socketTimeout" value="60000" /> <property name="socketKeepAlive" value="true" /> <property name="writeConcern" ref="writeConcern" /> </bean> <!-- 使用工厂创建mongo实例 --> <bean id="mongo" class="demo.dcn.mongodb.MongoFactoryBean"> <!-- mongoDB的配置对象 --> <property name="mongoOption" ref="mongoClientOption"/> <!-- 是否主从分离(读取从库),默认为false,读写都在主库 --> <!-- <property name="readSecondary" value="true" /> --> <!-- 设定写策略,默认为WriteConcern.SAFE,优先级高于mongoOptions中的safe --> <property name="writeConcern" value="SAFE" /> <!-- 设定服务器列表,默认为localhost:27017 --> <property name="serverStrings"> <array> <value>${mongo.db.host_master}</value> <!-- <value>${mongo.db.host_salve}</value> --> </array> </property> <!-- 设定认证参数列表,默认为空 --> <!-- <property name="credentialStrings"> <array> <value>${mongo.db.credential_1}</value> </array> </property> --> </bean> <!-- 使用工厂创建morphia实例,同时完成类映射操作 --> <bean id="morphia" class="demo.dcn.mongodb.MorphiaFactoryBean"> <!-- 指定要扫描的POJO包路径 --> <property name="mapPackages"> <array> <value>demo.dcn.mongodb.vo</value> </array> </property> </bean> <!-- 使用工厂创建datastore,同时完成index和caps的确认操作 --> <bean id="datastore" class="demo.dcn.mongodb.DataStoreFactoryBean"> <property name="morphia" ref="morphia" /> <property name="mongo" ref="mongo" /> <property name="dbName" value="${mongo.db.databaseName_1}" /> <!-- 是否进行index和caps的确认操作,默认为flase --> <property name="toEnsureIndexes" value="true" /><!-- 是否确认索引存在,默认false --> <property name="toEnsureCaps" value="true" /><!-- 是否确认caps存在,默认false --> </bean> </beans>
dataStoreFactoryBean工厂指定数据连接获取mongo,marphiadb对象。
package demo.dcn.mongodb; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; import org.springframework.beans.factory.config.AbstractFactoryBean; import com.mongodb.MongoClient; public class DataStoreFactoryBean extends AbstractFactoryBean<Datastore> { 代码: ...(支持java, ruby, js, xml, html, php, python, c, c++, c#, sql)
privateMorphiamorphia;//morphia实例,最好是单例
privateMongoClientmongo;//mongo实例,最好是单例
privateStringdbName;//数据库名
privatebooleantoEnsureIndexes=false;//是否确认索引存在,默认false
privatebooleantoEnsureCaps=false;//是否确认caps存在,默认false
@Override
protectedDatastorecreateInstance()throwsException{
Datastoreds=morphia.createDatastore(mongo,dbName);
if(toEnsureIndexes){
ds.ensureIndexes();
}
if(toEnsureCaps){
ds.ensureCaps();
}
returnds;
}
@Override
publicClass<?>getObjectType(){
returnDatastore.class;
}
@Override
publicvoidafterPropertiesSet()throwsException{
super.afterPropertiesSet();
if(mongo==null){
thrownewIllegalStateException("mongoisnotset");
}
if(morphia==null){
thrownewIllegalStateException("morphiaisnotset");
}
}
/*----------------------setters-----------------------*/
publicMorphiagetMorphia(){
returnmorphia;
}
publicvoidsetMorphia(Morphiamorphia){
this.morphia=morphia;
}
publicMongoClientgetMongo(){
returnmongo;
}
publicvoidsetMongo(MongoClientmongo){
this.mongo=mongo;
}
publicStringgetDbName(){
returndbName;
}
publicvoidsetDbName(StringdbName){
this.dbName=dbName;
}
publicbooleanisToEnsureIndexes(){
returntoEnsureIndexes;
}
publicvoidsetToEnsureIndexes(booleantoEnsureIndexes){
this.toEnsureIndexes=toEnsureIndexes;
}
publicbooleanisToEnsureCaps(){
returntoEnsureCaps;
}
publicvoidsetToEnsureCaps(booleantoEnsureCaps){
this.toEnsureCaps=toEnsureCaps;
}
}
MongoClientOptionmongodb连接对象参数设定。
package demo.dcn.mongodb; import javax.net.SocketFactory; import org.bson.codecs.configuration.CodecRegistry; import com.mongodb.DBDecoderFactory; import com.mongodb.DBEncoderFactory; import com.mongodb.DefaultDBDecoder; import com.mongodb.DefaultDBEncoder; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientOptions.Builder; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; public class MongoClientOption { private String description; private ReadPreference readPreference = ReadPreference.primary();//读写分离 private WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED;//write concern 来让用户自己衡量性能和写安全 Acknowledged 中等级别,能够拿到mongodb返回的信息。默认是这个设置 private CodecRegistry codecRegistry = MongoClient.getDefaultCodecRegistry(); private int minConnectionsPerHost; private int maxConnectionsPerHost = 100; //最大的连接数 private int threadsAllowedToBlockForConnectionMultiplier = 5;//线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。 private int serverSelectionTimeout = 1000 * 30; private int maxWaitTime = 1000 * 60 * 2;//最大等待连接的线程阻塞时间2分钟 private int maxConnectionIdleTime; private int maxConnectionLifeTime;//最大连接存活数 private int connectTimeout = 1000 * 10;//连接超时的毫秒。0是默认和无限 private int socketTimeout = 0;//socket超时。0是默认和无限 private boolean socketKeepAlive = false; private boolean sslEnabled = false; private boolean sslInvalidHostNameAllowed = false; private boolean alwaysUseMBeans = false; private int heartbeatFrequency = 10000; private int minHeartbeatFrequency = 500; private int heartbeatConnectTimeout = 20000; private int heartbeatSocketTimeout = 20000; private int localThreshold = 15; private boolean autoConnectRetry = true;//是否自动连接 private String requiredReplicaSetName; private DBDecoderFactory dbDecoderFactory = DefaultDBDecoder.FACTORY;//Mongo Java驱动程序配置 private DBEncoderFactory dbEncoderFactory = DefaultDBEncoder.FACTORY;//mongo java 编码工厂 private SocketFactory socketFactory = SocketFactory.getDefault();//socket 工厂 private boolean cursorFinalizerEnabled = true; public void setDescription(String description) { this.description = description; } public void setReadPreference(ReadPreference readPreference) { this.readPreference = readPreference; } public void setWriteConcern(WriteConcern writeConcern) { this.writeConcern = writeConcern; } public void setCodecRegistry(CodecRegistry codecRegistry) { this.codecRegistry = codecRegistry; } public void setMinConnectionsPerHost(int minConnectionsPerHost) { this.minConnectionsPerHost = minConnectionsPerHost; } public void setMaxConnectionsPerHost(int maxConnectionsPerHost) { this.maxConnectionsPerHost = maxConnectionsPerHost; } public void setThreadsAllowedToBlockForConnectionMultiplier(int threadsAllowedToBlockForConnectionMultiplier) { this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; } public void setServerSelectionTimeout(int serverSelectionTimeout) { this.serverSelectionTimeout = serverSelectionTimeout; } public void setMaxWaitTime(int maxWaitTime) { this.maxWaitTime = maxWaitTime; } public void setMaxConnectionIdleTime(int maxConnectionIdleTime) { this.maxConnectionIdleTime = maxConnectionIdleTime; } public void setMaxConnectionLifeTime(int maxConnectionLifeTime) { this.maxConnectionLifeTime = maxConnectionLifeTime; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public void setSocketKeepAlive(boolean socketKeepAlive) { this.socketKeepAlive = socketKeepAlive; } public void setSslEnabled(boolean sslEnabled) { this.sslEnabled = sslEnabled; } public void setSslInvalidHostNameAllowed(boolean sslInvalidHostNameAllowed) { this.sslInvalidHostNameAllowed = sslInvalidHostNameAllowed; } public void setAlwaysUseMBeans(boolean alwaysUseMBeans) { this.alwaysUseMBeans = alwaysUseMBeans; } public void setHeartbeatFrequency(int heartbeatFrequency) { this.heartbeatFrequency = heartbeatFrequency; } public void setMinHeartbeatFrequency(int minHeartbeatFrequency) { this.minHeartbeatFrequency = minHeartbeatFrequency; } public void setHeartbeatConnectTimeout(int heartbeatConnectTimeout) { this.heartbeatConnectTimeout = heartbeatConnectTimeout; } public void setHeartbeatSocketTimeout(int heartbeatSocketTimeout) { this.heartbeatSocketTimeout = heartbeatSocketTimeout; } public void setLocalThreshold(int localThreshold) { this.localThreshold = localThreshold; } public void setRequiredReplicaSetName(String requiredReplicaSetName) { this.requiredReplicaSetName = requiredReplicaSetName; } public void setDbDecoderFactory(DBDecoderFactory dbDecoderFactory) { this.dbDecoderFactory = dbDecoderFactory; } public void setDbEncoderFactory(DBEncoderFactory dbEncoderFactory) { this.dbEncoderFactory = dbEncoderFactory; } public void setSocketFactory(SocketFactory socketFactory) { this.socketFactory = socketFactory; } public void setCursorFinalizerEnabled(boolean cursorFinalizerEnabled) { this.cursorFinalizerEnabled = cursorFinalizerEnabled; } public MongoClientOptions getMongoClientOptions() { Builder builder = MongoClientOptions.builder(); builder.connectionsPerHost(maxConnectionsPerHost); builder.connectTimeout(connectTimeout); builder.description(description); builder.heartbeatConnectTimeout(heartbeatConnectTimeout); builder.heartbeatSocketTimeout(heartbeatSocketTimeout); builder.localThreshold(localThreshold); builder.maxConnectionIdleTime(maxConnectionIdleTime); builder.maxConnectionLifeTime(maxConnectionLifeTime); builder.minConnectionsPerHost(minConnectionsPerHost); builder.minHeartbeatFrequency(minHeartbeatFrequency); builder.readPreference(readPreference); builder.requiredReplicaSetName(requiredReplicaSetName); builder.serverSelectionTimeout(serverSelectionTimeout); builder.alwaysUseMBeans(alwaysUseMBeans); builder.socketFactory(socketFactory); builder.socketKeepAlive(socketKeepAlive); builder.sslEnabled(sslEnabled); builder.sslInvalidHostNameAllowed(sslInvalidHostNameAllowed); builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier); builder.writeConcern(writeConcern); builder.codecRegistry(codecRegistry); builder.maxWaitTime(maxWaitTime); builder.socketTimeout(socketTimeout); builder.heartbeatFrequency(heartbeatFrequency); builder.dbDecoderFactory(dbDecoderFactory); builder.dbEncoderFactory(dbEncoderFactory); builder.cursorFinalizerEnabled(cursorFinalizerEnabled); return builder.build(); } public boolean isAutoConnectRetry() { return autoConnectRetry; } public void setAutoConnectRetry(boolean autoConnectRetry) { this.autoConnectRetry = autoConnectRetry; } }
MongoFactoryBeanmongodb初始化工厂:
package demo.dcn.mongodb; import com.mongodb.*; import org.springframework.beans.factory.config.AbstractFactoryBean; import java.util.ArrayList; import java.util.List; public class MongoFactoryBean extends AbstractFactoryBean<Mongo> { // 表示服务器列表(主从复制或者分片)的字符串数组 private String[] serverStrings; // 表示认证参数 private String[] credentialStrings; // mongoDB配置对象 private MongoClientOption mongoOption; // 是否主从分离(读取从库),默认读写都在主库 private boolean readSecondary = false; // 设定写策略(出错时是否抛异常),默认采用SAFE模式(需要抛异常) @SuppressWarnings("deprecation") private WriteConcern writeConcern = WriteConcern.SAFE; @Override public Class<?> getObjectType() { return Mongo.class; } @Override protected Mongo createInstance() throws Exception { Mongo mongo = initMongo(); // 设定主从分离 if (readSecondary) { mongo.setReadPreference(ReadPreference.secondaryPreferred()); } // 设定写策略 mongo.setWriteConcern(writeConcern); return mongo; } /** * 初始化mongo实例 * * @return * @throws Exception */ private MongoClient initMongo() throws Exception { // 根据条件创建Mongo实例 MongoClient mongo = null; List<ServerAddress> serverList = getServerList(); List<MongoCredential> credentialsList = getCredentialsList(); MongoClientOptions mongoOptions = mongoOption.getMongoClientOptions(); if (serverList.size() == 0) { mongo = new MongoClient(); } else if (serverList.size() == 1) { if (null != mongoOptions) { if (credentialsList.size() == 0) { mongo = new MongoClient(serverList.get(0), mongoOptions); } else { mongo = new MongoClient(serverList.get(0), credentialsList, mongoOptions); } } else { if (credentialsList.size() == 0) { mongo = new MongoClient(serverList.get(0)); } else { mongo = new MongoClient(serverList.get(0), credentialsList); } } } else { if (null != mongoOptions) { if (credentialsList.size() == 0) { mongo = new MongoClient(serverList, mongoOptions); } else { mongo = new MongoClient(serverList, credentialsList, mongoOptions); } } else { if (credentialsList.size() == 0) { mongo = new MongoClient(serverList); } else { mongo = new MongoClient(serverList, credentialsList); } } } return mongo; } /** * 根据服务器字符串列表,解析出服务器对象列表 * <p/> * * @return * @throws Exception * @Title: getServerList * </p> */ private List<ServerAddress> getServerList() throws Exception { List<ServerAddress> serverList = new ArrayList<ServerAddress>(); try { for (String serverString : serverStrings) { String[] temp = serverString.split(":"); String host = temp[0]; if (temp.length > 2) { throw new IllegalArgumentException( "Invalid server address string: " + serverString); } if (temp.length == 2) { serverList.add(new ServerAddress(host, Integer .parseInt(temp[1]))); } else { serverList.add(new ServerAddress(host)); } } return serverList; } catch (Exception e) { throw new Exception( "Error while converting serverString to ServerAddressList", e); } } /** * 根据服务器认证字符串列表,解析出服务器认证对象列表 * <p/> * * @return * @throws Exception * @Title: getCredentialList * </p> */ private List<MongoCredential> getCredentialsList() throws Exception { List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); try { if(null != credentialStrings) { for (String credentialString : credentialStrings) { String[] temp = credentialString.split(":"); String database = temp[0]; if (temp.length > 3) { throw new IllegalArgumentException( "Invalid credential param string: " + credentialString); } if (temp.length == 3) { MongoCredential credential = MongoCredential.createCredential(temp[1], database, temp[2].toCharArray()); credentialsList.add(credential); } else { throw new IllegalArgumentException( "Invalid credential param string: " + credentialString); } } } return credentialsList; } catch (Exception e) { throw new Exception( "Error while converting credentialString to MongoCredentialsList", e); } } public String[] getServerStrings() { return serverStrings; } public void setServerStrings(String[] serverStrings) { this.serverStrings = serverStrings; } public String[] getCredentialStrings() { return credentialStrings; } public void setCredentialStrings(String[] credentialStrings) { this.credentialStrings = credentialStrings; } public boolean isReadSecondary() { return readSecondary; } public MongoClientOption getMongoOption() { return mongoOption; } public void setMongoOption(MongoClientOption mongoOption) { this.mongoOption = mongoOption; } public void setReadSecondary(boolean readSecondary) { this.readSecondary = readSecondary; } public WriteConcern getWriteConcern() { return writeConcern; } public void setWriteConcern(WriteConcern writeConcern) { this.writeConcern = writeConcern; } /* ------------------- setters --------------------- */ }
MorphiaFactoryBean映射工厂实列:
package demo.dcn.mongodb; import org.mongodb.morphia.Morphia; import org.springframework.beans.factory.config.AbstractFactoryBean; public class MorphiaFactoryBean extends AbstractFactoryBean<Morphia> { /** * 要扫描并映射的包 */ private String[] mapPackages; /** * 要映射的类 */ private String[] mapClasses; /** * 扫描包时,是否忽略不映射的类 这里按照Morphia的原始定义,默认设为false */ private boolean ignoreInvalidClasses; /** * 映射Morphia实列 */ @Override protected Morphia createInstance() throws Exception { Morphia m = new Morphia(); if (mapPackages != null) { for (String packageName : mapPackages) { m.mapPackage(packageName, ignoreInvalidClasses); } } if (mapClasses != null) { for (String entityClass : mapClasses) { m.map(Class.forName(entityClass)); } } return m; } @Override public Class<?> getObjectType() { return Morphia.class; } public String[] getMapPackages() { return mapPackages; } public void setMapPackages(String[] mapPackages) { this.mapPackages = mapPackages; } public String[] getMapClasses() { return mapClasses; } public void setMapClasses(String[] mapClasses) { this.mapClasses = mapClasses; } public boolean isIgnoreInvalidClasses() { return ignoreInvalidClasses; } public void setIgnoreInvalidClasses(boolean ignoreInvalidClasses) { this.ignoreInvalidClasses = ignoreInvalidClasses; } /*----------------------setters-----------------------*/ }
这里自己没有搭建集群分片,读写目前用的一个mongodb数据库。另外可以MongoVUE管理工具,比较好用。当然命令用习惯了,用命令也是一样。下载地址:http://www.baidu.com/link?url=IF-yXcmW-RgoE2hPr4kNGoPwSIkRljqJhPR_gOuEwZPloaUsI9V-t-iMTFN8eAQR
mongodb下载地址:https://www.mongodb.com/download-center安装搭建什么的比较简单。百度一下都有啦。这里就不做介绍了。基本环境算是搭建起来了。现在用下morphia的增删改查方法吧。
package demo.dcn.mongodb.service; import demo.dcn.mongodb.vo.LookerMongodb; import demo.dcn.mongodb.vo.TestMongodb; import demo.dcn.service.utils.demoExceptionUtil; import demo.dcn.type.ResultMap; /** * 测试mongodb服务 * @author [email protected] */ public interface TestRemoteService { /** * 保存收货人地址 * @param mongodb * @return */ public abstract ResultMap saveTestMongodb(TestMongodb mongodb); /** * 保存looker 号 * @param lookerMongodb * @return */ public abstract ResultMap saveLooker(LookerMongodb lookerMongodb); /** * 通过Id 查询 对象 * @param id * @return * @throws demoExceptionUtil */ public abstract TestMongodb findTestMongodbById(Long id) throws demoExceptionUtil; /** * 更新测试 testMongodb * @param mongodb * @return * @throws demoExceptionUtil */ public abstract void updateMongodb(TestMongodb mongodb) throws demoExceptionUtil; /** * 删除测试testMongodb * @param id * @return * @throws demoExceptionUtil */ public abstract ResultMap delMongodb(Long id) throws demoExceptionUtil; }
package demo.dcn.mongodb.serviceImpl; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import redis.clients.jedis.ShardedJedisPipeline; import com.google.common.collect.Maps; import demo.dcn.cache.JedisUtil; import demo.dcn.cache.RedisClientBase; import demo.dcn.common.RedisKey.TEST_MONGODB_CACHE; import demo.dcn.mongodb.dao.TestMongodbDAO; import demo.dcn.mongodb.service.TestRemoteService; import demo.dcn.mongodb.vo.LookerMongodb; import demo.dcn.mongodb.vo.TestMongodb; import demo.dcn.service.utils.demoExceptionUtil; import demo.dcn.type.ResultMap; @Service public class TestRemoteServiceImpl implements TestRemoteService { private final Logger logger = LoggerFactory.getLogger(TestRemoteServiceImpl.class); @Autowired @Qualifier("redisClientBase") private RedisClientBase redisClientBase; @Autowired private TestMongodbDAO testMongodbDAO; @Override public ResultMap saveTestMongodb(TestMongodb mongodb) { ResultMap resultMap = ResultMap.SUCCESS; try{ if(mongodb!=null){ Integer a = testMongodbDAO.addTestMongodb(mongodb); System.out.println(a); } }catch(Exception e){ resultMap =ResultMap.FAILURE; logger.error(e.getMessage(), e); } return resultMap; } @Override public ResultMap saveLooker(LookerMongodb lookerMongodb) { ResultMap resultMap = ResultMap.SUCCESS; try{ if(lookerMongodb!=null){ Integer a = testMongodbDAO.addLookerMongodb(lookerMongodb); System.out.println(a); } }catch(Exception e){ resultMap =ResultMap.FAILURE; logger.error(e.getMessage(), e); } return resultMap; } @Override public TestMongodb findTestMongodbById(Long id) throws demoExceptionUtil { TestMongodb testMongodb= null; try{ String redisKey = String.format(TEST_MONGODB_CACHE.keyformat, id); String json = redisClientBase.getString(redisKey);//redis 连接已经封装好了,用完了会自动关闭 ShardedJedisPipeline jedisPipeline = redisClientBase.getShardedJedis().getShardedJedis().pipelined(); testMongodb = JedisUtil.toObject(json, TestMongodb.class);//将json 转换成testMongodb 对象反序列化 if(testMongodb==null){//如果缓存为空 testMongodb = testMongodbDAO.findTestMongod(id); if(testMongodb!=null){//存入缓存 String jsonMongodb = JedisUtil.toJson(testMongodb);//序列化 redisClientBase.setnx(redisKey, jsonMongodb); redisClientBase.expire(redisKey, TEST_MONGODB_CACHE.expire);//设置key的过期时间 } } }catch(Exception e){ logger.error(e.getMessage(),e); throw new demoExceptionUtil("查询错误",e); } return testMongodb; } @Override public void updateMongodb(TestMongodb mongodb) throws demoExceptionUtil { try{ Map<String,Object> map = Maps.newHashMap(); String redisKey = String.format(TEST_MONGODB_CACHE.keyformat, mongodb.getLid()); map.put("lid", mongodb.getLid()); map.put("name", mongodb.getName()); map.put("list", mongodb.getList()); map.put("createTime", mongodb.getCreateTime()); testMongodbDAO.UpdateTestMongodb(map); redisClientBase.del(redisKey);//删除缓存 }catch(Exception e){ logger.error(e.getMessage(),e); throw new demoExceptionUtil("跟新错误",e); } } @Override public ResultMap delMongodb(Long id) throws demoExceptionUtil { ResultMap resultMap = ResultMap.SUCCESS; try{ String redisKey = String.format(TEST_MONGODB_CACHE.keyformat, id); Integer n = testMongodbDAO.delTestMongodb(id); System.out.println(n); redisClientBase.del(redisKey); }catch(Exception e){ logger.error(e.getMessage(),e); resultMap = ResultMap.FAILURE; throw new demoExceptionUtil("跟新错误",e); } return resultMap; } }
package demo.dcn.mongodb.dao.impl; import java.util.Map; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.dao.BasicDAO; import org.mongodb.morphia.query.Query; import org.mongodb.morphia.query.UpdateOperations; import org.mongodb.morphia.query.UpdateResults; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import com.google.common.base.Preconditions; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.WriteConcern; import com.mongodb.WriteResult; import demo.dcn.mongodb.dao.TestMongodbDAO; import demo.dcn.mongodb.mapper.TestMongodbMapper; import demo.dcn.mongodb.vo.LookerMongodb; import demo.dcn.mongodb.vo.TestMongodb; @Repository public class TestMongodbDAOImpl extends BasicDAO<TestMongodb, String> implements TestMongodbDAO { @Autowired public TestMongodbDAOImpl(@Qualifier("datastore")Datastore ds) {//注入数据源 super(ds); } @Override public Integer addTestMongodb(TestMongodb mongodb) { Query<TestMongodb> query = createQuery().field(TestMongodbMapper.LOOKER_ID).equal(mongodb.getLid()); query.filter(TestMongodbMapper.LIST, mongodb.getList()); UpdateOperations<TestMongodb> option = createUpdateOperations().set(TestMongodbMapper.LOOKER_NAME, mongodb.getName()); UpdateResults u = getDs().update(query, option, true); if(u.getInsertedCount()>0) { return u.getInsertedCount(); } return 0; } @Override public Integer addLookerMongodb(LookerMongodb lookerMongodb) { ds.save("LookerMongodb", lookerMongodb); return 1; } @Override public TestMongodb findTestMongod(Long id) { Preconditions.checkNotNull(id); Query<TestMongodb> query = createQuery().field(TestMongodbMapper.LOOKER_ID).equal(id); TestMongodb mongodb = findOne(query); return mongodb; } @Override public void UpdateTestMongodb(Map<String, Object> map) { DBCollection collection = getDs().getDB().getCollection("TEST_MONGODB"); BasicDBObject queryObj = new BasicDBObject(); queryObj.put(TestMongodbMapper.LOOKER_ID, map.get("lid")); BasicDBObject filedObj=new BasicDBObject(map); BasicDBObject update=new BasicDBObject(); update.put("$set", filedObj); collection.update(queryObj, update, true, false, WriteConcern.SAFE);//第一个true 表示 是否upsert=true, 找到这一行就 修改,没有就追加 为false 没有就不追加 第二false当找到多个只更新一个。 } @Override public int delTestMongodb(Long id) { Query<TestMongodb> query = createQuery().field(TestMongodbMapper.LOOKER_ID).equal(id); WriteResult wr = deleteByQuery(query); int n = wr.getN(); if (n > 0) { return n; } return 0; } }
package demo.dcn.mongodb.vo; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.bson.types.ObjectId; import org.mongodb.morphia.annotations.Embedded; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Id; @Entity(value="TEST_MONGODB",noClassnameStored=true) public class TestMongodb implements Serializable { private static final long serialVersionUID = 1L; @Id private ObjectId id; private Long lid; private Long createTime; /** * @return the lid */ public Long getLid() { return lid; } /** * @param lid the lid to set */ public void setLid(Long lid) { this.lid = lid; } private String name; @Embedded private List<Address> list = new ArrayList<Address>(); /** * @return the id */ public ObjectId getId() { return id; } /** * @param id the id to set */ public void setId(ObjectId id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the list */ public List<Address> getList() { return list; } /** * @param list the list to set */ public void setList(List<Address> list) { this.list = list; } /** * @return the createTime */ public Long getCreateTime() { return createTime; } /** * @param createTime the createTime to set */ public void setCreateTime(Long createTime) { this.createTime = createTime; } public TestMongodb() { super(); } }
package demo.dcn.mongodb.vo; import java.io.Serializable; import org.mongodb.morphia.annotations.Embedded; @Embedded public class Address implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; private String address; private String iphone; private Integer defAdd;//是否是默认地址 0 表示不是,1 表示是 /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the address */ public String getAddress() { return address; } /** * @param address the address to set */ public void setAddress(String address) { this.address = address; } /** * @return the iphone */ public String getIphone() { return iphone; } /** * @param iphone the iphone to set */ public void setIphone(String iphone) { this.iphone = iphone; } /** * @return the defAdd */ public Integer getDefAdd() { return defAdd; } /** * @param defAdd the defAdd to set */ public void setDefAdd(Integer defAdd) { this.defAdd = defAdd; } }
package demo.dcn.common; /** * redis key标准格式类 * @author [email protected] */ public interface RedisKey { interface TEST_MONGODB_CACHE{ String keyprefix ="test:mongodb";//前缀 String keyformat =keyprefix+"%s";//后缀 int expire = 60 * 60 * 24;//缓存存活时间1天 } }
package demo.dcn.mongodb.mapper; public class TestMongodbMapper { public static final String LOOKER_ID ="lid";//looker_id public static final String LOOKER_NAME = "name"; public static final String CREATE_TIME = "createTime";//创建时间 public static final String LIST = "list";//收货地址 public static final String MONGODB ="mongodb";//对象 public static final String ID = "id";//id唯一标识 }
import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.bson.types.ObjectId; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.mysql.fabric.xmlrpc.base.Array; import demo.dcn.cache.JedisUtil; import demo.dcn.cache.RedisClientBase; import demo.dcn.mongodb.service.TestRemoteService; import demo.dcn.mongodb.vo.Address; import demo.dcn.mongodb.vo.LookerMongodb; import demo.dcn.mongodb.vo.TestMongodb; import demo.dcn.redis.service.RegisterService; import demo.dcn.service.utils.UuidUtils; import demo.dcn.service.utils.demoExceptionUtil; import demo.dcn.service.utils.security.Md5Util; import demo.dcn.type.ResultMap; import demo.dcn.vo.Looker; import demo.dcn.vo.LookerSalt; /** * 测试 * @author [email protected] * * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={ "classpath*:config/demo-spring-context.xml", "classpath*:config/demo-spring-datasource.xml", "classpath*:config/demo-spring-redis.xml", "classpath*:config/demo-sql-config.xml", "classpath*:config/demo-spring-mongodb.xml" }) public class test { @Autowired private RegisterService registerService; @Autowired @Qualifier("redisClientBase") private RedisClientBase redisClientBase; @Autowired private TestRemoteService testRemoteService; @Test public void testMongoDB(){ TestMongodb mongodb = new TestMongodb(); List<Address> addList = new ArrayList<Address>(); Address address = new Address(); address.setName("坤坤"); address.setIphone("18123074271"); address.setDefAdd(0); address.setAddress("成都市天府大道天府新区1"); addList.add(address); mongodb.setLid(103456987L); mongodb.setName("坤坤3"); mongodb.setList(addList); ResultMap map = testRemoteService.saveTestMongodb(mongodb); System.out.println(map.getDesc()); } //@Test public void testLookerMongodb(){ LookerMongodb lookerMongodb = new LookerMongodb(); List<Address> addList = new ArrayList<Address>(); Address address = new Address(); address.setName("坤坤"); address.setIphone("18123074271"); address.setDefAdd(0); address.setAddress("成都市天府大道天府新区"); addList.add(address); lookerMongodb.setLid(123698745l); lookerMongodb.setLevel(1); lookerMongodb.setName("萧萧"); lookerMongodb.setAddList(addList); ResultMap map =testRemoteService.saveLooker(lookerMongodb); System.out.println(map.getDesc()); } @Test public void testFindMongodb() throws demoExceptionUtil{ TestMongodb mongodb =testRemoteService.findTestMongodbById(103456987L); if(mongodb!=null){ System.out.println(mongodb.getName()); System.out.println(mongodb.getLid()); } } @Test public void testUpdateMongodb() throws demoExceptionUtil{ TestMongodb mongodb = new TestMongodb(); List<Address> addList = new ArrayList<Address>(); Address address = new Address(); address.setName("坤坤1"); address.setIphone("18123074271"); address.setDefAdd(0); address.setAddress("成都市天府大道天府新区1"); addList.add(address); mongodb.setLid(103456987L); mongodb.setName("坤坤2"); mongodb.setList(addList); testRemoteService.updateMongodb(mongodb); } @Test public void testDelMongodb() throws demoExceptionUtil{ ResultMap map =testRemoteService.delMongodb(103456987l); System.out.println(map.getDesc()); } }
这里自己用的缓存,和一些工具类的使用,结合公司的一些写法。封装了了一下公共类的使用。如果需要搭建框架的朋友直接那过去用吧