当前位置:   article > 正文

SpringBoot通过feign调用Python的Flask框架下的SSE接口_springboot 调用 flask

springboot 调用 flask

Python的Flask框架下的SSE接口代码如下

  1. # function to push data to the server
  2. def pushData():
  3. # randint is just to make every message not look the same
  4. while True:
  5. number = randint(0, 9)
  6. print('I push data to the server: {0}'.format(number))
  7. yield 'data: %s\n\n' % 'I am data that has been pushed to the server: {0}'.format(number)
  8. time.sleep(1)
  9. # provide SSE stream to the web browser
  10. @app.route('/sse/stock-price')
  11. def stream():
  12. return flask.Response(pushData(), mimetype="text/event-stream")

注意:pushData函数一定是一个不断输出的函数,如果只一次性返回,则连接就自动结束!

Springboot的Feign接口调用接口

  1. @FeignClient(name="sse-python",url="http://192.152.1.12:3000/")
  2. public interface SSEFeign {
  3. @GetMapping(value = "/sse/stock-price", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  4. feign.Response streamStockPrice( );
  5. }

如果需要通过Springboot的restful通过feign创建一个SSE接口,代码如下:

  1. @Autowired
  2. SSEFeign sseFeign;
  3. @GetMapping(value = "/stock-price", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  4. public SseEmitter streamStockPrice() throws InterruptedException {
  5. SseEmitter emitter = new SseEmitter();
  6. emitter.onCompletion(new Runnable() {
  7. @Override
  8. public void run() {
  9. System.out.println("进入了onCompletion");
  10. }
  11. });
  12. emitter.onError((e) -> {
  13. // e.printStackTrace();
  14. System.out.println("进入了onError");
  15. });
  16. new Thread(()->{
  17. feign.Response response = sseFeign.streamStockPrice();
  18. Response.Body body = response.body();
  19. InputStream fileInputStream = null;
  20. try {
  21. fileInputStream = body.asInputStream();
  22. byte[] bytes = new byte[1024];
  23. int len = 0;
  24. while ((len = fileInputStream.read(bytes)) != -1) {
  25. String str=new String(bytes,"utf-8");
  26. System.out.println(str);
  27. emitter.send(SseEmitter.event().data(str));
  28. }
  29. fileInputStream.close();
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33. }).start();
  34. return emitter;
  35. }

注意,通过feign读取InputStream流不断输出的过程,一定要在异步线程中。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/880315
推荐阅读
相关标签
  

闽ICP备14008679号