Spring Boot WebSocket 推送
发布日期:2021-08-22 06:43:22 浏览次数:1 分类:技术文章

本文共 4422 字,大约阅读时间需要 14 分钟。

一. 依赖 pom.xml

4.0.0
org.springframework
gs-messaging-stomp-websocket
0.1.0
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
org.springframework.boot
spring-boot-starter-websocket
org.webjars
webjars-locator-core
org.webjars
sockjs-client
1.0.2
org.webjars
stomp-websocket
2.3.3
org.webjars
bootstrap
3.3.7
org.webjars
jquery
3.1.0
org.springframework.boot
spring-boot-starter-test
test
1.8
org.springframework.boot
spring-boot-maven-plugin

二. webSocket配置

@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig implements WebSocketMessageBrokerConfigurer {    @Override    public void configureMessageBroker(MessageBrokerRegistry config) {        config.enableSimpleBroker("/topic");        config.setApplicationDestinationPrefixes("/app");    }    @Override    public void registerStompEndpoints(StompEndpointRegistry registry) {        registry.addEndpoint("/gs-guide-websocket").withSockJS();    }}

三. 定时能力打开

@EnableScheduling@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

四. 服务器推送

@Controllerpublic class GreetingController {    // boot自动配置    @Autowired    private SimpMessagingTemplate messagingTemplate;    @MessageMapping("/hello")    @SendTo("/topic/greetings")    public Greeting greeting(HelloMessage message) throws Exception {        Thread.sleep(1000); // simulated delay        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");    }    /**     * 向订阅/topic/greetings 推送消息     * @throws Exception     */    @Scheduled(fixedRate = 1000)    public void greeting1() throws Exception {        messagingTemplate.convertAndSend("/topic/greetings", new Greeting("Hello, fixedRate !"));    }}

五 js订阅

var stompClient = null;function setConnected(connected) {    $("#connect").prop("disabled", connected);    $("#disconnect").prop("disabled", !connected);    if (connected) {        $("#conversation").show();    }    else {        $("#conversation").hide();    }    $("#greetings").html("");}function connect() {    var socket = new SockJS('/gs-guide-websocket');    stompClient = Stomp.over(socket);    stompClient.connect({}, function (frame) {        setConnected(true);        console.log('Connected: ' + frame);        stompClient.subscribe('/topic/greetings', function (greeting) {            showGreeting(JSON.parse(greeting.body).content);        });    });}function disconnect() {    if (stompClient !== null) {        stompClient.disconnect();    }    setConnected(false);    console.log("Disconnected");}function sendName() {    stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));}function showGreeting(message) {    $("#greetings").append("" + message + "");}$(function () {    $("form").on('submit', function (e) {        e.preventDefault();    });    $( "#connect" ).click(function() { connect(); });    $( "#disconnect" ).click(function() { disconnect(); });    $( "#send" ).click(function() { sendName(); });});

QQ交流群869658872

转载地址:https://blog.csdn.net/weixin_33738555/article/details/89625599 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:telnet使用
下一篇:Redis设计与实现学习总结

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月12日 12时58分50秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章