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

本文详细介绍了如何在Python的Flask框架中使用Server-SentEvents(SSE)实现持续数据推送,并展示了如何在Springboot中通过Feign调用这个接口,确保数据在异步线程中不断输出。
Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

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流不断输出的过程,一定要在异步线程中。

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值