闹着玩的来源:前台发送消息,后台接受处理发给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. vue-cli(vue脚手架)

    vue-cli用于自动生成vue+webpack项目. 安装webpack:npm install webpack -g 检查webpack是否安装成功和版本:webpack -v 如果是webpac ...

  2. Jenkins+PowerShell持续集成环境搭建(六)参数化构建

    参数化构建可以应用于动态绑定源码地址等情况. 勾选“This build is parameterized”: 如果需要动态绑定源码地址,参考: 配置完成后构建项目变成:

  3. 【C/C++】C/C++中的数组是怎么实现的?

    几乎所有的语言都把数组作为一种固有的数据类型,数组也是我们最常用的数据结构之一.在语言底层,数组是如何实现的呢?本文以抽象数据类型的形式,定义.实现数组. 创建数组,理论上,我们可以使用创建任意维度的 ...

  4. Spring 使用介绍(十)—— 单元测试

    一.概述 Spring测试框架提供了对单元测试的支持,以便使用spring的依赖注入和事务管理功能 maven依赖: <dependency> <groupId>junit&l ...

  5. Spring Security 学习总结

    Spring Security Spring Security是基于Spring提供声明式安全保护的安全性框架.Spring Security提供了完整的安全性解决方案,能够在Web请求级别和方法调用 ...

  6. Luogu5245 【模板】多项式快速幂(多项式exp)

    A(x)k=eklnA(x).泰勒展开之后容易发现k并非在指数上,所以对p取模. #include<iostream> #include<cstdio> #include< ...

  7. PHP linux ZendGuardLoader.so: undefined symbol: executor_globals

    /usr/xxx/php    xxx/xxx.php 报了这个错. 本人出现此问题的原因:  php执行程序路径错了. 解决: linux下执行   which php   命令  查看php真实路 ...

  8. PHP 事务写法

    $md=new Model(); //创建事务 $md->startTrans(); //开始事务 $md->table("ym_xxx")->where(&qu ...

  9. JXOI2017颜色

    题面 loj 分析 这道题非常妙啊 对于可保留区间[l, r] 枚举右端点r 考虑l的取值范围有两重约数 记颜色i出现的最右侧位置是\(max_i\) 最左侧位置是\(min_i\) r前最后一次出现 ...

  10. Hdoj 2199.Can you solve this equation? 题解

    Problem Description Now,given the equation 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,can you find its solutio ...