1、pom.xml

		<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、WebSocketConfig

启用WebSocket的支持也是很简单,几句代码搞定

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

3、WebSocketServer

因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
直接@ServerEndpoint("/websocket")@Component启用即可,然后在里面实现@OnOpen,@onClose,@onMessage等方法

package com.yanan.base.config.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/websocket/{userId}") //WebSocket客户端建立连接的地址
@Component
@Slf4j
public class WebSocketServer {
private final Logger log= LoggerFactory.getLogger(WebSocketServer.class);
/**
* 存活的session集合(使用线程安全的map保存)
*/
private static Map<String, Session> livingSessions = new ConcurrentHashMap<>(); /**
* 建立连接的回调方法
*
* @param session 与客户端的WebSocket连接会话
* @param userId 用户名,WebSocket支持路径参数
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
livingSessions.put(session.getId(), session);
log.info(userId + "进入连接");
} @OnMessage
public void onMessage(String message, Session session, @PathParam("userId") String userId) {
log.info(userId + " : " + message);
sendMessageToAll(userId + " : " + message);
} @OnError
public void onError(Session session, Throwable error) {
log.info("发生错误");
log.error(error.getStackTrace() + "");
} @OnClose
public void onClose(Session session, @PathParam("userId") String userId) {
livingSessions.remove(session.getId());
log.info(userId + " 关闭连接");
} /**
* 单独发送消息
*
* @param session
* @param message
*/
public void sendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 群发消息
*
* @param message
*/
public void sendMessageToAll(String message) {
livingSessions.forEach((sessionId, session) -> {
sendMessage(session, message);
});
} }

 4、接收rabbitmq消息

application.yml配置

spring:
rabbitmq:
host: localhost
port: 5672
username: test
password: test
virtual-host: /

  监听器接收消息队列RabbitmqListener.java

package com.yanan.base.config.rabbit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanan.base.config.rabbitmq.WebSocketServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; @Component
@Slf4j
public class RabbitmqListener {
private final Logger log= LoggerFactory.getLogger(RabbitmqListener.class);
@Autowired
private WebSocketServer webSocketServer;
// AES加密解密
private String sKey = "785641234654";
private String ivParamter = "0392039203";
//queue指要监听列队的名字
@RabbitListener(queues = "sdf")
public void reveiverDirectQueue(String message){
decrypt(message);
}
public JSONObject decrypt(String message) {
try {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParamter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(message);// 先用 base64 解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
JSONObject object = JSON.parseObject(originalString);
// websocket发送消息
webSocketServer.sendMessageToAll(originalString);
log.info("监听消息:" + originalString);
return object;
} catch (Exception ex) {
return null;
}
}
}

5、vue

data () {
return {
queueReceiveSetting: { // 消息队列配置
websock: null,
client: null,
wsuri: 'ws://localhost:8089/websocket/dfgd'
}
}
}
  methods: {
initWebSocket () {
// ws地址
if (this.queueReceiveSetting.websock) {
this.queueReceiveSetting.websock.close()
}
this.queueReceiveSetting.websock = new WebSocket(this.queueReceiveSetting.wsuri)
this.queueReceiveSetting.websock.onopen = res => {
console.log('开启连接')
}
this.queueReceiveSetting.websock.onmessage = res => {
let data = JSON.parse(res.data)
console.log('接收到的数据:', data)
}
this.queueReceiveSetting.websock.onclose = res => {
console.log('连接关闭')
}
this.queueReceiveSetting.websock.onerror = res => {
console.log('连接出错')
}
}
},
mounted () {
this.initWebSocket()
}

  

