spring + rabbitmq + websocket实现实时通知

导入依赖:

 compile group: 'org.springframework.amqp', name: 'spring-rabbit', version: '1.4.5.RELEASE'
    compile group: 'com.rabbitmq', name: 'amqp-client', version: '3.5.1'
建立spring-rabbitMQ.properties内容如下:

//rabbitmq-config.properties
mq.host=127.0.0.1
mq.username=guest
mq.password=guest
mq.port=5672
mq.vhost=/
mq.exchange=xpingEx
mq.queue=xping
mq.queue_key=queue_key
建立spring-rabbitMQ.xml 内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <description>rabbitmq 连接服务配置</description>
    <!-- 连接配置 -->
    <rabbit:connection-factory id="connectionFactory01" host="${mq.host}" username="${mq.username}" password="${mq.password}" port="${mq.port}"  virtual-host="${mq.vhost}"/>
    <rabbit:admin connection-factory="connectionFactory01"/>



    <!-- 消息对象json转换类 -->
    <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />

    <!-- durable是否持久化-->
    <rabbit:queue id="queue_key" name="${mq.queue}" durable="true" auto-delete="false" exclusive="false" />

    <rabbit:direct-exchange name="${mq.exchange}" durable="true" auto-delete="false" id="mq-exchange">
        <rabbit:bindings>
            <rabbit:binding queue="queue_key" key="${mq.queue_key}"/>
        </rabbit:bindings>
    </rabbit:direct-exchange>

    <!-- spring template声明-->
    <rabbit:template exchange="${mq.exchange}" id="amqpTemplate"  connection-factory="connectionFactory01"  message-converter="jsonMessageConverter" />

    <bean id="queueListenter" class="com.xping.MQ.RabbitConsumor"/>
    <rabbit:listener-container connection-factory="connectionFactory01" acknowledge="auto">
        <rabbit:listener queues="queue_key" ref="queueListenter"/>
    </rabbit:listener-container>
</beans>
引入配置文件到spirng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	">

    <!-- 注解支持 -->
    <context:annotation-config/>
    <!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描  .service-->
    <context:component-scan base-package="com.xping">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 引入属性文件(多个) -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:dbConfig.properties</value>
                <value>classpath:redis.properties</value>
                <value>classpath:spring-rabbitMQ.properties</value>
            </list>
        </property>
    </bean>

    <import resource="spring-mybatis.xml"/>
    <import resource="spring-redis.xml"/>
    <import resource="spring-rabbitMQ.xml"/>
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>

</beans>
建立productor service:

package com.xping.MQ;

public interface RabbitProductorService {
    /**
     * 发送消息到指定队列
     * @param queueKey
     * @param object
     */
    public void sendMessage(String queueKey, Object object);
}
建立productor service实现类:

package com.xping.MQ;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RabbitProductorServiceImpl implements RabbitProductorService{

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public void sendMessage(String routeKey, Object message) {
        try {
            amqpTemplate.convertAndSend(routeKey,message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
建立consumor:
package com.xping.MQ;

import com.xping.controller.WebSocketServer;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.io.IOException;

public class RabbitConsumor implements MessageListener{

    @Override
    public void onMessage(Message message) {
        System.out.println("consumor:" + message.toString());
        for(WebSocketServer webSocketServer :WebSocketServer.webSocketSet){
            try {
                webSocketServer.sendMessage(message.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

控制器测试:

 @Autowired
    RabbitProductorService rabbitProductorService;

    @GetMapping("/sendMsg")
    public void sendMsg(@RequestParam("msg") String msg){
        rabbitProductorService.sendMessage("queue_key ",msg);
    }
结果:

consumor:(Body:'"傻逼"'MessageProperties [headers={__TypeId__=java.lang.String}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=null, replyTo=null, contentType=application/json, contentEncoding=UTF-8, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=xpingEx, receivedRoutingKey=queue_key, deliveryTag=3, messageCount=0])



使用websocket做实时通知:

建立socket控制器:

package com.xping.controller;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/webSocket")
public class WebSocketServer {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    // 若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    public static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;

        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
前端:

<html>
<head>
    <title>WebSocket</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="main">
    <div id="message"></div>
</div>
</body>
<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        //创建一个WebSocket连接,URL:127.0.0.1:8080/realTimeWebSocket/webSocket
        //注:后端Server在模块realTimeWebSocket下,所以路径下多了一层realTimeWebSocket
        websocket = new WebSocket("ws://127.0.0.1:8080/webSocket");
    }
    else {
        alert('当前浏览器 不支持WebSocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("连接成功");
    }

    //接收到消息的回调方法,此处添加处理接收消息方法,当前是将接收到的信息显示在网页上
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("连接关闭,如需登录请刷新页面。");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上,如果不需要显示在网页上,则不调用该方法
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }
</script>
</html>
先把服务端跑起来 访问前端显示连接成功  开始测试发消息:

结果:

连接成功
(Body:'"傻逼"'MessageProperties [headers={__TypeId__=java.lang.String}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=null, replyTo=null, contentType=application/json, contentEncoding=UTF-8, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=xpingEx, receivedRoutingKey=queue_key, deliveryTag=3, messageCount=0])













  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳十三

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值