当前位置: 首页 > news >正文

网站用access做数据库吗国家免费技能培训

网站用access做数据库吗,国家免费技能培训,网站建设费的摊销年限,如何用word做网站JVM是支持多线程程序的,当程序需要同时执行两个或多个任务,实现一些需要等待的任务时,如用户输入、文件读写、网络操作、搜索等多线程程序比单线程程序更具优势,可充分利用CPU资源,完成时间更短,提高应用程…

JVM是支持多线程程序的,当程序需要同时执行两个或多个任务,实现一些需要等待的任务时,如用户输入、文件读写、网络操作、搜索等多线程程序比单线程程序更具优势,可充分利用CPU资源,完成时间更短,提高应用程序的响应,增强用户体验。因此学会改善程序结构,将即长又复杂的进程分为多个线程,独立去运行,对于开发者来说至关重要。

以下载多个文件为例,如何使用多线程机制,高效率的完成下载任务?且听我我慢慢道来。

提出需求:编写一个API,打包下载GitHub的所有用户头像(以zip形式返回所有用户头像)。

在这里插入图片描述

文件压缩我们统一使用apache的commons-compress相关类进行压缩,因此需要引入相关的依赖

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.24.0</version>
</dependency>

完整代码:

/*** TODO** @Description* @Author laizhenghua* @Date 2023/8/31 09:22**/
@RestController
@SpringBootApplication
public class TestApplication {public static void main(String[] args) {SpringApplication.run(TestApplication.class, args);}@Autowiredprivate ServletContext servletContext;@GetMapping("/test")public void test() {ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletResponse response = servletRequestAttributes.getResponse();RestTemplate restTemplate = new RestTemplate();String usersUrl = "https://api.github.com/users";// 查询github用户信息JSONArray userList = restTemplate.getForObject(usersUrl, JSONArray.class);if (CollectionUtils.isEmpty(userList)) {fallback("下载失败,失败原因: 查询为空", response);return;}// 下载路径准备String rootPath = servletContext.getRealPath("/") + "avatars";File root = new File(rootPath);if (!root.exists()) {root.mkdir();}// 初始化线程池(JDK 5.0新增的线程池API更多知识可自行学习)ExecutorService executorService = Executors.newFixedThreadPool(10);userList.forEach(item -> {JSONObject user = new JSONObject((Map)item);String login = user.getString("login"); // github登录名String downloadUrl = user.getString("avatar_url"); // 头像下载地址String filePath = rootPath + File.separator + login + ".png";// 执行下载任务(下载至本地)// ****** 一个线程处理一个用户(主线程只负责提交任务尽可能把耗时逻辑都放到多线程任务里如下载、IO操作等) ******executorService.execute(() -> {try {File file = new File(filePath);boolean newFile = file.createNewFile();if (!newFile) {return;}String name = Thread.currentThread().getName();String log = String.format("[%s] download start --- download path: %s", name, filePath);System.out.println(log);// 调用下载接口获取输入流程ResponseEntity<Resource> responseEntity = restTemplate.getForEntity(downloadUrl, Resource.class);// 将得到的输入流写入文件InputStream inputStream = null;OutputStream outputStream = null;try {inputStream = Objects.requireNonNull(responseEntity.getBody()).getInputStream();outputStream = new FileOutputStream(file);byte[] buffer = new byte[1024];int len;while ((len = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {IOUtils.close(inputStream);IOUtils.close(outputStream);}} catch (IOException e) {e.printStackTrace();}});});// 关闭线程池executorService.shutdown();// 使用org.apache.commons类压缩下载好的头像ZipArchiveOutputStream zipAos = null;try {// 等待线程池中所有任务执行完成(指定时间内没有执行完则返回false)boolean allTaskCompleted = executorService.awaitTermination(30, TimeUnit.MINUTES);if (!allTaskCompleted) {fallback("下载失败", response);}// 设置下载信息response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("github_avatar.zip", "utf-8") + "\"");response.setContentType("application/zip");zipAos = new ZipArchiveOutputStream(response.getOutputStream());zipAos.setEncoding("UTF-8");zipAos.setUseZip64(Zip64Mode.AsNeeded);File[] files = root.listFiles(); // 获取所有下载好的头像assert files != null;for (File file : files) {// 将头像压缩至 github_avatar.zip 文件ZipArchiveEntry entry = new ZipArchiveEntry(file, file.getName());entry.setLastModifiedTime(FileTime.fromMillis(file.lastModified()));zipAos.putArchiveEntry(entry);try (InputStream inputStream = new FileInputStream(file)) {byte[] buffer = new byte[1024];int len;while ((len = inputStream.read(buffer)) != -1) {zipAos.write(buffer, 0, len);}file.delete(); // 删除文件}}zipAos.closeArchiveEntry();} catch (Exception e) {e.printStackTrace();} finally {IOUtils.close(zipAos);}}private void fallback(String message, HttpServletResponse response) {response.setCharacterEncoding("UTF-8");response.setContentType(MediaType.APPLICATION_JSON_VALUE);PrintWriter writer = null;try {R error = R.error(500, message);JSONObject json = new JSONObject(error);writer = response.getWriter();writer.append(json.toString());} catch (IOException e) {e.printStackTrace();} finally {if (writer != null) {writer.close();}}}
}

对于打包下载,我们可以用单线程,也可以用多线程,处理这种任务多线程的优势就体现出来了,可自行对比下单线程和多线程程序响应速度。

在这里插入图片描述

使用多线程需要注意的是:

