Spring Boot使用EventSource和观察者模式实现服务端推送

服务端:

Controller:

package com.example.demo;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import com.example.demo.service.MsgService;


@Controller
@RequestMapping("/")
public class MsgControl {
	
	@Resource(name="msgService")
	private MsgService msgService;
	
	@ResponseBody
	@RequestMapping(value = "/getMsg", produces="text/event-stream;charset=UTF-8")
	DeferredResult getMsg(HttpServletResponse response) throws IOException {
		response.setContentType("text/event-stream");
    	response.setCharacterEncoding("UTF-8");
    	response.setStatus(200);
    	msgService.removeErrorResponse();
    	msgService.getListRes().add(response);
    	if(!response.getWriter().checkError()){
    		response.getWriter().write("data:hello\n\n");
    		response.getWriter().flush();
    	}
    	DeferredResult df = new DeferredResult(60000l);
    	return df;
    }
}

Service:

package com.example.demo.service;

import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Vector;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Lazy(value = false)
@EnableScheduling
@Service(value="msgService")
public class MsgService {
	
	final Vector list_res= new Vector();
	
	public Vector getListRes()
	{
		return list_res;
	}
	
	@Scheduled(initialDelay = 0, fixedDelay = 3*1000)
	public void run() {
		this.removeErrorResponse();
		Iterator it = list_res.iterator();
		Random rand =new Random();
		int num=rand.nextInt(100);
		while(it.hasNext())
		{
			PrintWriter pw = null;
			try {
				pw = it.next().getWriter();
				if(pw == null || pw.checkError())
				{				
					continue;
				}
	    		pw.write("data:msg: hello, the random num is: " + num + "\n\n");
	    		pw.flush();
			} catch (Exception e) {
				
			} 
		}
	}
	
	public synchronized void removeErrorResponse(){
		Iterator it = list_res.iterator();
		while(it.hasNext())
		{
			PrintWriter pw = null;
			try {
				pw = it.next().getWriter();
				if(pw == null)
				{
					it.remove();
					continue;
				}
				else if(pw.checkError()){
					pw.close();
					it.remove();
					continue;
				}
			} catch (Exception e) {				
				it.remove();
			} 	
		}
	}
}

前端代码:




	
	信息


	

运行结果:

你可能感兴趣的:(服务器推送,SpringBoot,spring,java)