SpringBoot: 异步controller

一、定义异步线程类:

package cn.edu.tju.controller;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AsyncTask implements Runnable {
    private HttpServletResponse response;
    private AsyncContext asyncContext;

    public AsyncTask(HttpServletResponse response,AsyncContext asyncContext) {
        this.response = response;
        this.asyncContext=asyncContext;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(20000);
            PrintWriter out = response.getWriter();
            out.write("have to...");
            out.flush();
            out.close();
            asyncContext.complete();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

二、定义异步响应的controller

package cn.edu.tju.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class AsyncController {
    @RequestMapping("/async")
    public void async(String info, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AsyncContext asyncContext = request.startAsync();
        //asyncContext.setTimeout(2000L);
        //默认超时时间30秒
        //System.out.println(asyncContext.getTimeout());
        AsyncTask asyncTask=new AsyncTask(response,asyncContext);
        new Thread(asyncTask).start();


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个名为“知识管理系统”的JAVA毕业设计项目,基于Spring Boot框架和MySQL数据库。该项目旨在帮助用户管理和分享知识,提高学习效率。以下是关于该项目的500字资源介绍:项目结构:本项目采用经典的MVC(Model-View-Controller)架构,分为前端、后端和数据库三个部分。前端使用HTML、CSS和JavaScript进行页面设计和交互实现;后端使用Spring Boot框架进行业务逻辑处理;数据库使用MySQL存储数据。功能模块:本项目主要包括以下几个功能模块:用户管理:包括用户注册、登录、修改密码等功能。分类管理:用户可以创建、编辑、删除分类,以便对知识进行归类。文章管理:用户可以发布、编辑、删除文章,同时支持文章的点赞、评论等功能。搜索功能:用户可以通过关键词搜索相关的文章和分类。数据统计:对用户、分类、文章等数据进行统计分析,以便了解系统的运行情况。技术特点:本项目采用了以下技术特点:使用Spring Boot框架,简化了项目的配置和部署过程,提高了开发效率。使用MyBatis作为持久层框架,实现了与MySQL数据库的高效交互。使用Thymeleaf模板引擎,实现了前后端分离,提高了页面渲染性能。使用Bootstrap框架进行前端页面设计,使页面具有良好的响应式效果。使用Ajax技术实现异步数据交互,提高了用户体验。应用场景:本项目适用于学校、企业、团队等场景,帮助用户管理和分享知识,提高工作效率。总之,这个项目是一个功能完善、技术先进的知识管理系统,可以帮助你快速搭建一个知识分享平台。通过学习和实践这个项目,你可以掌握Spring Boot框架、MySQL数据库以及前后端分离等技术,为你的JAVA开发技能提升打下坚实的基础。
springboot学习笔记 spring基础 Spring概述 Spring的简史 xml配置 注解配置 java配置 Spring概述 Spring的模块 核心容器CoreContainer Spring-Core Spring-Beans Spring-Context Spring-Context-Support Spring-Expression AOP Spring-AOP Spring-Aspects Messaging Spring-Messaging WEB Spring-Web Spring-Webmvc Spring-WebSocket Spring-Webmvc-Portlet 数据访问/集成(DataAccess/Intefration) Spring-JDBC Spring-TX Spring-ORM Spring-OXM Spring-JMS Spring的生态 Spring Boot Spring XD Spring Cloud Spring Data Spring Integration Spring Batch Spring Security Spring HATEOAS Spring Social Spring AMQP Spring Mobile Spring for Android Spring Web Flow Spring Web Services Spring LDAP Spring Session Spring项目快速搭建 Maven简介 Maven安装 Maven的pom.xml dependencies dependency 变量定义 编译插件 Spring项目的搭建 Spring Tool Suite https://spring.io/tools/sts/all IntelliJ IDEA NetBeans https://netbeans.org/downloads/ Spring基础配置 依赖注入 声明Bean的注解 @Component组件,没有明确的角色 @Service在业务逻辑层(service层) @Repository在数据访问层(dao层) @Controller在展现层(MVC→SpringMVC) 注入Bean的注解 @Autowired:Spring提供的注解 @Inject:JSR-330提供的注解 @Resource:JSR-250提供的注解 Java配置 @Configuration声明当前类是一个配置类 @Bean注解在方法上,声明当前方法的返回值为一个Bean AOP @Aspect 声明是一个切面 拦截规则@After @Before @Around PointCut JoinPoint Spring常用配置 Bean的Scope Singleton Prototype Request Session GlobalSession SpringEL和资源调用 注入普通字符 注入操作系统属性 注入表达式云算结果 注入其他Bean的属性 注入文件内容 注入网址内容 注入属性文件 Bean的初始化和销毁 Java配置方式 注解方式 Profile @Profile 通过设定jvm的spring.profiles.active参数 web项目设置在Servlet的context parameter中 事件Application Event 自定义事件,集成ApplicationEvent 定义事件监听器,实现ApplicationListener 使用容器发布事件 Spring高级话题 Spring Aware BeanNameAware BeanFactoryAware
要实现Spring Boot中Controller异步大文件下载,可以使用Servlet 3.0中的异步特性。 首先,在Controller中定义一个异步方法,使用HttpServletResponse将文件流写回客户端。具体代码如下: ```java @GetMapping("/download") public void download(HttpServletResponse response) throws Exception { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=file.zip"); AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(0); asyncContext.start(() -> { try { OutputStream outputStream = response.getOutputStream(); InputStream inputStream = new FileInputStream(new File("path/to/large/file")); IOUtils.copy(inputStream, outputStream); outputStream.flush(); asyncContext.complete(); } catch (Exception e) { asyncContext.complete(); throw new RuntimeException(e); } }); } ``` 在上面的代码中,我们使用AsyncContext启动一个异步线程,将文件流写回客户端。同时,我们需要设置异步超时时间为0,以避免Servlet容器默认的超时时间限制。 另外,我们使用了Apache Commons IO库中的IOUtils.copy方法,将输入流复制到输出流中。 最后,需要注意的是,由于文件下载是一个比较耗时的操作,因此建议将下载请求交给专门的线程池进行处理,以避免阻塞其他请求。可以使用Spring Boot提供的@Async注解将方法标记为异步方法,并配置线程池参数。 ```java @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(100); executor.setThreadNamePrefix("async-download-"); executor.initialize(); return executor; } } ``` 在上面的代码中,我们配置了一个线程池,核心线程数为10,最大线程数为20,队列容量为100,线程名前缀为async-download-。这样,每个下载请求都会由一个线程处理,避免了阻塞其他请求的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值