websocket准实时推送消息
来源:互联网 发布:什么软件可以写日记 编辑:程序博客网 时间:2024/05/21 06:50
在web项目中前端向后端请求数据时,如果要求数据的实时性,第一种方式是基于ajax的长轮训,第二种方式是websocket通讯,今天要介绍的是第二种方式。直接上代码。
进行websocket通讯的类,要加上component注解
@ServerEndpoint("/websocket/{uid}")@Component("websocket")public class SocketServer { private Session session; private static ConcurrentHashMap< String , SocketServer> map = new ConcurrentHashMap<String , SocketServer>(); //建立连接后,将session存在map中 @OnOpen public void onOpen(@PathParam("uid") String uid, Session session ) { this.session = session; map.put(uid,this); } //遍历发送消息 public void sendMessage (String message) { for(SocketServer server : map.values()){ try { server.session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } } }}
定时器每隔55秒去查数据库中的order表,如果有新的记录增加,就往队列中加入一条消息
@Component@EnableSchedulingpublic class Producer { Jedis jedis = new Jedis("127.0.0.1", 6379); int tempId ; @Scheduled(cron = "0/55 * * * * ?") public void run(){ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql:///maetin","root","123456"); String sql = "select * from tbl_product order by id desc limit 1"; try { con = this.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ if(tempId == 0 ){ tempId = rs.getInt("id"); } if(tempId < rs.getInt("id")){ tempId = rs.getInt("id"); jedis.lpush("IdQueue" , tempId+""); } } }catch (Exception e){ e.printStackTrace(); }finally { } }}
推送消息到前端
@Component@EnableSchedulingpublic class Consumer { Jedis jedis = new Jedis("127.0.0.1", 6379); @Autowired private SocketServer socket; @Autowired private BusiService service; @Scheduled(cron = "0/30* * * * ?") public void run(){ String id = jedis.rpoplpush("IdQueue", "TempQueue"); if(null != id){ jedis.rpop("TempQueue"); socket.sendMessage("推送的消息"); } }}
阅读全文
0 0
- websocket准实时推送消息
- php实现websocket实时消息推送
- php实现websocket实时消息推送
- Websocket(3)--实时推送
- WebSocket点对点通信-Tomcat websocket点对点通信-实时通信-服务器消息推送
- Websocket消息推送平台
- websocket消息推送
- WebSocket与消息推送
- WebSocket与消息推送
- WebSocket与消息推送
- java websocket消息推送
- webSocket 消息推送
- WebSocket与消息推送
- WebSocket与消息推送
- 消息推送之Websocket
- WebSocket与消息推送
- WebSocket与消息推送
- WebSocket与消息推送
- 迷宫问题 poj3984
- 遍历Map集合的四种方法
- Java爬虫,信息抓取的实现
- hive2版本安装
- HDOJ 3790-最短路径问题
- websocket准实时推送消息
- 操作系统---进程管理
- bank
- linux系统启动流程详解
- 5.2 stat.py
- popupwindow点击其它位置和点击back键不消失,以及和dialog的区别。
- 一个数组中有多个对象
- Oracle子程序之函数(function)和过程(procedure)
- chrome浏览器插件,让您浏览器页面游小鱼儿