  1. Executors.newFixedThreadPool()是创建一个可重用固定线程数量的线程池。
  2. 主线程只负责分配任务,把耗时的逻辑尽可能的写到多线程任务上独立执行。
  3. 使用完线程池必须要关闭,先调用 shutdown() 方法关闭线程池,然后调用 awaitTermination(long timeout, TimeUnit unit) 方法等待线程池中的所有任务执行完成,只有线程池中的所有任务都执行完了,才能把响应信息写到response上。
http://www.hengruixuexiao.com/news/8136.html

相关文章:

  • 网站 被攻击_主业篡改 被黑了 织梦做的站河北seo基础
  • 手机网站建设品牌百度云盘登录入口
  • 南充市房地产网官方网站近几年的网络营销案例
  • 怎么用ps做网站首页图片企业品牌推广网站
  • 做相册视频的网站百度账号登录中心
  • 自己家的电脑宽带50m做网站服务器百度关键词排名
  • 网站怎么做支付接口图片外链在线生成网址
  • 网站建设 网站设计站长工具seo综合查询下载
  • 网站域名骗子企业网站建设报价表
  • 怎么在网站中做视频背景福州专业的seo软件
  • 重庆玻璃制作厂家武汉seo培训
  • 武汉有做夺宝网站的吗百度官网下载电脑版
  • 计算机网站开发与技术专业介绍宁德市地图
  • 免费空间访客100个网站百度seo在线优化
  • 网站界面设计有哪些网站排名怎么优化
  • 毕业设计做网站还是系统好石家庄百度推广排名优化
  • 电子商务网站建设试卷.doc推广计划怎么做推广是什么
  • 关于建网站做淘宝联盟专业的网络推广
  • ppt做的比较好的网站专业培训心得体会
  • 网站建设和网络推广外包百度发布
  • 网站pv怎么统计关键词网站查询
  • vs2008 做网站seo优化平台
  • destoon b2b 网站名称无法修改怎么自己做一个网址
  • 北京公司注册虚拟地址广告优化
  • 做电商网站报价怎样才能在百度上面做广告宣传
  • 营销型网站免费模板下载今日重大事件
  • 为企业做网站企业网站推广的方法
  • 南通公司做网站网络营销的几种模式
  • 做订单管理网站用什么软件云推广
  • 网页和网站区别推广普通话心得体会