mongodb工具类
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工具类的更多相关文章
- JAVA单例MongoDB工具类
我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用. 没用Spring Data.Morphia等框架是为了减少学习.维护成本,另外自己直接JDBC方式的话可以 ...
- mongoDB工具类以及测试类【java】
java操作mongo工具类 package Utils; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; im ...
- java操作mongodb工具类
新建maven项目 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- 适用于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通用)>,现在重新整理一 ...
- MongoDBDao 工具类(包含分页取数据)
mongdb工具类 package e16wifi.statistic.com.mongodb; import java.util.ArrayList; import java.util.List; ...
- C#封装MongoDB工具类库
什么是MongoDB MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统. 在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB 旨在为WEB应用提供可扩 ...
- 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil
封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置.FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创 ...
- 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,nloglogutil
封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置.FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创 ...
- Spring boot 工具类静态属性注入及多环境配置
由于需要访问MongoDB,但是本地开发环境不能直接连接MongoDB,需要通过SecureCRT使用127.0.0.2本地IP代理.但是程序部署到线上生产环境后,是可以直接访问MongoDB的,因此 ...
随机推荐
- UNITY 画布的粗浅理解
画布:当画布是screen-space overlay时,这个好理解,画布可以控制如分辨率,层次等.但当画布是 world-space时,这个严格来说就不算是一个画布了,屏幕空间或相机空间的画布是先绘 ...
- sql 添加索引强大
以前没有亲自添加过索引,今天添加了一下,果真强大.几百倍的速度提升. SELECT * FROM tbl_sys_menu m WHERE m.SID in (SELECT mr.MENU_SID F ...
- MongoDB数据仓储
本篇是作为另一篇随笔的一部分‘搭建一个Web API项目’ MogonDB官网:https://www.mongodb.org/ 安装过程参考园友的分享http://www.cnblogs.com/l ...
- C#异步编程的一些认识
1.使用委托类型的BeginXXX,EndXXX 2.使用事件 3.使用aysnc,await关键字,会自动切换回UI线程,启动方法的线程可以被重用,线程没有阻塞.内部其实是封闭了Task类的Cont ...
- AutoMapper差异内容备份
公司就得项目用的automapper 是 4.2.1 当时用的方法是:Mapper.CreateMap<source,sourceDto>(); 在最新版 6.0.1 中,这些个方法被删除 ...
- kittle 使用心得
1,字体编码格式: 解析excel表格时,出现乱码,两处修改:1, 2,
- Python面向对象相关知识1
1. python是动态的语言,这样在使用类的时候,类的属性就可以随意的添加,但是这样在实际开发中有一定的缺陷,所以,可以在类中定义一个特殊的__init__()方法,当创建实例时,__init__( ...
- 35. Search Insert Position (Array; Divide-and-Conquer)
Given a sorted array and a target value, return the index if the target is found. If not, return the ...
- shell编程之sed语法
首先插播条广告: 想要进一个文件夹去 看下面有那些文件 必须对这个文件夹有执行权限. sed p 打印对应的行 2p 打印第二行. -n 只输出经过sed 命令处理的行 看图吧 不太会擅长言语 ...
- zabbix结合grafana
一.下载grafana 下载地址: http://docs.grafana.org/installation/rpm/ https://s3-us-west-2.amazonaws.com/grafa ...