Python的Flask框架下的SSE接口代码如下
# function to push data to the server
def pushData():
# randint is just to make every message not look the same
while True:
number = randint(0, 9)
print('I push data to the server: {0}'.format(number))
yield 'data: %s\n\n' % 'I am data that has been pushed to the server: {0}'.format(number)
time.sleep(1)
# provide SSE stream to the web browser
@app.route('/sse/stock-price')
def stream():
return flask.Response(pushData(), mimetype="text/event-stream")
注意:pushData函数一定是一个不断输出的函数,如果只一次性返回,则连接就自动结束!
Springboot的Feign接口调用接口
@FeignClient(name="sse-python",url="http://192.152.1.12:3000/")
public interface SSEFeign {
@GetMapping(value = "/sse/stock-price", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
feign.Response streamStockPrice( );
}
如果需要通过Springboot的restful通过feign创建一个SSE接口,代码如下:
@Autowired
SSEFeign sseFeign;
@GetMapping(value = "/stock-price", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter streamStockPrice() throws InterruptedException {
SseEmitter emitter = new SseEmitter();
emitter.onCompletion(new Runnable() {
@Override
public void run() {
System.out.println("进入了onCompletion");
}
});
emitter.onError((e) -> {
// e.printStackTrace();
System.out.println("进入了onError");
});
new Thread(()->{
feign.Response response = sseFeign.streamStockPrice();
Response.Body body = response.body();
InputStream fileInputStream = null;
try {
fileInputStream = body.asInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1) {
String str=new String(bytes,"utf-8");
System.out.println(str);
emitter.send(SseEmitter.event().data(str));
}
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
return emitter;
}
注意,通过feign读取InputStream流不断输出的过程,一定要在异步线程中。