Forráskód Böngészése

feat:小节评分

Joburgess 4 éve
szülő
commit
f1a611c21f

+ 19 - 39
mec-teacher/src/main/java/com/ym/mec/teacher/config/WebSocketConfig.java

@@ -1,60 +1,40 @@
 package com.ym.mec.teacher.config;
 
-import com.ym.mec.teacher.handler.CustomPrincipalHandshakeHandler;
-import com.ym.mec.teacher.handler.SoundHandler;
-import com.ym.mec.teacher.interceptor.WebSocketChannelInterceptor;
+import com.ym.mec.teacher.handler.WebSocketHandler;
 import com.ym.mec.teacher.interceptor.WebSocketHandshakeInterceptor;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
-import org.springframework.messaging.simp.config.ChannelRegistration;
-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;
+import org.springframework.web.socket.config.annotation.EnableWebSocket;
+import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
+import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
+import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
 
 /**
  * @Author Joburgess
  * @Date 2021/6/8 0008
  */
 @Configuration
-@EnableWebSocketMessageBroker
-public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
+@EnableWebSocket
+public class WebSocketConfig implements WebSocketConfigurer {
 
     @Autowired
+    private WebSocketHandler webSocketHandler;
+    @Autowired
     private WebSocketHandshakeInterceptor webSocketHandshakeInterceptor;
 
     @Override
-    public void registerStompEndpoints(StompEndpointRegistry registry) {
-        registry.addEndpoint("/soundWebSocket")
-                .addInterceptors(webSocketHandshakeInterceptor)
-                .setHandshakeHandler(new CustomPrincipalHandshakeHandler())
-                .setAllowedOrigins("*");
+    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
+        webSocketHandlerRegistry.addHandler(webSocketHandler, "/ws")
+                .addInterceptors(webSocketHandshakeInterceptor);
     }
 
-    @Override
-    public void configureMessageBroker(MessageBrokerRegistry config) {
-        // prefix for subscribe
-        config.enableSimpleBroker("/topic");
-        // prefix for send
-        config.setApplicationDestinationPrefixes("/push");
+    @Bean
+    public ServletServerContainerFactoryBean createWebSocketContainer() {
+        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
+        container.setMaxTextMessageBufferSize(8192*4);
+        container.setMaxBinaryMessageBufferSize(8192*4);
+        return container;
     }
 
-    @Override
-    public void configureClientInboundChannel(ChannelRegistration registration) {
-        /*
-         * 配置消息线程池
-         * 1、corePoolSize() 配置核心线程池, 当线程数小于此配置时, 不管线程中有无空闲的线程, 都会产生新线程处理任务
-         * 2、maxPoolSize() 配置线程池最大数, 当线程池等于此配置时, 不会产生新线程
-         * 3、keepAliveSeconds() 线程池维护线程所允许的空闲时间, 单位为秒
-         */
-        registration.taskExecutor()
-                .corePoolSize(10)
-                .maxPoolSize(20)
-                .keepAliveSeconds(60);
-        /*
-         * 添加STOMP自定义拦截器
-         * 消息拦截器, 实现ChannelInterceptor接口
-         */
-        registration.interceptors(new WebSocketChannelInterceptor());
-    }
 }

+ 0 - 63
mec-teacher/src/main/java/com/ym/mec/teacher/handler/CustomPrincipalHandshakeHandler.java

@@ -1,63 +0,0 @@
-package com.ym.mec.teacher.handler;
-
-import org.springframework.http.server.ServerHttpRequest;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.web.socket.WebSocketHandler;
-import org.springframework.web.socket.server.RequestUpgradeStrategy;
-import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
-
-import java.security.Principal;
-import java.util.Map;
-
-/**
- * @Author Joburgess
- * @Date 2021/6/15 0015
- */
-public class CustomPrincipalHandshakeHandler extends DefaultHandshakeHandler {
-
-    public CustomPrincipalHandshakeHandler() {
-    }
-
-    public CustomPrincipalHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) {
-        super(requestUpgradeStrategy);
-    }
-
-    @Override
-    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
-        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
-        CustomPrincipalPrincipal principal = new CustomPrincipalPrincipal();
-        principal.setName(authentication.getName().split(":")[1]);
-        return principal;
-    }
-
-    class CustomPrincipalPrincipal implements Principal {
-        private String name;
-
-        @Override
-        public String getName() {
-            return name;
-        }
-
-        public void setName(String name) {
-            this.name = name;
-        }
-
-        @Override
-        public boolean equals(Object o) {
-            if (this == o) return true;
-            if (o == null || getClass() != o.getClass()) return false;
-
-            CustomPrincipalPrincipal that = (CustomPrincipalPrincipal) o;
-
-            return name != null ? name.equals(that.name) : that.name == null;
-
-        }
-
-        @Override
-        public int hashCode() {
-            return name != null ? name.hashCode() : 0;
-        }
-    }
-
-}

+ 0 - 63
mec-teacher/src/main/java/com/ym/mec/teacher/handler/CustomSubProtocolWebSocketHandler.java

