闹着玩的来源:前台发送消息,后台接受处理发给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(写着玩的)的更多相关文章

  1. SpringBoot整合Kafka和Storm

    前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接 ...

  2. SpringBoot+WebSocket

    SpringBoot+WebSocket 只需三个步骤 导入依赖 <dependency> <groupId>org.springframework.boot</grou ...

  3. SpringBoot系列八:SpringBoot整合消息服务(SpringBoot 整合 ActiveMQ、SpringBoot 整合 RabbitMQ、SpringBoot 整合 Kafka)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合消息服务 2.具体内容 对于异步消息组件在实际的应用之中会有两类: · JMS:代表作就是 ...

  4. springboot+websocket+sockjs进行消息推送【基于STOMP协议】

    springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...

  5. 利用SpringBoot+Logback手写一个简单的链路追踪

    目录 一.实现原理 二.代码实战 三.测试 最近线上排查问题时候,发现请求太多导致日志错综复杂,没办法把用户在一次或多次请求的日志关联在一起,所以就利用SpringBoot+Logback手写了一个简 ...

  6. Springboot+Websocket+JWT实现的即时通讯模块

    场景 目前做了一个接口:邀请用户成为某课程的管理员,于是我感觉有能在用户被邀请之后能有个立马通知他本人的机(类似微博.朋友圈被点赞后就有立马能收到通知一样),于是就闲来没事搞了一套. ​ 涉及技术栈 ...

  7. python写机器人玩僵尸骰子

    python写机器人玩僵尸骰子由Al Sweigart用python发布注意:我正在为我的僵尸骰子模拟器寻找反馈,以及这一套指令.如果你觉得有什么地方可以改进,请发邮件到al@inventwithpy ...

  8. springboot集成Kafka

    kafka和MQ的区别: 1)在架构模型方面, RabbitMQ遵循AMQP协议,RabbitMQ的broker由Exchange,Binding,queue组成,其中exchange和binding ...

  9. SpringBoot WebSocket STOMP 广播配置

    目录 1. 前言 2. STOMP协议 3. SpringBoot WebSocket集成 3.1 导入websocket包 3.2 配置WebSocket 3.3 对外暴露接口 4. 前端对接测试 ...

随机推荐

  1. SQL Server中获取指定时间段内的所有月份

    例如查询 2012-1-5 到 2012-11-3 之间所有的月份 declare @begin datetime,@end datetime set @begin='2012-1-5' set @e ...

  2. codeforces433B

    Kuriyama Mirai's Stones CodeForces - 433B 有n颗宝石,每个宝石都有自己的价值. 然后m次询问.问区间[i,j]的宝石的总值,或者问排序后的区间[i,j]的总值 ...

  3. poj2739(尺取法+质数筛)

    题意:给你一个数,问这个数能否等于一系列连续的质数的和: 解题思路:质数筛打出质数表:然后就是尺取法解决: 代码: #include<iostream> #include<algor ...

  4. bzoj4152-[AMPPZ2014]The_Captain

    Description 给定平面上的n个点,定义(x1,y1)到(x2,y2)的费用为min(|x1-x2|,|y1-y2|),求从1号点走到n号点的最小费用. Input 第一行包含一个正整数n(2 ...

  5. 11/5/2018模拟 Problem C

    题面 题解 我有特殊的哈希技巧 以到下一个相同字符的距离为值哈希, 如果不存在或在串外, 就是 \(|T| + 1\). 加入一个新字符 \(S_i\) 时, 同时修改它上一次出现时的值, 由 \(| ...

  6. BZOJ5419[Noi2018]情报中心——线段树合并+虚树+树形DP

    题目链接: [NOI2018]情报中心 题目大意:给出一棵n个节点的树,边有非负边权,并给出m条链,对于每条链有一个代价,要求选出两条有公共边的链使两条链的并的边权和-两条链的代价和最大. 花了一天的 ...

  7. Windows server 2012 卸载iis 黑屏

    转载:https://jingyan.baidu.com/article/ff42efa9fb6f16c19e2202dc.html 1 按  ctrl+alt+end 键,新建运行任务 ,输入cmd ...

  8. 初略 异步IO

    import asyncio asyncio.coroutine() from concurrent.futures import ThreadPoolExecutor def task(): pri ...

  9. 【hihocoder1167】高等理论计算机科学 (重链剖分 +树状数组)

    Descroption 原题链接给你一棵\(~n~\)个点的树和\(~m~\)条链,求两两相交的链有多少对,两条链相交当且仅当有至少一个公共点.\(~1 \leq n, m \leq 10 ^ 5~\ ...

  10. 原生JS节点操作

    获取子节点 1. children 不是标准的dom属性,但是几乎被所有浏览器支持.获取子元素的元素节点(只包括元素节点) 注意:在IE中,children包含注释节点. 2. childNodes ...