springboot服务端怎么推送SSE
springboot服务端怎么推送SSE,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
站在用户的角度思考问题,与客户深入沟通,找到郊区网站设计与郊区网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站设计制作、网站制作、企业官网、英文网站、手机端网站、网站推广、申请域名、网站空间、企业邮箱。业务覆盖郊区地区。
package com.demo.action;
import com.demo.serviceI.DemoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@RestController
public class DemoAction {
@Autowired
private DemoService demoService;
/**
* 健康检查json串模拟
* @return
*/
@RequestMapping(value = "health.json")
public String healt(){
return "{\"status\":\"UP\",\"diskSpace\":{\"status\":\"UP\",\"total\":249769230336,\"free\":71914618880,\"threshold\":10485760},\"db\":{\"status\":\"UP\",\"database\":\"MySQL\",\"hello\":1}}";
}
/**
* 条件注解使用
* @return
*/
@RequestMapping(value = "user/info")
public String info(){
return demoService.info();
}
/**
* 异步调用方法
*/
@RequestMapping(value = "print")
public void print(){
for (int i = 0; i < 100; i++) {
demoService.print(i);
}
}
/**
* 服务端推送技术
*/
@RequestMapping(value = "serverPush",produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
public String serverPush(){
Map demo = new HashMap<>(1);
demo.put("name","张三"+new Random().nextInt());
ObjectMapper objectMapper = new ObjectMapper();
String s = "data:";
try {
s += objectMapper.writeValueAsString(demo)+"\n\n";
System.out.println(s);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return s;
}
} 页面代码
Title
注意使用过程中容易遇到的问题:
1.由于返回类型使用了text/event-stream,所以在服务端响应数据必须使用String或其他文本类型
2. 在返回数据时,必须用data:和\n\n分别开头和结尾;如:String.format("data:%s\n\n",data),这里将我坑惨,网上和书上资料只是给了个例子没有具体说明,找了半天没找到原因和前端链接成功就是触发不了message事件

关于springboot服务端怎么推送SSE问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。
分享标题:springboot服务端怎么推送SSE
转载来于:http://www.jxjierui.cn/article/gejdso.html


咨询
建站咨询
