websocket准实时推送消息

在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
@EnableScheduling
public 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
@EnableScheduling
public 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("推送的消息");
        }
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值