springboot 통합 웹 소켓 (stompjs)

5452 단어 자바고급
1. pom 의존

    org.springframework.boot
    spring-boot-starter-websocket

2. websocket 설정 클래스
package cn.longrace.wisdom.common.websocket;

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;

@Configuration
@EnableWebSocketMessageBroker  //    STOMP            ,         @MessageMapping
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //     socketJs    ,    webSocketServer,    
        //                
        // http://localhost:9999/webSocketServer      WebSocket  
        registry.addEndpoint("/webSocketServer").setAllowedOrigins("*");
        //   stompjs,              ,     ,           ,
        //     vue      ws  ,     http  , :          // Vue.prototype.$globalWebsocketUrl= ws://localhost:8080/wisdom-classrome/webSocketServer         // registry.addEndpoint("/webSocketServer").setAllowedOrigins("*").withSockJS();    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        ///               ,                    
        registry.enableSimpleBroker("/topic","/user");
        //                      "/app", /app        @MessageMapping        
        registry.setApplicationDestinationPrefixes("/app");
        //             /user/
        registry.setUserDestinationPrefix("/user/");
    }
}

3. 메 시 지 를 수신 하고 메 시 지 를 보 내 는 컨트롤 러 클래스
package cn.longrace.wisdom.common.websocket;


import cn.longrace.wisdom.common.vo.R;
import cn.longrace.wisdom.modules.dataBase.entity.StudentEntity;
import cn.longrace.wisdom.modules.teacher.member.entity.TeacherActivityClassPerformanceEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

/**
 *
 * @ClassName: WebSocketAction
 * @Description: websocket   
 * @author cheng
 * @date 2017 9 27    4:20:58
 */
@RestController
@RequestMapping("webSocket")
public class WebSocketAction{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     *              
     * path: /handsUp  ,/rushToAnswer  
     */
    @MessageMapping("/handsUp")
    public void handsUpMessage (@RequestParam(name = "msg")String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String studentId = jsonObject.getString("id");
        String name = jsonObject.getString("name");
        String teacherId = jsonObject.getString("teacherId");
        String type = jsonObject.getString("type");
        String path = jsonObject.getString("path");

        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setId(Long.parseLong(studentId));
        studentEntity.setName(name);
        studentEntity.setTeacherId(Long.parseLong(teacherId));
        System.out.println(type + "chatMessage.getReceiver()------------------"+studentEntity);
        //          
        messagingTemplate.convertAndSendToUser(studentId, path, studentEntity);
//        messagingTemplate.convertAndSendToUser(String.valueOf(studentEntity.getId().longValue()),"/handsUp",studentEntity); //          
    }

    /**
     *   
     * @param performanceEntity
     */
    @GetMapping("/groupSending")
    @RequiresRoles("teacher")
    public R groupSending (TeacherActivityClassPerformanceEntity performanceEntity) {
        String topic = "/topic/"+performanceEntity.getCurriculumId()+"/"+performanceEntity.getGradeId();
//        performanceEntity.setType(0);
        messagingTemplate.convertAndSend(topic, JSON.toJSONString(performanceEntity));
        return R.ok();
    }

    /**
     *         id
     * @param performanceEntity
     * @return
     */
    @GetMapping("/pushCurriculumId")
    public R pushCurriculumId (TeacherActivityClassPerformanceEntity performanceEntity) {
        String topic = "/topic/"+performanceEntity.getGradeId();
        messagingTemplate.convertAndSend(topic, JSON.toJSONString(performanceEntity));
        return R.ok();
    }

    /**
     *    
     */
    @RequestMapping("/sendStudentId")
    public void groupSending (@RequestParam(value = "studentId",required = false) Long studentId) {
        messagingTemplate.convertAndSend("/topic/comparisonFace", studentId);
    }
}

좋은 웹페이지 즐겨찾기