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. http安全

    https介绍  因为HTTP是明文传输,所以不安全,容易被黑客窃听或窜改: 通信安全必须同时具备机密性.完整性,身份认证和不可否认这四个特性 HTTPS的语法.语义仍然是HTTP,但把下层的协议由T ...

  2. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    版本的问题 重新输入 npm install 再输入 npm run serve重启,如果还是不可以的话,在把之前装的都清空 依次输入以下命令 rm -rf node_modulesrm packag ...

  3. python 99乘法表

    先把代码贴上 for i in range(1,10): for j in range(1,i+1): s="%d X %d = %d"%(j,i,i*j) print(s,end ...

  4. HttpServletRequest、HttpServletResponse

    doGet()/doPost()方法都有两个参数,一个为代表请求的request,另一个代表响应response. request是获取前台传递的内容,response是反馈给前台数据 HttpSer ...

  5. std:ios:sync_with_stdio (false)以及局限性

    如何在输入输出上提高一下效率emmmm #include<iostream> #include<stdio.h> #include<stdlib.h> #inclu ...

  6. PHP 类型比较

    PHP 类型比较 虽然 PHP 是弱类型语言,但也需要明白变量类型及它们的意义,因为我们经常需要对 PHP 变量进行比较,包含松散和严格比较. 松散比较:使用两个等号 == 比较,只比较值,不比较类型 ...

  7. layui实现图片上传

    页面代码: <style> .uploadImgBtn2{ width: 120px; height: 92px; cursor: pointer; position: relative; ...

  8. Netty(一):server启动流程解析

    netty作为一个被广泛应用的通信框架,有必要我们多了解一点. 实际上netty的几个重要的技术亮点: 1. reactor的线程模型; 2. 安全有效的nio非阻塞io模型应用; 3. pipeli ...

  9. SLAM中的逆深度参数化

    参数化问题 在SLAM的建图过程中,把像素深度假设成了高斯分布.那么这么假设是否是合适的呢?这里关系到一个参数化的问题. 我们经常用一个点的世界坐标x,y,z三个量来描述它,这是一种参数化形式.我们认 ...

  10. python8.3多进程

    from multiprocessing import Processimport time def run1 (name,sex): print(name,sex,"执行进程1" ...