Springboot+WebSocket+Kafka(写着玩的)
闹着玩的来源:前台发送消息,后台接受处理发给kafka,kafka消费者接到消息传给前台显示。联想到websocket。
最终效果如图:
页面解释:
不填写内容的话,表单值默认为Topic、Greeting、Name
点击订阅,按钮变黑
Send Topic | 广播 | 前台显示前缀:T-You Send |
Subscribe Topic | 订阅广播 | 前台显示前缀:A-You Receive、B-You Receive |
Send Queue | 广播 | 前台显示前缀:Q-You Send |
Subscribe Queue | 订阅广播 | 前台显示前缀:C-You Receive、D-You Receive |
Subscribe Point | 订阅点对点 | 前台显示前缀:/user/110/queue/pushInfo,Receive |
Send Kafka | 点对点 | 前台显示前缀:Kafka Send |
Receive Kafka | 订阅点对点 | 前台显示前缀:Kafka Receive |
重要提示:欲接受消息,先点击订阅
关键代码:
配置websocket
package com.example.demo.conf; import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; /**
* @program: boot-kafka
* @description:
* @author: 001977
* @create: 2018-07-11 11:30
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfigurationWithSTOMP implements WebSocketMessageBrokerConfigurer { @Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/clientConnectThis").setAllowedOrigins("*").withSockJS();
} @Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// P2P should conf a /user ; broadcast should conf a /topic
config.enableSimpleBroker("/topic", "/queue", "/user");
config.setApplicationDestinationPrefixes("/app"); // Client to Server
config.setUserDestinationPrefix("/user"); // Server to Client
}
}
controller
package com.example.demo.controller; import com.example.demo.entity.Welcome;
import com.example.demo.service.KafkaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView; /**
* @program: boot-kafka
* @description:
* @author: 001977
* @create: 2018-07-11 11:00
*/
@RestController
public class SimpleController { @Autowired
private KafkaService kafkaService; @Autowired
private SimpMessagingTemplate simpMessagingTemplate; @RequestMapping("/")
public ModelAndView stomp(){
return new ModelAndView("stomp_home");
} @SubscribeMapping("/firstConnection")
public Welcome thanks(){
return new Welcome("...", "Thank You!");
} @MessageMapping("/sendMessageTopic")
@SendTo("/topic/webSocketTopic")
public Welcome sendToTopic(@RequestBody Welcome welcome){
System.out.println("Send-Topic-Msg:" + welcome);
return welcome;
} @MessageMapping("/sendMessageQueue")
@SendToUser("/queue/webSocketQueue")
public Welcome sendToQueue(@RequestBody Welcome welcome){
System.out.println("Send-Queue-Msg:" + welcome);
return welcome;
} /**
* P2P,后台模拟推送给前台,需打开@Scheduled注释
*/
//@Scheduled(fixedRate = 1000L)
public void send(){
Welcome welcome = new Welcome("110","Hello!");
simpMessagingTemplate.convertAndSendToUser("110", "/queue/pushInfo", welcome);
System.err.println(welcome);
} @MessageMapping("/sendKafka")
public Welcome sendToKafka(@RequestBody Welcome welcome){
boolean b = kafkaService.send(welcome);
if (b)
System.out.println("Send-Kafka-Msg:" + welcome);
return welcome;
} }
前端JS
var socket = new SockJS('/clientConnectThis');
var stompClient = Stomp.over(socket);
stompClient.connect({},
function connectCallback(frame) { // success
connectResult("Connect Success");
stompClient.subscribe('/app/firstConnection', function (response) {
var returnData = JSON.parse(response.body);
receiveText("/app/firstConnection,Test Receive:" + returnData.greeting);
});
},
function errorCallBack(error) { // failed
connectResult("Connect Break");
}
); //发送消息
function sendTopic() {
var topic = $('#topic').val();
var message = $('#message').val();
var name = $('#name').val();
if(topic == "")
topic = "Topic";
if(message == "")
message = "Greeting";
if(name == "")
name = "Name";
var messageJson = JSON.stringify({"topic":topic,"greeting": message,"name":name});
stompClient.send("/app/sendMessageTopic", {}, messageJson);
sendText("T-You Send:" + messageJson);
}
function sendQueue() {
var topic = $('#topic').val();
var message = $('#message').val();
var name = $('#name').val();
if(topic == "")
topic = "Topic";
if(message == "")
message = "Greeting";
if(name == "")
name = "Name";
var messageJson = JSON.stringify({"topic":topic,"greeting": message,"name":name});
stompClient.send("/app/sendMessageQueue", {}, messageJson);
sendText("Q-You Send:" + messageJson);
} //订阅消息
function subscribeTopic(t) {
$(t).css({
"backgroundColor": "#000"
});
stompClient.subscribe('/topic/webSocketTopic', function (response) {
var returnData = JSON.parse(response.body);
receiveText("A-You Receive:(name=" + returnData.name + ",greeting=" + returnData.greeting + ",topic=" + returnData.topic + ")")
});
stompClient.subscribe('/topic/webSocketTopic', function (response) {
var returnData = JSON.parse(response.body);
receiveText("B-You Receive:(name=" + returnData.name + ",greeting=" + returnData.greeting + ",topic=" + returnData.topic + ")")
});
} //订阅消息
function subscribeQueue(t) {
$(t).css({
"backgroundColor": "#000"
});
stompClient.subscribe('/user/queue/webSocketQueue', function (response) {
var returnData = JSON.parse(response.body);
receiveText("C-You Receive:(name=" + returnData.name + ",greeting=" + returnData.greeting + ",topic=" + returnData.topic + ")")
});
stompClient.subscribe('/user/queue/webSocketQueue', function (response) {
var returnData = JSON.parse(response.body);
receiveText("D-You Receive:(name=" + returnData.name + ",greeting=" + returnData.greeting + ",topic=" + returnData.topic + ")")
});
} function subscribePoint(t) {
$(t).css({
"backgroundColor": "#000"
});
// /user/{userId}/**
stompClient.subscribe('/user/110/queue/pushInfo', function (response) {
var returnData = JSON.parse(response.body);
receiveText("/user/110/queue/pushInfo,Receive:" + returnData.greeting);
});
} function sendKafka() {
var topic = $('#topic').val();
var message = $('#message').val();
var name = $('#name').val();
if(topic == "")
topic = "Topic";
if(message == "")
message = "Greeting";
if(name == "")
name = "Name";
var messageJson = JSON.stringify({"topic":topic,"greeting": message,"name":name});
stompClient.send("/app/sendKafka", {}, messageJson);
sendText("Kafka Send:" + messageJson);
} function kafkaReceive(t) {
$(t).css({
"backgroundColor": "#000"
});
stompClient.subscribe('/user/kafka-user-id/queue/kafkaMsg', function (response) {
var returnData = JSON.parse(response.body);
receiveText("Kafka Receive:(name=" + returnData.name + ",greeting=" + returnData.greeting + ",topic=" + returnData.topic + ")")
});
} function sendText(v) {
$('.container .right').append($('<div class="common-message send-text">'+ v +'</div>'));
} function receiveText(v) {
$('.container .right').append($('<div class="common-message receive-text">'+ v +'</div>'));
} function connectResult(v) {
$('.container').append($('<div class="connect-text">'+ v +'</div>'))
}
其余的见GitHub
Springboot+WebSocket+Kafka(写着玩的)的更多相关文章
- SpringBoot整合Kafka和Storm
前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接 ...
- SpringBoot+WebSocket
SpringBoot+WebSocket 只需三个步骤 导入依赖 <dependency> <groupId>org.springframework.boot</grou ...
- SpringBoot系列八:SpringBoot整合消息服务(SpringBoot 整合 ActiveMQ、SpringBoot 整合 RabbitMQ、SpringBoot 整合 Kafka)
声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合消息服务 2.具体内容 对于异步消息组件在实际的应用之中会有两类: · JMS:代表作就是 ...
- springboot+websocket+sockjs进行消息推送【基于STOMP协议】
springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...
- 利用SpringBoot+Logback手写一个简单的链路追踪
目录 一.实现原理 二.代码实战 三.测试 最近线上排查问题时候,发现请求太多导致日志错综复杂,没办法把用户在一次或多次请求的日志关联在一起,所以就利用SpringBoot+Logback手写了一个简 ...
- Springboot+Websocket+JWT实现的即时通讯模块
场景 目前做了一个接口:邀请用户成为某课程的管理员,于是我感觉有能在用户被邀请之后能有个立马通知他本人的机(类似微博.朋友圈被点赞后就有立马能收到通知一样),于是就闲来没事搞了一套. 涉及技术栈 ...
- python写机器人玩僵尸骰子
python写机器人玩僵尸骰子由Al Sweigart用python发布注意:我正在为我的僵尸骰子模拟器寻找反馈,以及这一套指令.如果你觉得有什么地方可以改进,请发邮件到al@inventwithpy ...
- springboot集成Kafka
kafka和MQ的区别: 1)在架构模型方面, RabbitMQ遵循AMQP协议,RabbitMQ的broker由Exchange,Binding,queue组成,其中exchange和binding ...
- SpringBoot WebSocket STOMP 广播配置
目录 1. 前言 2. STOMP协议 3. SpringBoot WebSocket集成 3.1 导入websocket包 3.2 配置WebSocket 3.3 对外暴露接口 4. 前端对接测试 ...
随机推荐
- WEX5中ajax跨域访问的几种方式
1.使用jsonp方式 使用jsonp访问的话,前端需要把回调函数名传递给后端,后端执行完后也需要把回调函数传回给前端,默认情况下ajax自动生成一个回调函数名,后端可以通过String callba ...
- 一、Composer
一.Composer -依赖管理工具 Composer 会帮你安装这些依赖的库文件
- 定位linux jdk安装路径
如何在一台Linux服务器上查找JDK的安装路径呢? 有那些方法可以查找定位JDK的安装路径?是否有一些局限性呢? 下面总结了一下如何查找JDK安装路径的方法. 1:echo $JAVA_HOME 使 ...
- Jenkins+PowerShell持续集成环境搭建(二)控制台项目
1. 新建一个名字为HelloWorld.Console的Freesyle项目: 2. 配置源码管理: 3. 编译配置: 版本:选择MSBuild4 文件:D:\CI\Config\HelloWorl ...
- Process 模块的方法
join from multiprocessing import Process import time, os def task(name): print('%s is running' % nam ...
- 【python练习题】程序1
#题目:有1.2.3.4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? count = 0 for i in range(1,5): for j in range(1,5): for k ...
- codeforces496C
Removing Columns CodeForces - 496C You are given an n × m rectangular table consisting of lower case ...
- BZOJ4321queue2——DP/递推
题目描述 n 个沙茶,被编号 1~n.排完队之后,每个沙茶希望,自己的相邻的两 人只要无一个人的编号和自己的编号相差为 1(+1 或-1)就行: 现在想知道,存在多少方案满足沙茶们如此不苛刻的条件. ...
- P1427 小鱼念数字
P1427 题目描述 小鱼最近被要求参加一个数字游戏,要求它把看到的一串数字(长度不一定,以0结束,最多不超过100个,数字不超过2^32-1),记住了然后反着念出来(表示结束的数字0就不要念出来了) ...
- 洛谷P1216数字三角形题解
题目 这道题是一个典型的DP,可以用倒推,顺推的方法,来解这道题.当然用不同的方法他的循环次序是不一样的,所以我们一定要深刻地理解题目的大意,再采用状态转移方程与边界每次求出最优解,并记录循环一遍后就 ...