Mongodb学习笔记(三)

MongoDB学习笔记三:MongoDB集群环境搭建 MongDB学习笔记三:MongDB集群环境搭建标签(空格分隔): MongDB一、集群搭建简介 为什么使用集群架构? 主从:故障转移:无法实现,如果主机宕机,需要关闭slave并且按照master模式启动。无法解决单点故障 无法autofailover 不可以自动主从的切换 为了解决主从的问题,MongDB3.0之后出现副本集,副本集解决了故障转移的问题,但是一个副本集中的 阅读详情
AI摘要

本文详细介绍了一个项目中集成MongoDB的过程,包括配置文件、DAO层实现、文件上传及读取的具体实现等,并通过实例展示了如何使用MongoDB进行数据操作。

这里是ynb中Mongodb的使用:

(1)在pom.xml:

<profiles>
	<!-- ================= Database Profiles ================= -->
	<profile>
		<id>test</id>   
		<activation>
			<activeByDefault>true</activeByDefault>
		</activation>
		<properties>
			<jdbc.url>jdbc:mysql://10.18.96.16:3306/ynb_test?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true</jdbc.url>
			<jdbc.username>njb</jdbc.username>     
			<jdbc.password>njb2015</jdbc.password>
			<mongodb.url>10.18.97.32:27017</mongodb.url>
			<mongodb.dbname>db</mongodb.dbname>
			<mongodb.username/>
			<mongodb.password/>
			<redis.host>10.18.97.32</redis.host>
			<redis.port>6379</redis.port>
			<redis.keyword.ip>10.18.97.32</redis.keyword.ip>
			<redis.keyword.port>6379</redis.keyword.port>
			<zookeeper.ip>10.18.97.32</zookeeper.ip>
			<zookeeper.cliport>2181</zookeeper.cliport>
			....//省略很多组件
		</properties>
	</profile>
</profiles>

<dependencies>
	<dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.12.2</version>
	</dependency>	
	<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.3.0.RELEASE</version>
        </dependency>
</dependencies>

(2)applicationContext-resources.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:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:drools="http://drools.org/schema/drools-spring"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       		http://www.springframework.org/schema/data/mongo	http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
            http://www.springframework.org/schema/aop   
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://drools.org/schema/drools-spring 
		   http://drools.org/schema/drools-spring-1.3.0.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- For mail settings and future properties files -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <value>classpath:hibernate.properties</value>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>

    <!-- JNDI DataSource for J2EE environments -->
    <!--<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/appfuse"/>-->

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
       <!--   <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/> -->
        
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        
        <property name="maxActive" value="350"/>
        <property name="maxWait" value="10000"/>
        <property name="poolPreparedStatements" value="true"/>
        <property name="defaultAutoCommit" value="true"/>
        <property name="validationQuery" value="SELECT 1+1"/>
        <property name="testOnBorrow" value="true"/>
        <property name="filters" value="stat" /> 
        <!--申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 -->
		<property name="testWhileIdle" value="true" />
		<property name="timeBetweenEvictionRunsMillis" value="10000" />
    </bean>

	<bean id="jedisPoolConfig" class="com.eshore.framework.util.JedisPoolConfigWrapper">
		<!--最大连接数 -->
		<property name="maxActive" value="50" />
		<!--最大空闲连接数 -->
		<property name="maxIdle" value="5" />
		<!--初始化连接数 -->
		<property name="minIdle" value="1" />
		<!--最大等待时间 -->
		<property name="maxWait" value="5000" />
		<!--对拿到的connection进行validateObject校验 -->
		<property name="testOnBorrow" value="true" />
		<!--在进行returnObject对返回的connection进行validateObject校验 -->
		<property name="testOnReturn" value="true" />
		<!--定时对线程池中空闲的链接进行validateObject校验 -->
		<property name="testWhileIdle" value="true" />
	</bean>
	
	<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
	     <constructor-arg index="0">
	            <bean factory-bean="jedisPoolConfig" factory-method="getConfig"/>
	     </constructor-arg>
        <constructor-arg index="1" value="${redis.host}"/>
	</bean>
	
    <!-- <mongo:mongo host="${mongodb.url}" port="${mongodb.port}"/> -->
	<mongo:mongo replica-set="${mongodb.url}">
	    <mongo:options
		 connections-per-host="800"
		 threads-allowed-to-block-for-connection-multiplier="5"
		 max-wait-time="7000" 
         connect-timeout="7000" 
		 write-fsync="true"
		 />
	</mongo:mongo>    	
		
	<mongo:db-factory dbname="${mongodb.dbname}" username="${mongodb.username}" password="${mongodb.password}" mongo-ref="mongo" />
     
    <bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />

    <bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
        <constructor-arg name="typeKey"><null /></constructor-arg>
    </bean>
    
    <bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mappingContext" ref="mappingContext" />
        <property name="typeMapper" ref="defaultMongoTypeMapper" />
    </bean>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
    </bean>
    

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>
	<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="classpath:ehcache.xml" p:shared="true"/>
  
