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

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 引入依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> ``` 2. 创建Feign接口 创建一个Feign接口来定义调用第三方天气预报接口的方法,该接口使用`@FeignClient`注解来指定要调用的服务名和服务地址。 ```java @FeignClient(name = "weather", url = "http://www.weather.com.cn") public interface WeatherClient { @GetMapping("/data/sk/{cityCode}.html") String getWeather(@PathVariable("cityCode") String cityCode); } ``` 3. 创建Controller 创建一个Controller来处理前端的请求,该Controller使用`@RestController`注解来指定返回的结果是JSON格式的数据。 ```java @RestController @RequestMapping("/weather") public class WeatherController { @Autowired private WeatherClient weatherClient; @GetMapping("/{cityCode}") public String getWeather(@PathVariable("cityCode") String cityCode) { String result = weatherClient.getWeather(cityCode); // 处理返回结果 return result; } } ``` 4. 测试 启动SpringBoot应用,访问`http://localhost:8080/weather/101210101`,即可查看北京市的天气预报信息。 返回的结果如下所示: ```json {"weatherinfo":{"city":"北京","cityid":"101010100","temp":"-2","WD":"西南风","WS":"2级","SD":"26%","AP":"1022hPa","njd":"暂无实况","WSE":"2","time":"17:55","sm":"1.1","isRadar":"1","Radar":""}} ``` 通过以上步骤,我们成功地使用Feign技术调用了第三方天气预报接口,并以JSON格式显示给前端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值