This is the 11th day of my participation in Gwen Challenge

Rabbitmq + WebSocket can push data to the front desk in real time.

websocket

Websocket Long connection WebSocket is a new network protocol based on TCP. It enables full-duplex communication between the browser and the server — allowing the server to actively send messages to the client.

Why long connections?

HTTP protocol communication can only be initiated by the client, and Websocket implements the server to push data to the client

use

1. Rely on

<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>Copy the code

2. The configuration

@Configuration
public class WebSocketConfig extends HttpSessionHandshakeInterceptor {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

Copy the code

Example 3.

@Component @ServerEndpoint(value = "/web", encoders = { ServerEncoder.class }) @Slf4j public class WsgCtrl { @Autowired RabbitTemplate rabbitTemplate; private Session session; public static CopyOnWriteArraySet<WsgCtrl> webSocketSet = new CopyOnWriteArraySet<WsgCtrl>(); @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); Log.info (" [websocket message] new connection, total :{}", webSocketSet.size()); } @OnClose public void onClose() { webSocketSet.remove(this); Log.info (" [websocket message] disconnected, total :{}", webSocketSet.size()); } @onMessage public void OnMessage (String message) throws Exception {log.info(" [webSocket message] Receives the message sent by the client :{}", message); System.out.println(message); sendMessage(message); } public void sendMessage(String message) throws Exception { // for (WsgCtrl webSocket: WebSocketSet) {// log.info(" [websocket message] broadcast message, message={}", message); // try { // webSocket.session.getBasicRemote().sendText(message+"======"); // } catch (Exception e) { // e.printStackTrace(); // } // } JSONObject jsonObject = JSONObject.parseObject(message); BopDao bopDao = JSONObject.toJavaObject(jsonObject, BopDao.class); this.session.getBasicRemote().sendObject(bopDao); / / sendText method commonly, transfer object need to use sendObject method configuration code ServerEncoder / / this. At the same time the session. The getBasicRemote () sendText (message); }}Copy the code

4.ServerEncoder.java

/** * public class ServerEncoder implements Encoder.Text<BopDao> {@override public void init(EndpointConfig endpointConfig) { } @Override public void destroy() { // TODO Auto-generated method stub } @Override  public String encode(BopDao bopDao) throws EncodeException { String s = JSON.toJSONString(bopDao); return s; }}Copy the code

The rabbitmq websocket integration

Call the custom sendMessage method when listening on the method

@Slf4j @RabbitListener(queues = "messagechange") @Controller public class Receiver { @Autowired BopInter bopInter; @RabbitHandler public void receiver(BopDao bopDao,Message message,Channel channel) throws Exception { Log.info ("<============= listens for queue messages ============>"); boolean flag = TestCtrl.flag; log.info("flag:"+flag); if(bopDao! =null&&flag==true){ for ( WsgCtrl item : WsgCtrl.webSocketSet ){ item.sendMessage(JSON.toJSONString(bopDao)); } bopInter.updateBop(bopDao); long deliveryTag = message.getMessageProperties().getDeliveryTag(); channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); } // else { // channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true); / /}}}Copy the code

I’ll add that later