</beans>

(3)MongoDBDaoImpl:

package com.eshore.framework.dao.mongodb;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
public class MongoDBDaoImpl implements MongoDBDao {

    Logger log = Logger.getLogger(MongoDBDaoImpl.class);

    private MongoTemplate mongoTemplate;

    @Override
    public List getAll(String collectionName) {
        DB db = mongoTemplate.getDb();
        List list = new ArrayList();
        DBCollection coll = db.getCollection(collectionName);
        DBCursor cursor = coll.find();
        try {
            while (cursor.hasNext()) {
                DBObject object = cursor.next();
                list.add(object);
            }
        } finally {
            cursor.close();
        }
        return list;
    }

    @Override
    public void delete(String collectionName, String id) {
        DB db = mongoTemplate.getDb();
        DBCollection coll = db.getCollection(collectionName);
        coll.remove(new BasicDBObject("_id", new ObjectId(id)));
    }

    @Override
    public DBObject findOne(String collectionName, String id) {
        DB db = mongoTemplate.getDb();
        DBCollection coll = db.getCollection(collectionName);
        return coll.findOne(new BasicDBObject("_id", new ObjectId(id)));
    }

    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }

    @Override
    public List getList(String collectionName, BasicDBObject query,
        PageInfo pageInfo) {
        DB db = mongoTemplate.getDb();
        DBCollection coll = db.getCollection(collectionName);
        if (pageInfo.getSortDirection() == pageInfo.SORT_DIRECTION_DESC) {
            pageInfo.setSortDirection(-1);
        }
        DBCursor cursor = coll.find(query).sort(
            new BasicDBObject(pageInfo.getSortField(), pageInfo
                .getSortDirection()));
        List list = new ArrayList();
        try {
            while (cursor.hasNext()) {
                DBObject object = cursor.next();
                list.add(object);
            }
        } finally {
            cursor.close();
        }
        return list;
    }

    @Override
    public List getAll(String collectionName, BasicDBObject query) {
        DB db = mongoTemplate.getDb();
        List list = new ArrayList();
        DBCollection coll = db.getCollection(collectionName);
        DBCursor cursor = coll.find(query);
        try {
            while (cursor.hasNext()) {
                DBObject object = cursor.next();
                list.add(object);
            }
        } finally {
            cursor.close();
        }
        return list;
    }

}