@@ -1,63 +0,0 @@
-package com.ym.mec.teacher.handler;
-
-import com.alibaba.fastjson.JSONObject;
-import com.ym.mec.teacher.interceptor.WebSocketChannelInterceptor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.messaging.MessageChannel;
-import org.springframework.messaging.SubscribableChannel;
-import org.springframework.web.socket.CloseStatus;
-import org.springframework.web.socket.WebSocketSession;
-import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler;
-
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * @Author Joburgess
- * @Date 2021/6/15 0015
- */
-public class CustomSubProtocolWebSocketHandler extends SubProtocolWebSocketHandler {
-
-    private final Logger LOGGER = LoggerFactory.getLogger(SubProtocolWebSocketHandler.class);
-
-    /**
-     * Create a new {@code SubProtocolWebSocketHandler} for the given inbound and outbound channels.
-     * @param clientInboundChannel the inbound {@code MessageChannel}
-     * @param clientOutboundChannel the outbound {@code MessageChannel}
-     */
-    public CustomSubProtocolWebSocketHandler(MessageChannel clientInboundChannel, SubscribableChannel clientOutboundChannel) {
-        super(clientInboundChannel, clientOutboundChannel);
-    }
-
-    /**
-     * 建立连接成功之后执行的方法
-     * @param session 处理器
-     * @throws Exception 异常
-     */
-    @Override
-    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
-        LOGGER.info("afterConnectionEstablished: connection established -- session --> {}", session);
-        if (Objects.isNull(session) || Objects.isNull(session.getPrincipal())) {
-            LOGGER.warn("afterConnectionEstablished: session is null or user is null -- session --> {}", session);
-            return;
-        }
-        Map<String, Object> attributes = session.getAttributes();
-        String sessionId = session.getId();
-        LOGGER.info("afterConnectionEstablished: attributes -->{}, sessionId --> {}", JSONObject.toJSONString(attributes), session);
-        attributes.put("clientId", sessionId);
-        super.afterConnectionEstablished(session);
-    }
-
-    /**
-     * 在关闭连接之后调用
-     * @param session WebSocket处理器
-     * @param closeStatus 状态
-     * @throws Exception 异常
-     */
-    @Override
-    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
-        LOGGER.info("afterConnectionClosed: close -- closeStatus --> {}", closeStatus);
-        super.afterConnectionClosed(session, closeStatus);
-    }
-}

+ 3 - 4
mec-teacher/src/main/java/com/ym/mec/teacher/handler/SoundHandler.java → mec-teacher/src/main/java/com/ym/mec/teacher/handler/WebSocketHandler.java

@@ -5,7 +5,6 @@ import com.ym.mec.auth.api.entity.SysUser;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Service;
 import org.springframework.web.socket.*;
 import org.springframework.web.socket.handler.AbstractWebSocketHandler;
@@ -19,15 +18,15 @@ import java.util.concurrent.ConcurrentHashMap;
  * @Date 2021/6/9 0009
  */
 @Service
-public class SoundHandler extends AbstractWebSocketHandler {
+public class WebSocketHandler extends AbstractWebSocketHandler {
 
-    private static final Logger LOGGER = LoggerFactory.getLogger(SoundHandler.class);
+    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketHandler.class);
 
     private final Map<String, WebSocketSession> clients = new ConcurrentHashMap<>();
     @Autowired
     private SysUserFeignService sysUserFeignService;
 
-    public SoundHandler() {
+    public WebSocketHandler() {
         super();
     }
 

+ 0 - 80
mec-teacher/src/main/java/com/ym/mec/teacher/interceptor/WebSocketChannelInterceptor.java

@@ -1,80 +0,0 @@
-package com.ym.mec.teacher.interceptor;
-
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.messaging.Message;
-import org.springframework.messaging.MessageChannel;
-import org.springframework.messaging.simp.stomp.StompCommand;
-import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
-import org.springframework.messaging.support.ChannelInterceptor;
-import org.springframework.messaging.support.MessageHeaderAccessor;
-
-import java.util.List;
-import java.util.Optional;
-
-/**
- * @Author Joburgess
- * @Date 2021/6/15 0015
- */
-public class WebSocketChannelInterceptor implements ChannelInterceptor {
-
-    private final Logger LOGGER = LoggerFactory.getLogger(WebSocketChannelInterceptor.class);
-
-    /**
-     * 在消息发送之前执行, 如果此方法返回值为空, 则不会发生实际的消息发送
-     * @param message 消息
-     * @param channel 通道
-     * @return 消息
-     */
-    @Override
-    public Message<?> preSend(Message<?> message, MessageChannel channel) {
-        StompHeaderAccessor stompHeader = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
-        /*
-         * 判断是否首次连接请求, 如果已经连接, 返回message
-         */
-        if (StompCommand.CONNECT.equals(stompHeader.getCommand())) {//首次连接
-            LOGGER.info("preSend: {} connected", stompHeader.getUser().getName());
-        } else if (StompCommand.DISCONNECT.equals(stompHeader.getCommand())) {//断开连接
-            LOGGER.info("preSend: {} close connect", stompHeader.getUser().getName());
-        }
-        return message;
-    }
-
-    /**
-     * 在消息被实际检索之前调用, 在WebSocket场景中应用不到
-     * @param channel 通道
-     * @return false: 不会检索任何消息
-     */
-    @Override
-    public boolean preReceive(MessageChannel channel) {
-        return true;
-    }
-
-    /**
-     * 在检索到消息之后, 返回调用方法之前调用, 可以进行消息修改, 如果返回null, 就不会执行下一步操作
-     * @param message 消息
-     * @param channel 通道
-     * @return 消息
-     */
-    @Override
-    public Message<?> postReceive(Message<?> message, MessageChannel channel) {
-        return message;
-    }
-
-    /**
-     * 在消息发送后立刻调用
-     * @param message 消息
-     * @param channel 通道
-     * @param sent 表示调用的返回值
-     */
-    @Override
-    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
-        /*StompHeaderAccessor stompHeader = StompHeaderAccessor.wrap(message);
-        if (Objects.isNull(stompHeader.getCommand())) {//心跳消息
-            return;
-        }
-        log.info("postSend -- command --> {}", stompHeader.getCommand());*/
-    }
-
-}