Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

spring boot controller实现接收到请求之后 每隔1秒输出一个内容

  1. User

    spring boot controller实现接收到请求之后 每隔1秒输出一个内容

  2. Assistant

    为了实现每隔1秒输出一个内容,你可以创建一个基于Spring Boot的RESTful API Web服务。以下是一个简单的实现:

    1. 首先,确保你在pom.xml文件中添加了spring-boot-starter-web依赖:
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    1. 创建一个Spring Boot Web应用主类Application.java:
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    
    1. 创建一个名为SampleController.java的控制器类,如下所示:
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import java.io.OutputStream;
    import javax.servlet.http.HttpServletResponse;
    
    @RestController
    public class SampleController {
    
        @GetMapping("/stream")
        public void stream(HttpServletResponse response) {
            response.setContentType("text/plain");
            response.addHeader("Transfer-Encoding", "chunked");
            response.addHeader("Cache-Control", "no-cache");
    
            try (OutputStream os = response.getOutputStream()) {
                for (int i = 0; i < 10; i++) {
                    String message = "Output [" + (i + 1) + "]\n";
                    os.write(message.getBytes());
                    os.flush();
    
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (IOException e) {
                throw new RuntimeException("Error while writing to output stream");
            }
        }
    }
    

    在上面的示例中,我们创建了一个名为/stream的GET请求处理程序。响应类型被设置为text/plain,以支持每隔1秒返回一部分内容。

    通过使用response.getOutputStream(),我们可以向响应输出流中写入内容,并在每次写入数据后调用Thread.sleep(1000)来暂停1秒。

    启动应用程序,并在你的浏览器中访问http://localhost:8080/stream,你将会看到每隔1秒输出一个字符串。