spring boot一种新的消息推送机制get长连接

在开发业务中,经常需要服务器与客户端的消息交互,有的业务需要等待服务器处理并且实时看到处理进度,即看到服务器的处理进度,本文以spring boot来讲解,其他的语言也可以类推。

1.实现思路:

​ 当浏览器发送请求时,与服务器建立http GET连接,此时保持连接不断开,服务器就可以主动发送消息给前端页面了

第一步:
@GetMapping("getmessage")
    public void sendMsg(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("application/json;charset=utf-8");

        while (true) {
            String newMessage = msgService.getNewMessage();
            if(StringUtils.isNotEmpty(newMessage)){
                write(response, "测试" + newMessage + "--------------------\n");

            }
            Thread.sleep(1000);
        }
    }
    private void write(HttpServletResponse response, String content) throws IOException {
        response.getWriter().write(content + "");
        response.flushBuffer();
        response.getWriter().flush();
    }
第二步:

而while循环就需要去请求公共一个内存变量才能保证系统的稳定性(while一直去轮询数据库是不现实的)。

Spring Boot有一个共享变量的类,在发送post消息时,将最新的一条消息保存到publishEvent中:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
 
@RestController
public class GetMessage {
    
    @Autowired
    private ApplicationContext ac;

    @PostMapping("addMsg")
    public Result addMsg(String msg) {
        Message messages = new Message();
        messages.setContent(msg);
        System.out.println("接收到消息" + msg);
        ac.publishEvent(messages);
        return Result.success();
    }
}
第三部:

此时通过Spring Boot提供的事件监听方法就可以获取到post上传上来的消息:

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
 
@Service
public class MsgServiceImp {
    private String NewMessage = "";
 
    @EventListener
    public void sendMsg(Message message) {
        System.out.println("发送消息" );
        NowMessage = String.valueOf(message);
    }
 
    public String getNewMessage(){
        String msg = NewMessage;
        NewMessage = "";//消息清空
        return msg;
    }
}

效果图:

当有新的post消息上来时,调用addMsg方法,@EventListener就会监听到,将接收到的最新一条消息保存到变量NewMessage中,然后while循环不断的访问这个变量是否有变化,有则推送,无则不推送,直到有新的post请求消息上来时,NewMessage变量才会变化,while也才会再次向客户端推送消息。

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...