Spring Boot WebSocket 推送

一. 依赖 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
@EnableWebSocketMessageBroker
public 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
@SpringBootApplication
public class Application {

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

四. 服务器推送

@Controller
public 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

你可能感兴趣的:(Spring Boot WebSocket 推送)