(3.5)一个使用了MongoDBDao的例子:

 UserLogServiceImpl中:   
 /**
     * 查询用户日志
     *
     * @param requestBean
     * @return
     */
    @Override
    public Page<AppUserLogVo> queryAppUserLogList(AppUserLogRequestBean requestBean, PageInfo pageInfo) {
        if (StringUtils.isBlank(pageInfo.getSortField())) {
            pageInfo.setSortField("operateTime");
            pageInfo.setSortDirection(pageInfo.SORT_DIRECTION_DESC);
        }
        BasicDBObject query = new BasicDBObject();
        List<AppUserLogVo> logVoList = new ArrayList<AppUserLogVo>();

        if (requestBean != null && StringUtils.isNotBlank(requestBean.getMobileNo())) {
            Pattern pattern = Pattern.compile("^.*" + requestBean.getMobileNo() + ".*$", Pattern.CASE_INSENSITIVE);
            query.put("puppetMobileNo", pattern);
        }

        DB db = mongoDBDao.getMongoTemplate().getDb();
        DBCollection coll = db.getCollection(COLLECTION_NAME);
        DBCursor cursor = coll.find(query).skip(pageInfo.getPageNum() * pageInfo.getPageSize()).limit((pageInfo.getPageNum() + 1) * pageInfo.getPageSize());
        if (StringUtils.isNotBlank(pageInfo.getSortField())) {
            cursor.sort(new BasicDBObject(pageInfo.getSortField(), pageInfo.getSortDirection() == pageInfo.SORT_DIRECTION_DESC ? -1 : 1));
        }
        int count = cursor.count();
        try {
            while (cursor.hasNext()) {
                DBObject object = cursor.next();
                AppUserLogVo logListBean = new AppUserLogVo();
                logListBean.setOperateClassName(String.valueOf(object.get("operateClassName")));
                logListBean.setOperateDesc(String.valueOf(object.get("operateDesc")));
                logListBean.setPuppetId(String.valueOf(object.get("puppetId")));
                logListBean.setPuppetType(String.valueOf(object.get("puppetType")));
                logListBean.setOperateIp(String.valueOf(object.get("operateIp")));

                Date d = (Date) object.get("operateTime");
                logListBean.setOperateTime(d);

                logListBean.setOperateAccount(String.valueOf(object.get("operateAccount")));
                logListBean.setOperateId(Integer.parseInt(String.valueOf(object.get("operateId"))));
                logListBean.setOperateData(String.valueOf(object.get("operateData")));
                logListBean.setPuppetMobileNo(String.valueOf(object.get("puppetMobileNo")));
                if (object.get("device") == null) {
                    logListBean.setDevice("管理后台");
                } else {
                    logListBean.setDevice(String.valueOf(object.get("device")));
                }
                logVoList.add(logListBean);
            }
        } finally {
            cursor.close();
        }
        PageImpl<AppUserLogVo> page = new PageImpl<AppUserLogVo>();
        page.setResults(logVoList);
        page.setPageNumber(pageInfo.getPageNum());
        page.setPageSize(pageInfo.getPageSize());
        page.setTotalResults(count);
        return page;
    }

(4)使用GridFS的MongoDBFileDaoImpl:

普通文件系统优点是简单直接,缺点是当规模变大以后难于管理,难以扩展
使用GridFS的话优缺点正好对换,用起来相对复杂,但是当规模变大之后管理和扩展要容易得多

package com.eshore.framework.dao.mongodb;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
public class MongoDBFileDaoImpl implements MongoDBFileDao {

    private MongoTemplate mongoTemplate;

    private static final String COLLECTION_NAME = "uploadFile";
    
    /**
     * @param filename
     *            文件名
     */
    public void removeByFilename(String filename) {
        this.removeByFilename(COLLECTION_NAME, filename);
    }

    /**
     * @param filename
     *            文件名
     */
    public void removeByFilename(String collectionName, String filename) {
        GridFS gridFS = getGridFS(collectionName);
        gridFS.remove(filename);
    }

    /**
     * @param filename
     *            文件名
     */
    @Override
    public MongoDBFile findByFilename(String filename) {
        return this.findByFilename(COLLECTION_NAME, filename);
    }

