关于WebSocket+RabbitMQ整合实现消息实时推送的案例

WebSocket+RabbitMQ基于Spring boot实现

1.配置

  1. maven导包
    SpringBoot 与webSocket的关联
 <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-websocketartifactId>
    dependency>

SpringBoot与Rabbit MQ的关联

  <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-amqpartifactId>
  dependency>

配置application.yml文件

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: admin
    password: admin

编写RabbitMQ服务端

  1. 配置服务端的config
@Configuration
public class SendConfig {
    @Bean("queue")
    public Queue queueMsg(){
        return new Queue("queue");
    }
    @Bean("exchange")
    public TopicExchange exchange(){
        return new TopicExchange("exchange");
    }
    @Bean
    Binding bindingExchangeAndQueuemsg(@Qualifier("queue") Queue queue, @Qualifier("exchange") TopicExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("a");
    }
}
  1. 编写服务端的Controller
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {
    @Autowired
    private AmqpTemplate amqpTemplate;
    @RequestMapping("/send")
    public void SennerMsg(String msg){
        amqpTemplate.convertAndSend("exchange","a",msg);
    }
}

到这启动MQ后运行程序便可以看到有一个新的邮件
关于WebSocket+RabbitMQ整合实现消息实时推送的案例_第1张图片
或者用命令查看
关于WebSocket+RabbitMQ整合实现消息实时推送的案例_第2张图片

编写MQ的客户端(与WebSocket结合)

  1. 配置Websocket—做请求拦截
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

public class Hank implements HandshakeInterceptor{
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map map) throws Exception {
                      String jspCode = ((ServletServerHttpRequest) request).getServletRequest().getParameter("jspCode");
                if (jspCode != null) {
                    map.put("jspCoe", jspCode);
                } else {
                    return false;
                }

                return true;
            }
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
  1. 配置Websocket的Handler
@Component
public class MyWebSocketHandler implements WebSocketHandler {

    private static final Map userMap=new HashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
       String jspCode = (String )webSocketSession.getAttributes().get("jspCode");

        if(userMap.get(jspCode)==null){
            System.out.println(jspCode);
            userMap.put(jspCode,webSocketSession);
        }
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage webSocketMessage) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
    public void sendMsgToJsp(final TextMessage message, String type) throws  Exception{
        Iterator> it=userMap.entrySet().iterator();
        while (it.hasNext()){
            final Map.Entry entry=it.next();
            System.out.println(entry.getValue().isOpen());
            System.out.println(entry.getKey().contains(type));
            if(entry.getValue().isOpen()&&entry.getKey().contains(type)){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if(entry.getValue().isOpen()){
                                entry.getValue().sendMessage(message);
                            }
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }
}
  1. 配置WebSocket的config
@Component
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
    @Resource
    private MyWebSocketHandler handler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(handler, "/wsMy").addInterceptors(new HandshakeInterceptor() {
            @Override
            public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map map) throws Exception {
                String jspCode = ((ServletServerHttpRequest) request).getServletRequest().getParameter("jspCode");
                if (jspCode != null) {
                    map.put("jspCode", jspCode);
                } else {
                return false;
            }

                return true;
            }

            @Override
            public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

            }
        });
    }
}
  1. 配置客户端的cortorller(二者关联的部分)
     @Autowired
    public MyWebSocketHandler handler;

   @RabbitListener(queues = "queue")
    public void Recive(String msg) throws Exception{
        handler.sendMsgToJsp(new TextMessage(msg), "A");
    }

到此便可以启动测试了
关于WebSocket+RabbitMQ整合实现消息实时推送的案例_第3张图片

另附上前端页面

 <script type="text/javascript">
        var websocket;

        // 首先判断是否 支持 WebSocket
        if('WebSocket' in window) {

            websocket = new WebSocket("ws://localhost:8080/wsMy?jspCode=AA");
        } else if('MozWebSocket' in window) {
            websocket = new MozWebSocket("ws://localhost:8080/wsMy?jspCode=AA");
        } else {
            websocket = new SockJS("ws://localhost:8080/wsMy?jspCode=AA");
        }

        // 打开连接时
        websocket.onopen = function(event) {
            console.log(" websocket.onopen  ");
        };

        // 收到消息时
        websocket.onmessage = function(event) {
            console.log("收到一条消息"+event.data);
            alert(event.data);
        };

        websocket.onerror = function(event) {
            console.log("  websocket.onerror  ");
        };

        websocket.onclose = function(event) {
            console.log("  websocket.onclose  ");
        };



    script>

你可能感兴趣的:(RabbitMQ,websocket)