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