    /**
     * @param filename
     *            文件名
     * @param collectionName
     *            集合名
     */
    @Override
    public MongoDBFile findByFilename(String collectionName, String filename) {
        MongoDBFile mongoDBFile = null;
        GridFS gridFS = getGridFS(collectionName);
        GridFSDBFile gridFSDBFile = gridFS.findOne(filename);
        if (gridFSDBFile != null) {
            mongoDBFile = new MongoDBFile();
            mongoDBFile.set_id(gridFSDBFile.getId().toString());
            mongoDBFile.setContentType(gridFSDBFile.getContentType());
            mongoDBFile.setFilename(gridFSDBFile.getFilename());
            try {
                mongoDBFile.setBytes(IOUtils.toByteArray(gridFSDBFile
                    .getInputStream()));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
            // mongoDBFile.setInputStream(gridFSDBFile.getInputStream());
        }
        return mongoDBFile;
    }

    /**
     * 存储文件 使用默认集合名
     * 
     * @throws IOException
     */
    @Override
    public void saveFile(MongoDBFile mongoDBFile) throws IOException {
        this.saveFile(COLLECTION_NAME, mongoDBFile);
    }

    /**
     * 存储文件
     * 
     * @param collectionName
     *            集合名 默认以IO流方式存入
     * @throws IOException
     */
    @Override
    public void saveFile(String collectionName, MongoDBFile mongoDBFile)
        throws IOException {
        GridFS gridFS = getGridFS(collectionName);
        GridFSInputFile gfs = null;
        if (mongoDBFile.getBytes() != null) {
            gfs = gridFS.createFile(mongoDBFile.getBytes());
        } else if (mongoDBFile.getInputStream() != null) {
            gfs = gridFS.createFile(mongoDBFile.getInputStream());
        } else {
            gfs = gridFS.createFile(mongoDBFile.getFile());
        }
        if (mongoDBFile.get_id() != null) {
            gfs.put("_id", mongoDBFile.get_id());
        }
        gfs.put("filename", mongoDBFile.getFilename());
        gfs.put("contentType", mongoDBFile.getContentType());
        gfs.save();
    }

    /**
     * 
     * @param collectionName
     *            集合名
     * @return
     */
    public GridFS getGridFS(String collectionName) {
        DB db = mongoTemplate.getDb();
        GridFS gridFS = new GridFS(db, collectionName);
        return gridFS;
    }

    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }

    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

}

(5)MongoDBFileServiceImpl:

package com.eshore.framework.service.impl;

@Service("mongoDBFileService")
@Transactional(readOnly = true)
public class MongoDBFileServiceImpl implements MongoDBFileService {
    static Logger log = Logger.getLogger(MongoDBFileServiceImpl.class);

    @Autowired
    private MongoDBFileBuilder mongoDBFileBuilder;

    @Autowired
    private MongoDBFileDao mongoDBFileDao;

    @Override
    @Transactional(readOnly = false)
    public void removeByFilename(String filename) {
        mongoDBFileDao.removeByFilename(filename);
    }

    @Override
    public void removeByFilename(String collectionName, String filename) {
        // TODO Auto-generated method stub

    }

    @Override
    @Transactional(readOnly = false)
    public MongoDBFileVo findByFilename(String filename) {
        MongoDBFileVo mongoDBFileVo = null;
        try {
            MongoDBFile mongoDBFile = mongoDBFileDao.findByFilename(filename);
            mongoDBFileVo = mongoDBFileBuilder.buildValueObject(mongoDBFile);
        } catch (Exception e) {
            /*
             * // TODO Auto-generated catch block e.printStackTrace();
             */
        }
        return mongoDBFileVo;
    }

