import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.types.ObjectId;
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;
public class Test {
private MongoDatabase database = null;
public static void main(String[] args) throws Exception {
Test t=new Test();
String ID = t.insertMedicalFile("测试一下1.txt", "fjkasdhfkjhdaslfhklahflasdhlhflk");
String selectMedicalFileByObjectId = t.selectMedicalFileByObjectId("5c91ec501a551431b07eff28");
String selectMedicalFileByFileName = t.selectMedicalFileByFileName("测试一下1.txt");
}
/**
* 向 IMAGE_FILE 中写入文件记录。
* @param fileName 文件名
* @param xmlContent 文件内容。
* @throws Exception
*/
public String insertMedicalFile(String fileName , String xmlContent) throws Exception{
MongoDatabase mds = null;
mds = getMdbOperator();
InputStream inputStream = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
//业务逻辑模式
GridFSBucket gridFSBucket = GridFSBuckets.create(mds,"IMAGE_FILE");
ObjectId objectId = gridFSBucket.uploadFromStream(fileName, inputStream);
System.out.println("HUC 生成的 objectId = " + objectId);
inputStream.close();
return objectId+"" ;
}
/**
* 根据文件id返回文件内容
* @param objectId
* @return
*/
public String selectMedicalFileByObjectId(String objectId){
String result = "" ;
try {
MongoDatabase mds = null;
mds = getMdbOperator();
GridFSBucket gridFSBucket = GridFSBuckets.create(mds,"IMAGE_FILE");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
gridFSBucket.downloadToStream(new ObjectId(objectId), baos);
result = baos.toString("UTF-8");
} catch (Exception e) {
result = "" ; //此处可能会报异常错误,异常错误的原因是 上面 downloadToStream 为空。
e.printStackTrace();
}
return result ;
}
/**
* 根据文件名返回文件内容
* @param fileName
* @return
*/
public String selectMedicalFileByFileName(String fileName){
String result = "" ;
try {
MongoDatabase mds = null;
mds = getMdbOperator();
GridFSBucket gridFSBucket = GridFSBuckets.create(mds,"IMAGE_FILE");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
gridFSBucket.downloadToStream(fileName, baos);
result = baos.toString("UTF-8");
} catch (Exception e) {
result = "" ; //此处可能会报异常错误,异常错误的原因是 上面 downloadToStream 为空。
e.printStackTrace();
}
return result ;
}
/**
* 获得链接
*
* @return
*/
public MongoDatabase getMdbOperator() {
try {
MongoClient mongoClient = getMongoClient();
if (mongoClient != null) {
CodecProvider pojoCodecProvider = PojoCodecProvider.builder()
.automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(
MongoClient.getDefaultCodecRegistry(),
fromProviders(pojoCodecProvider));
database = mongoClient.getDatabase("HUC")
.withCodecRegistry(pojoCodecRegistry);
return database;
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static MongoClient getMongoClient() throws Exception {
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
// 与目标数据库能够建立的最大connection数量为200,当连接池被用光时,会被阻塞住
build.connectionsPerHost(200);
// 如果当前所有的connection都在使用中,则每个connection上可以有100个线程排队等待
build.threadsAllowedToBlockForConnectionMultiplier(100);
/*
* 一个线程访问数据库的时候,在成功获取到一个可用数据库连接之前的最长等待时间为2分钟
* 这里比较危险,如果超过maxWaitTime都没有获取到这个连接的话,该线程就会抛出Exception
* 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败
*/
build.maxWaitTime(1000 * 60 * 2); // 这个就是Server Selection
// Timeout?
build.connectTimeout(1000 * 60 * 1); // 与数据库建立连接的timeout设置为1分钟
build.socketTimeout(10 * 1000); // 发送请求和接收请求的超时时间
MongoClientOptions myOptions = build.build();
// 创建链接
MongoCredential credential = MongoCredential.createCredential(
"admin", "HUC", "123456".toCharArray());
List addresses = new ArrayList();
//mongoDB集群地址
addresses.add(new ServerAddress("192.168.220.130", 27017));
addresses.add(new ServerAddress("192.168.220.128", 27017));
addresses.add(new ServerAddress("192.168.220.129", 27017));
return new MongoClient(addresses,credential,myOptions);
}
}
java将字符串存入GridF并通过id或文件名查询
点赞
收藏