pom.xml文件增加Mongodb jar包

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.0</version>
</dependency> <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.3.RELEASE</version>
</dependency>

  src/main/resources下增加mongodb.properties

mongoip=127.0.0.1
mongoport=27017
mongodatabase=VulnSubmit connections_per_host=10
max_wait_time=120000
connect_timeout=0 mongo_user=sysadmin
mongo_pass=simple123456

  Mongodb工具类

package com.vulnverify.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.UUID; import javax.validation.constraints.Null; import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.model.Filters; /**
* MongoDB 工具类
* 方便进行文件的上传与下载
* 共提供上传、下载、删除文件工具类
*
* @author linan
* @since 20170517
*/
public class GeneralMongoDbUtil { private final static Properties PROPERTIES = new Properties();
private final static Logger logger = LoggerFactory.getLogger(GeneralMongoDbUtil.class); static {
try {
URL url = GeneralMongoDbUtil.class.getClassLoader().getResource("mongodb.properties");
if (url != null) {
logger.info("Found 'mongodb.properties' file in local classpath");
InputStream inputStream = url.openStream();
try {
PROPERTIES.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
logger.info("Could not load 'mongo_db.properties' file from local classpath: " + e);
}
} public GeneralMongoDbUtil() {
} private static class Config { /**
* MongoDB connection properties
*/
public static String ip = null;
public static int port = 27017;
public static String database = null; /**
* MongoDB connection pool properties
*/
public static int connectionsPerHost = 10;
public static int maxWaitTime = 120000;
public static int connectTimeout = 0;
public static boolean socketKeepAlive = true;
public static int socketTimeout = 150000; public static MongoClientOptions mongoClientOptions = null; /**
* 用户及凭证
*/
public static List<MongoCredential> credentialList = new ArrayList<MongoCredential>(); static {
ip = PROPERTIES.getProperty("mongoip");
port = Integer.parseInt(PROPERTIES.getProperty("mongoport"));
database = PROPERTIES.getProperty("mongodatabase"); connectionsPerHost = Integer.parseInt(PROPERTIES.getProperty("connections_per_host"));
maxWaitTime = Integer.parseInt(PROPERTIES.getProperty("max_wait_time"));
connectTimeout = Integer.parseInt(PROPERTIES.getProperty("connect_timeout"));
socketKeepAlive = true;
socketTimeout = 150000; mongoClientOptions = MongoClientOptions.builder()
.connectTimeout(connectTimeout)
.maxWaitTime(maxWaitTime)
.connectionsPerHost(connectionsPerHost)
.socketKeepAlive(socketKeepAlive)
.socketTimeout(socketTimeout)
.build(); /**
* 认证与凭证
*
*/
MongoCredential credential = MongoCredential.createCredential(
PROPERTIES.getProperty("mongo_user"), database,
PROPERTIES.getProperty("mongo_pass").toCharArray()); credentialList.add(credential); }
} private static final class MongoInstance {
public final static MongoClient client;
static {
// client = new MongoClient(new ServerAddress(Config.ip,
// Config.port), Config.credentialList, Config.mongoClientOptions);
client = new MongoClient(new ServerAddress(Config.ip, Config.port), Config.mongoClientOptions);
}
} /**
* destroy pool
*/
public static final void destroy() {
MongoInstance.client.close();
} /**
* get a MongoDatabase
*
* @return
*/
public static MongoDatabase getDatabase() {
return MongoInstance.client.getDatabase(Config.database);
} public static MongoDatabase getGridFsDatabase() {
return MongoInstance.client.getDatabase("gridfs");
} /**
* get a MongoDatabase by Name
*
* @param databaseName
* @return
*/
public static MongoDatabase getDatabase(String databaseName) {
return MongoInstance.client.getDatabase(databaseName);
} // //////////////////以下为上传内容////////////////////////////// /**
* 上传文件 到 MongoDB
*
* @param destinationName
* @param inputStream
* @return
*/
public static String uploadFileToGridFS(String destinationName, InputStream inputStream, String bucketName) {
/**
* 缺省桶名是 fs
*/
GridFSBucket bucket = GridFSBuckets.create(getDatabase(), bucketName);
ObjectId fileId = bucket.uploadFromStream(destinationName, inputStream);
return fileId.toHexString();
} /**
* 上传文件 到 MongoDB,可以选择关闭流
*
* @param destinationName
* @param inputStream
* @param close
* @return
*/
public static String uploadFileToGridFS(String destinationName, InputStream inputStream, String bucketName, boolean close) {
String fileId = null;
try {
fileId = uploadFileToGridFS(destinationName, inputStream, bucketName);
} finally {
if (close) {
try {
inputStream.close();
} catch (IOException e) {
logger.info("close inputstream fail:" + e);
}
}
}
return fileId;
} /**
* 上传文件 到 MongoDB,参数为 File
*
* @param destinationName
* @param file
* @return
*/
public static String uploadFileToGridFs(String destinationName, File file, String bucketName) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
String fileId = uploadFileToGridFS(destinationName, inputStream, bucketName, true);
return fileId;
} catch (IOException e) {
logger.info("upload fail:" + e);
}
return null;
} /**
* 上传文件 到 MongoDB,文件名不变上传
*
* @param file
* @return
*/
public static String uploadFileToGridFs(File file, String bucketName) {
return uploadFileToGridFs(file.getName(), file, bucketName);
} /**
* 上传文件 到 MongoDB,文件名加入UUID
*
* @param file
* @return
*/
public static String uploadFileToGridFSByUUID(File file, String bucketName) {
return uploadFileToGridFs(UUID.randomUUID().toString(), file, bucketName);
} // //////////////////以下为下载内容////////////////////////////// /**
* 通过 文件名 从MongoDB 下载文件
*
* @param sourceName
* @param outputStream
*/
public static void downloadFileByName(String sourceName, OutputStream outputStream, String bucketName) {
GridFSBucket bucket = GridFSBuckets.create(getDatabase(), bucketName);
bucket.downloadToStream(sourceName, outputStream); } /**
* 通过 objectid 从MongoDB 下载文件
*
* @param objectId
* @param outputStream
*/
public static void downloadFile(String objectId, OutputStream outputStream, String bucketName) {
/**
* 缺省桶名是 fs
*/
GridFSBucket bucket = GridFSBuckets.create(getDatabase(), bucketName);
bucket.downloadToStream(new ObjectId(objectId), outputStream);
} /**
* 从mongodb获取文件名称
* @param objectId
* @param outputStream
* @param 文件名称
*/
public static String getFileName(String objectId, String bucketName) {
GridFSBucket bucket = GridFSBuckets.create(getDatabase(), bucketName);
String fileName = bucket.find(Filters.eq("_id",new ObjectId(objectId))).first().getFilename();
return fileName;
} /**
* 通过 objectid 从MongoDB 下载文件
*
* @param objectId
* @param outputStream
*/
public static String downloadTaskResultFile(String objectId, OutputStream outputStream) {
/**
* 缺省桶名是 fs
*/
GridFSBucket bucket = GridFSBuckets.create(getGridFsDatabase(), "bucketme");
String fileName = bucket.find(Filters.eq("_id",new ObjectId(objectId))).first().getFilename();
bucket.downloadToStream(new ObjectId(objectId), outputStream);
return fileName;
} /**
* 通过 objectid 从MongoDB 下载文件
*
* @param objectId
* @param destinationFile
*/
public static void downloadFile(String objectId, File destinationFile, String bucketName) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(destinationFile);
downloadFile(objectId, outputStream, bucketName);
} catch (IOException e) {
logger.info("download fail:" + e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.info("close outputstream fail:" + e);
}
}
}
} /**
* 通过 objectid 从MongoDB 下载文件
*
* @param objectId
* @param destinationName
*/
public static void downloadFile(String objectId, String destinationName, String bucketName) {
File destinationFile = new File(destinationName);
downloadFile(objectId, destinationFile, bucketName);
} /**
* 通过 objectId 从MongoDB 删除文件
*
* @param objectId
*/
public static void deleteByObjectId(String objectId, String bucketName) {
GridFSBucket bucket = GridFSBuckets.create(getDatabase(), bucketName);
bucket.delete(new ObjectId(objectId));
} }

  