    @Override
    public MongoDBFileVo findByFilename(String collectionName, String filename) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    @Transactional(readOnly = false)
    public void saveFile(MongoDBFileVo mongoDBFileVo) throws IOException, BeanValidationException {

       // String startInfo = "调用mongoDBFileService.saveFile开始的时间" + new SimpleDateFormat("yyyyMMddhhmmssms.SSS").format(new Date(System.currentTimeMillis()));
        // log.error(startInfo);

        MongoDBFile mongoDBFile = mongoDBFileBuilder.buildEntity(mongoDBFileVo);
        mongoDBFileDao.saveFile(mongoDBFile);
    }

    @Override
    public void saveFile(String collectionName, MongoDBFileVo mongoDBFileVo) throws IOException, BeanValidationException {
        MongoDBFile mongoDBFile = mongoDBFileBuilder.buildEntity(mongoDBFileVo);
        mongoDBFileDao.saveFile(collectionName, mongoDBFile);

    }

    @Override
    @Transactional(readOnly = false)
    public void saveFile(List<MongoDBFileVo> mongoDBFileVos) throws IOException, BeanValidationException {
        Iterator<MongoDBFileVo> it = mongoDBFileVos.iterator();
        while (it.hasNext()) {
            MongoDBFileVo mongoDBFileVo = it.next();
            saveFile(mongoDBFileVo);
        }
    }
}
(5.5.1)ajax上传用户头像功能(页面代码):

<input type="hidden" id="imgUrl" name="imgUrl" value=""/>
<img class="normalFace" id="uploadimg" name="uploadimg" src="../images/fileUpload.png" onclick="fileSelect();"/>
<input id="appLogoFile" runat="server" name="appLogoFile" type="file" class="validate[required]" style="display:none;"  onchange="uploadInputChanged();"/>

//uploadInputChanged()如下:
function uploadInputChanged(){
	var myfileValue = $("#appLogoFile").val();
	if(!checkImageStyle("appLogoFile")){
		alert("仅支持JPG、JPEG、GIF、PNG格式的图片");
		return;
	}
	if(myfileValue&&myfileValue!=""){
		$.ajaxFileUpload({
	        url: basepath + '/appManager/uploadIcon.do?ajax=true',//用于文件上传的服务器端请求地址
	        type:'post',
	        secureuri:false,//一般设置为false
	        dataType: 'json',//返回值类型 一般设置为json
	        fileElementId:'appLogoFile',//文件上传空间的id属性  <input type="file" id="file" name="file" />
	        success: function (data, status)  //服务器成功响应处理函数
	        {
	        	if(data.fail){
	        		alert(data.fail);
	        	}else{
	        		$("#imgUrl").attr("value",data.imageurl);
	        		//生成预览
		        	<span style="color:#ff0000;">$("#uploadimg").attr("src",contextPath + "/uploadFile/loadImgDataByFileName.do?fileName="+data.imageurl</span>+"&time=" + Date.parse(new Date()));
	        	}
	        },
	        error: function (data, status, e)//服务器响应失败处理函数
	        {
	            alert(e);
	        }
		}
		
		); 
	}
}

//其中检测上传图片格式函数:
function checkImageStyle(divId){
	var uploadFile = document.getElementById(divId).value;
	var subfix = uploadFile.valueOf().toLowerCase();
	var reg=new RegExp(".jpg$|.jpeg$|gif$|png$");
	return reg.test(subfix);
}
(5.5.2)ajax上传用户头像功能(后台代码):

先保存到mongo中,然后返回图片url到前台

