发布于 

java流式输出接口

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

package com.ioo.system.refactor_report.controller;

import com.ioo.system.refactor_report.service.OldDateImportService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
* @Project:astoa-admin
* @Package:com.ioo.system.refactor_report.controller
* @Author:xen
* @name:OldDateImportController
* @Date:2024/9/14/0014 14:01
*/
@RestController
@RequestMapping("/v2/report/DateImport")
public class OldDateImportController{
@Resource
private OldDateImportService dateImportService;

@GetMapping()
public SseEmitter streamSse() {
SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
Thread streamThread = new Thread(() -> dateImportService.main(emitter));
streamThread.start();
return emitter;
}

}


Service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

package com.ioo.system.refactor_report.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
* @Project:astoa-admin
* @Package:com.ioo.system.refactor_report.service
* @Author:xen
* @name:OldDateImportService
* @Date:2024/8/1/0001 18:20
*/
@Slf4j
@Service
public class OldDateImportService {

public void main(SseEmitter emitter) {
try {
templateImport(emitter);
} catch (Exception e) {
Thread.currentThread().interrupt();
log.error(e.getMessage());
} finally {
emitter.complete();
}
}

private void sendDataToEmitter(SseEmitter emitter, String data) {
try {
emitter.send(SseEmitter.event().data(data));
} catch (IOException e) {
emitter.completeWithError(e);
}
}

private void templateImport(SseEmitter emitter) {
sendDataToEmitter(emitter, "模板导入开始");

sendDataToEmitter(emitter, "模板导入结束");
}


private void instanceImport(SseEmitter emitter) {
sendDataToEmitter(emitter, "实例导入开始");

sendDataToEmitter(emitter, "实例导入结束");
}

private void contentTemplateImport(SseEmitter emitter) {
sendDataToEmitter(emitter, "实例导入开始");

sendDataToEmitter(emitter, "实例导入结束");
}
}