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_第1张图片

 

转载于:https://my.oschina.net/u/3484671/blog/3097385

你可能感兴趣的:(java,json,前端,ViewUI)