Java实现http大文件流读取并批量插入数据库-
时间:2022-06-09 作者:chenn
1、概述
- 请求远程大文本,使用流的方式进行返回。需要设置http链接的超时时间
- 循环插入到List中,使用mybatis-plus批量插入到mysql中
2、需求
- 两台服务器
- 大文件放到其中一台服务器上
- 另外一台服务器以文件流的形式请求数据
- 批量插入到数据库中
3、实现思路
主要包括几个技术点:文件流提供;大文件数据读取;批量插入到数据库
1、文件流提供
使用springboot提供静态文件
域名ic-locations=file:/home/finance/h5/
2、大文件数据读取
设置HttpURLConnection的超时时间
3、批量插入数据库
使用mybtis-plus的批量插入,自定义sql
1000条分批次插入
4、代码
1、大文件数据读取
public String doGet(String httpurl) {
TestModel model=new TestModel();
List<TestModel> list=new ArrayList<>();
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) 域名Connection();
// 设置连接方式:get
域名equestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
域名onnectTimeout(150000000);
// 设置读取远程返回的数据时间:60000毫秒
域名eadTimeout(600000000);
// 发送请求
域名ect();
// 通过connection连接,获取输入流
if (域名esponseCode() == 200) {
is = 域名nputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放数据
String temp = null;
int i=0;
while ((temp = 域名Line()) != null) {
if (i>0&&i % 1000 ==0){
域名rtBatch(list);//批量导入
list=new ArrayList<>();
}
model=new TestModel();
域名d(域名eOf(i++));
域名ontent(temp);
域名reatedTime(域名());
域名(model);
}
}
} catch (MalformedURLException e) {
域名tStackTrace();
} catch (IOException e) {
域名tStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
域名e();
} catch (IOException e) {
域名tStackTrace();
}
}
if (null != is) {
try {
域名e();
} catch (IOException e) {
域名tStackTrace();
}
}
域名onnect();// 关闭远程连接
}
return result;
}
2、批量插入
1、controller
@GetMapping("/addtmp")
public void addtmp() {
String url = "http://域名.16:8081/域名";
long startTime = 域名entTimeMillis();//获取开始时间
域名t(url);
long endTime = 域名entTimeMillis();//获取结束时间
域名tln("测试代码块共耗时" + ((endTime - startTime)/1000) + "秒");//输出程序运行时间
TestModel model=new TestModel();
域名d("00000000000000000000001");
域名ontent("测试代码块共耗时" + ((endTime - startTime)/1000) + "秒");
域名reatedTime(域名());
域名(model);
}
2、mapper
@Repository
@Mapper
public interface TestMapper extends BaseMapper<TestModel> {
@Insert("<script>" +
"INSERT INTO tmp_chenn_test(id,content,createdTime)VALUES" +
"<foreach collection=\'testList\' item=\'testModel\' separator=\',\'> " +
"(#{域名},#{域名ent},#{域名tedTime})" +
"</foreach> " +
"</script>")//
boolean insertBatch(List<TestModel> testList);
}