没写过,你试试chatgpt的回答吧
import java.io.IOException;
import java.io.OutputStream;
import java.util.function.Consumer;
public class TimedOutputStream extends OutputStream {
private final OutputStream delegate;
private final Consumer<Long> completionCallback;
private final long startTime;
public TimedOutputStream(OutputStream delegate, Consumer<Long> completionCallback) {
this.delegate = delegate;
this.completionCallback = completionCallback;
this.startTime = System.currentTimeMillis();
}
@Override
public void write(int b) throws IOException {
delegate.write(b);
}
@Override
public void close() throws IOException {
delegate.close();
long endTime = System.currentTimeMillis();
long timeConsumed = endTime - startTime;
completionCallback.accept(timeConsumed);
}
}
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.ResponseBodyEmitter;
import java.io.OutputStream;
import java.util.concurrent.Executors;
@RestController
@RequestMapping("/download")
public class FileDownloadController {
@GetMapping("/stream")
public ResponseBodyEmitter streamData() {
ResponseBodyEmitter emitter = new ResponseBodyEmitter();
// Wrap the emitter's OutputStream with the TimedOutputStream
OutputStream outputStream = new TimedOutputStream(emitter.getOutputStream(),
timeConsumed -> {
// Handle completion here, e.g., logging the time consumed
System.out.println("Time consumed: " + timeConsumed + " ms");
});
// Simulate streaming data (replace with your actual data source)
Executors.newSingleThreadExecutor().submit(() -> {
try {
for (int i = 0; i < 10; i++) {
outputStream.write(("Data " + i + "\n").getBytes());
Thread.sleep(500); // Simulate data processing
}
} catch (Exception e) {
emitter.completeWithError(e);
} finally {
try {
outputStream.close();
} catch (IOException e) {
emitter.completeWithError(e);
}
}
emitter.complete();
});
return emitter;
}
}
【 在 feng321 的大作中提到: 】
: 能给个可以跑的样例代码吗?真是不太会。。。。
--
FROM 61.69.255.*