Springboot + Rabbitmq + WebSocet + vue的更多相关文章

  1. springboot+rabbitmq整合示例程

    关于什么是rabbitmq,请看另一篇文: http://www.cnblogs.com/boshen-hzb/p/6840064.html 一.新建maven工程:springboot-rabbit ...

  2. SpringBoot RabbitMQ 延迟队列代码实现

    场景 用户下单后,如果30min未支付,则删除该订单,这时候就要可以用延迟队列 准备 利用rabbitmq_delayed_message_exchange插件: 首先下载该插件:https://ww ...

  3. springboot rabbitmq 死信队列应用场景和完整demo

    何为死信队列? 死信队列实际上就是,当我们的业务队列处理失败(比如抛异常并且达到了retry的上限),就会将消息重新投递到另一个Exchange(Dead Letter Exchanges),该Exc ...

  4. springboot + rabbitmq 做智能家居,我也没想到会这么简单

    本文收录在个人博客:www.chengxy-nds.top,共享技术资源,共同进步 前一段有幸参与到一个智能家居项目的开发,由于之前都没有过这方面的开发经验,所以对智能硬件的开发模式和技术栈都颇为好奇 ...

  5. springboot + rabbitmq 用了消息确认机制,感觉掉坑里了

    本文收录在个人博客:www.chengxy-nds.top,技术资源共享,一起进步 最近部门号召大伙多组织一些技术分享会,说是要活跃公司的技术氛围,但早就看穿一切的我知道,这 T M 就是为了刷KPI ...

  6. 带着新人学springboot的应用07(springboot+RabbitMQ 下)

    说一两句废话,强烈推荐各位小伙伴空闲时候也可以写写自己的博客!不管水平高低,不管写的怎么样,不要觉得写不好或者水平不够就不写了(咳,我以前就是这样的想法...自我反省!). 但是开始写博客之后,你会发 ...

  7. 带着新人学springboot的应用06(springboot+RabbitMQ 中)

    上一节说了这么多废话,看也看烦了,现在我们就来用鼠标点点点,来简单玩一下这个RabbitMQ. 注意:这一节还是不用敲什么代码,因为上一节我们设置了那个可视化工具,我们先用用可视化工具熟悉一下流程. ...

  8. springboot rabbitmq整合

    这一篇我们来把消息中间件整合到springboot中 ===================================================================== 首先在 ...

  9. Springboot项目与vue项目整合打包

    我的环境 * JDK 1.8 * maven 3.6.0 * node环境 1.为什么需要前后端项目开发时分离,部署时合并? 在一些公司,部署实施人员的技术无法和互联网公司的运维团队相比,由于各种不定 ...

随机推荐

  1. socket网络(二)

    作用域 python/js语言中,无块级作用域 if 1 == 1: name = 'alex' print(name) python中以函数为作用域 def func(): name = 'alex ...

  2. 数据结构C语言实现----图

    邻接表储存结构 /*邻接表的边*/ typedef struct ArcNode { int adjvex; struct ArcNode *next; }ArcNode; /*邻接表的结点*/ ty ...

  3. 火车进栈(进出栈的模拟,dfs爆搜)

    这里有n列火车将要进站再出站,但是,每列火车只有1节,那就是车头. 这n列火车按1到n的顺序从东方左转进站,这个车站是南北方向的,它虽然无限长,只可惜是一个死胡同,而且站台只有一条股道,火车只能倒着从 ...

  4. jieba.lcut方法

    jieba库的作用就是对中文文章进行分词,提取中文文章中的词语 cut(字符串, cut_all,HMM) 字符串是要进行分词的字符串对象 cut_all参数为真表示采用全模式分词,为假表示采用精确模 ...

  5. Django学习路37_request属性

      打印元信息,基本上都会打印出来 类字典结构的 key 键 允许重复   get 请求可以传参,但是长度有限制 最大不能超过 2K post 文件上传使用 get 参数 默认放在网址中 post 在 ...

  6. Unicode 字符串

    Unicode 字符串 Python 中定义一个 Unicode 字符串和定义一个普通字符串一样简单:高佣联盟 www.cgewang.com >>> u'Hello World ! ...

  7. PHP xml_parse() 函数

    定义和用法 xml_parse() 函数解析 XML 文档.高佣联盟 www.cgewang.com 如果成功,该函数则返回 TRUE.如果失败,则返回 FALSE. 语法 xml_parse(par ...

  8. 【BZOJ4631】踩气球 题解(线段树)

    题目链接 ---------------------- 题目大意:给定一个长度为$n$的序列${a_i}$.现在有$m$个区间$[l_i,r_i]$和$q$个操作,每次选取一个$x$使得$a_x--$ ...

  9. SpringBoot中使用AOP打印接口日志的方法(转载)

    前言 AOP 是 Aspect Oriented Program (面向切面)的编程的缩写.他是和面向对象编程相对的一个概念.在面向对象的编程中,我们倾向于采用封装.继承.多态等概念,将一个个的功能在 ...

  10. “随手记”开发记录day07

    今天完成了关于我们页面中的相关信息,由于之前没有做过这个东西,只想着用一个view解决 可是发现我们整的太简单了,还是太年轻,最后想出来要跟java代码一起解决这个问题, 效果