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的,因此 ...
随机推荐
- AngularJS1.6版本中ui-router路由中/#!/的解决方法 - zhuan
本地编译出的文件可以正常运行,但是服务器编译后到了测试那里路由上就莫名的出现了/#!/,这导致了很多问题. 后来查了下是服务器编译器把AngularJS升级到了1.6版本,而我本地的依旧是1.5. 但 ...
- 配置python的豆瓣source
sunny@sunny-ThinkPad-T450:~$ mkdir ~/.pip sunny@sunny-ThinkPad-T450:~$ gedit ~/.pip/pip.conf [global ...
- fdsf
https://blog.csdn.net/chen_2890/article/details/83757022Elasticsearch环境搭建和介绍(Windows) https://blog.c ...
- #if (DEBUG)
//DEBUG必须大写,其它是不认的#if (DEBUG) Console.WriteLine("Debug");#else Conso ...
- java算法 第七届 蓝桥杯B组(题+答案) 8.四平方和
8.四平方和 (程序设计) 四平方和定理,又称为拉格朗日定理:每个正整数都可以表示为至多4个正整数的平方和.如果把0包括进去,就正好可以表示为4个数的平方和. 比如:5 = 0^2 + 0^2 + ...
- SpringBoot自定义拦截器实现
1.编写拦截器实现类,此类必须实现接口 HandlerInterceptor,然后重写里面需要的三个比较常用的方法,实现自己的业务逻辑代码 如:OneInterceptor package com ...
- Redis初学笔记
1.官网概述 Redis is an open source (BSD licensed), in-memory data structure store, used as database, cac ...
- Perl语言编程>>学习笔记2
1. Perl中变量的常用表示 ${var} 相当于 $var $Dog::days 在Dog包里面的变量$days $#days @days 的最后一个索引 ] $days 引用的数组 ...
- python 中面向对象编程简单总结2
1.python中继承的特点: (1)总是从一个类继承,默认为object类 (2)不要忘记调用super.__init__方法来初始化父类的方法 def __init__(self,args): s ...
- 【转载】Jedis对管道、事务以及Watch的操作详细解析
转载地址:http://blog.csdn.net/liyantianmin/article/details/51613772 1.Pipeline 利用pipeline的方式从client打包多条命 ...