mongodb工具类的更多相关文章

  1. JAVA单例MongoDB工具类

    我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用. 没用Spring Data.Morphia等框架是为了减少学习.维护成本,另外自己直接JDBC方式的话可以 ...

  2. mongoDB工具类以及测试类【java】

    java操作mongo工具类 package Utils; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; im ...

  3. java操作mongodb工具类

    新建maven项目 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...

  4. 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

    适用于app.config与web.config的ConfigUtil读写工具类   之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...

  5. MongoDBDao 工具类(包含分页取数据)

    mongdb工具类 package e16wifi.statistic.com.mongodb; import java.util.ArrayList; import java.util.List; ...

  6. C#封装MongoDB工具类库

    什么是MongoDB MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统. 在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB 旨在为WEB应用提供可扩 ...

  7. 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil

    封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置.FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创 ...

  8. 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,nloglogutil

    封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置.FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创 ...

  9. Spring boot 工具类静态属性注入及多环境配置

    由于需要访问MongoDB,但是本地开发环境不能直接连接MongoDB,需要通过SecureCRT使用127.0.0.2本地IP代理.但是程序部署到线上生产环境后,是可以直接访问MongoDB的,因此 ...

随机推荐

  1. Spring Boot tomcat参数

    主题 初学SpringBoot,想要配置一下tomcat的端口,以前tomcat直接在它的XML里配置就好了.现在SpringBoot直接继承了,不知道哪里配置.后来找到解决方法,记录一下. 具体方法 ...

  2. C#异步编程的一些认识

    1.使用委托类型的BeginXXX,EndXXX 2.使用事件 3.使用aysnc,await关键字,会自动切换回UI线程,启动方法的线程可以被重用,线程没有阻塞.内部其实是封闭了Task类的Cont ...

  3. MYSQL 存储过程、函数、临时表、游标

    创建函数 因为我们平时经常需要创建不同日期的数据,以模拟的场景,覆盖更多的用例,所以这里写了一个返回随机日期的demo.大家可以自行扩展. DROP FUNCTION IF EXISTS milan_ ...

  4. vue和bootstrap的select控件貌似有冲突?

    貌似vue和bootstrap的select控件会冲突,因为bootstrap的select控件会将option替换为<a>标签,这样就会导致vue渲染失败.(这个问题让我整了一个上午,最 ...

  5. ios野指针的3种常见情况

  6. 让tomcat自动定位到项目

    在servelt.xml中添加粗体部分. <Host name="localhost" appBase="webapps" unpackWARs=&quo ...

  7. 十大基于Docker的开发工具

    http://www.infoq.com/cn/news/2014/08/top-10-open-source-docker FlynnFlynn是一个使用Go语言编写的开源PaaS平台,Flynn使 ...

  8. 2PC之JTA原理与实现

    转自:https://www.ibm.com/developerworks/cn/java/j-lo-jta/index.html 利用 JTA 处理事务 什么是事务处理 事务是计算机应用中不可或缺的 ...

  9. [c++] final override keyword

    the two keyword are aimed at virtual function final final function must be a virtual funtion , final ...

  10. java重载方法的二义性

    http://blog.csdn.net/lavor_zl/article/details/40746813