@RequestMapping("/uploadIcon")
public void uploadIcon(HttpServletRequest request,
		HttpServletResponse response) {
	response.setCharacterEncoding("utf-8");
	response.setContentType("text/html");
	Date date = new Date();
	MultipartHttpServletRequest multipartRequest = null;
	MultipartFile multipartFile = null;
	try {
		multipartRequest = (MultipartHttpServletRequest) request;
		multipartFile = multipartRequest.getFile("appLogoFile");

		// File newFile = new File(indexbannerpath + "//" +newFilePath);
		// 如果文件大于400K返回错误信息
		if (multipartFile.getSize() > 400 * 1024) {
			JSONObject jsonO = new JSONObject();
			jsonO.put("fail", "头像文件太大了");
			response.getWriter().write(jsonO.toString());
		} else {
			// multipartFile.transferTo(newFile);
			AttachmentVo attachmentVo = new AttachmentVo();
			attachmentVo.setCreateTime(date);
			String extName = multipartFile.getOriginalFilename().substring(
					multipartFile.getOriginalFilename().lastIndexOf("."));
			attachmentVo.setExtName(extName);
			String fileNewName = UUID.randomUUID().toString() + "_"
					+ new SimpleDateFormat("yyyyMMddhhmmssms").format(date);
			attachmentVo.setFileName(fileNewName + extName);
			attachmentVo.setRelativePath(null);
			attachmentVo
					.setOldFileName(multipartFile.getOriginalFilename());
			attachmentVo.setOwnerType("appLogoFile");
			attachmentVo = attachmentService.add(attachmentVo);
			MongoDBFileVo mongoDBFileVo = new MongoDBFileVo();
			mongoDBFileVo.setContentType(attachmentVo.getExtName());
			mongoDBFileVo.setFilename(attachmentVo.getFileName());
			mongoDBFileVo.setBytes(multipartFile.getBytes());
			// mongoDBFileVo.setInputStream(inputStream);
			<span style="color:#ff0000;">mongoDBFileService</span>.saveFile(mongoDBFileVo);
			JSONObject jsonO = new JSONObject();
			jsonO.put(<span style="color:#ff0000;">"imageurl", attachmentVo.getFileName()</span>);
			<span style="color:#ff0000;">response.getWriter().write(jsonO.toString());</span>
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
(5.5.3)ajax上传用户头像功能(页面根据url再调用后台方法生成图片):

/**
 * 用户头像带缓存
 * 
 * @param fileName
 * @param request
 * @param response
 * @throws IOException
 */
@RequestMapping("/loadImgDataByFileName")
public void loadImgDataByFileName(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
	if(fileName==null) {
		return;
	}
    AttachmentVo attachmentVo = attachmentService.getByFileName(fileName);
    MongoDBFileVo  mongoDBFileVo=null;    
    if(attachmentVo!=null && attachmentVo.getFileName()!=null ){
        mongoDBFileVo = mongoDBFileService.findByFilename(attachmentVo.getFileName());
    }else{
        return;
    }
     
    response.setContentType(attachmentVo.getExtName());
    response.setHeader("Cache-Control", "public"); // HTTP/1.1
    response.setHeader("Pragma", "Pragma");
    response.setDateHeader("Expires", System.currentTimeMillis() + 30000000);
    byte[] buffer = mongoDBFileVo.getBytes();
    OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
    toClient.write(buffer);
    toClient.flush();
    toClient.close();
}



mongodb-jdbc mongodb-jdbc mongodb java jdbc驱动 =============== public static void main(String args [])抛出SQLException,ClassNotFoundException {jdbcdriver =“ org.opencloudb.jdbc.mongodb.MongoDriver”; jdbcurl =“ mongodb://192.168.0.99/test”; 字符串username =“ jifeng”; 字符串password =“ jifeng”; Class.forName(jdbcdriver); 连接c = DriverManager.getConnection(jdbcurl,username,password); 语句st = c.createStatement(); prin 立即下载

相关推荐

详解SpringBoot配置连接池

本篇文章主要详解SpringBoot配置连接池,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

Java基于MongoDB Template封装Dao层

mongoDB Template 提供了许多直接操作Mongo的方法, 在此基础上在进行一层封装, 用起来更顺手。使用此封装类, 对实体有要求, 请自行修改。

Best_Lynn的博客 1062

从零到一:AIC8800 USB-WiFi模块在Linux内核6.x下的驱动适配与避坑指南

本文详细介绍了AIC8800 USB-WiFi模块在Linux内核6.x下的驱动适配全流程,包括环境准备、源码编译、内核API变更处理及常见问题解决方案。重点针对驱动适配中的符号导出、设备ID识别和固件加载等核心挑战提供实用指南,帮助开发者高效完成硬件驱动兼容性调试。

k8l9m0n的博客 1028

java mongoclient 连接池_MongoDB -- MongoClient连接池用法

主要的调整在于2.10.0版本中引入了MongoClient类,同时在其API中也说明了Mongo类会在将来的版本中被MongoClient替换(Note: This class has been superseded by MongoClient, and may be deprecated in a future release.)。故在这次调整中,也对原先的MongoDB部分做了相应的修改。...

weixin_35782323的博客 1502

Proteus仿真AT89C51驱动DHT11:温湿度数据采集与LCD1602显示的5个调试坑点总结

本文总结了在Proteus仿真环境下使用AT89C51驱动DHT11温湿度传感器并通过LCD1602显示的5个常见调试坑点,包括DHT11时序问题、LCD1602初始化错误、数据校验失败、仿真特有差异及系统稳定性问题,提供了详细的解决方案和优化代码示例,帮助开发者高效完成温湿度采集项目。

weixin_30335575的博客 356

视觉机器人抓取实战:从物体定位到抓取估计的完整流程解析(附Python代码示例)

本文详细解析了视觉引导机器人抓取的完整技术流程,涵盖从物体定位、位姿估计到抓取估计的核心步骤。通过Python代码示例,演示了如何使用Open3D等工具进行点云处理、平面分割、PCA与ICP位姿估计,以及基于几何启发式的抓取生成方法,为机器人视觉抓取开发提供了清晰的实战指南。

peach的博客 914

Windows系统的Redis安装和简单使用

将requirepass复制在后面修改为自己密码,注意另一个文件夹一样的操作(在此文件夹中可以修改ip地址以及端口号,两个文件夹都是同时修改)或者可以在cmd命令中运行(输入redis-cli.exe -h 127.0.0.1 -p 6379)在cmd中启动的话需要输入redis-cli.exe -h 127.0.0.1 -p 6379。无密码时候:redis-cli.exe -h 127.0.0.1 -p 6379。启动服务:redis-server.exe --service-start。

m0_68384650的博客 273

element的el-cascader组件动态加载,以及报错处理问题

Blocked aria-hidden on an element because its descendant retained focus. The focus must not be hidden from assistive technology users. 报错处理

weixin_56527169的博客 1264

Mysql的JDBC 的常见连接属性

<br /> 在JDBC中,Connection类的创建方式有三种函数(不包括连接池),<br />一是:DriverManager.getConnection(String url),<br />二是:DriverManager.getConnection(String url,String user,String password);<br />三是:DriverManager.getConnection(String url,Properties info);<br /><br />MySQL的JDB

4449

emir分析RC corner如何选择

power analysis阶段 RC corner的选择

weixin_61954252的博客 3595

ComfyUI 局部重绘工作流示例

本文介绍了使用ComfyUI进行图像局部重绘的基础工作流程,重点讲解如何修改人物眼睛颜色和表情。主要内容包括:1.准备工作(可选下载DreamShaperv8模型);2.加载素材图片和工作流文件;3.使用遮罩编辑器绘制需要修改的区域;4.修改提示词控制生成内容;5.调整denoise参数优化效果。教程提供了详细的提示词示例(如"smile,blackeyes"等)和参数设置建议,帮助用户通过多次尝试获得理想效果。该工作流适用于修改图像局部区域而不影响整体画面。

云域A的博客 333

MongoDB学习笔记三

mongo入门;mongo原生使用手册

九离的博客 686

Linux 配置 multipath 多路径

每天一个 DBA 小知识,助你更进一步!

LuciferLiu_DBA 3299

MongoDB学习笔记(三)

5 一些基本操作 #添加内嵌文档 db.users.update{{username:"master"},{$set:{hobby:{cities:["beijing","shanghai","shenzhen"],movies:["marvel","DC"]}}}} #查询内嵌文档属性,属性需要加引号,值可以为数组里的值 db.users.find({"hobby.movies":"marve...

vincent_nkcs的博客 251

YOLOv8改进 | 主干网络 | 增加网络结构增强小目标检测能力【独家创新——附结构图】

YOLOv8改进,小目标检测,yolov8

kay_545 6021

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

MongoDB学习笔记(三)使用Spring Data操作MongoDB

1.所需的包: 2.代码: (1)配置文件一:bootstrap.xml //代码开始     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLoca

Lnho的专栏 2602

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Mongodb学习笔记(三)

   sharding(分片功能)     手动分片:所有数据库都支持,但是需要应用程序自行维护连接、存储和查询,难以维护和处理。     自动分片:集群自动分切数据存储、查询,自行负载均衡,对所有应用都是透明。mongodb支持自动分片功能     mongodb分片的基本思想是将集合切分成小块,这些块分散到若干片里面,每个片只负责总数据的一部分,但这些对应用程序是透明的,一切由...

我思故我在 192

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

MongoDB 学习笔记三 术语概念

MongoDB 学习笔记三 术语概念数据库文档(Document)集合合法的集合名元数据MongoDB 数据类型ObjectId字符串时间戳日期 不管我们学习什么数据库都应该学习其中的基础概念,在 MongoDB 中基本的概念是文档、集合、数据库、下面我们来介绍: 下表将帮助你更容易理解 MongoDB 中的一些概念: SQL术语/概念 MongoDB术语/概念 解释/说明 databas...

人在囧途的博客 473

MongoDB 学习笔记三 JAVA调用MongoDB

驱动https://github.com/mongodb/mongo-java-driver http://central.maven.org/maven2/org/mongodb/mongo-java-driver/连接Mongo mongo = new Mongo(); DB db = mongo.getDB(“test”);

猿来这样-谢厂节的博客 9128

MongoDb学习笔记三 MongoDB and PyMongo

英文原文:http://api.mongodb.org/python/current/tutorial.html 翻译的不好还请大家见谅,呵呵,翻译也是一种学习,当你翻译过后,基本上也就了解了,好了不废话了,见译文,如下: 本文主要是做为MongoDb的python客户端使用

学习、思考、分享 4888

Mongodb使用学习笔记(三)

graph LR flowchat st=>start:开始 e=>end:结束 sub1=>operation: 初始化参数 sub2=>operation: 编译 sub3=>operation: 模块编译 sub4=>operation: 完成编译 sub5=>operation: 输出文件 st->sub1->sub2->sub3->sub4->sub5->e ...

daxiandan的博客 1290

MongoDB学习笔记<三>

MongoDb学习笔记<三>

小齐的笔记本 854

MongoDB学习笔记《三》

这一次做一些基本的操作增删改查操作 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MongoDbTestPrint { public class Student { private int _ID;

萌萌的It人 www.itmmd.com 869

MONGO学习笔记(三、MongoDB CURD)

MONGO学习笔记(三、MongoDB CURD) MongoDB的语法和传统关系型数据库语法不同,它调用的是JavaScript提供的API接口。例如: 添加数据 单行数据插入(insert) use appdb db.book.insert({ title: 'my first book', publishedData : new Date(), tags: [ 'MongoDB', 'nosql' ], favCount: 25, author: 'zale' , }

qq_39069111的博客 562

MongoDB学习笔记(三) 聚合

在数据库的实际应用中,我们常常需要使用聚合操作帮助我们处理数据,对数据进行统计和整理 这篇文章我们将会学习如何在 MongoDB 中使用聚合操作

半虹小站 440
上一篇: Mongodb学习笔记(二)
下一篇: Redis学习笔记(一)
sd4422739
博客等级 码龄15年 7粉丝 12原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值