refactor: 添加 websocket 连接认证拦截器实现点对点指定用户发送消息;移除 easy-captcha 替换为 hutool-captcha验证码实现代码简化;重构认证接口控制层代码。
This commit is contained in:
@@ -1,17 +1,16 @@
|
||||
package com.youlai.system.controller.demo;
|
||||
|
||||
import com.youlai.system.common.result.Result;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.messaging.handler.annotation.DestinationVariable;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.SendTo;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
/**
|
||||
* WebSocket 测试控制器
|
||||
*
|
||||
@@ -24,28 +23,35 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@Slf4j
|
||||
public class WebsocketController {
|
||||
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
|
||||
/**
|
||||
* 广播发送消息
|
||||
*
|
||||
* @param message 消息内容
|
||||
*/
|
||||
@MessageMapping("/sendToAll")
|
||||
@SendTo("/topic/all")
|
||||
@SendTo("/topic/notice")
|
||||
public String sendToAll(String message) {
|
||||
// 处理消息
|
||||
return "Hello, " + message + "!";
|
||||
return "System Notice: " + message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 点对点发送消息
|
||||
* <p>
|
||||
* 模拟 张三 给 李四 发送消息场景
|
||||
*
|
||||
* @param principal 当前用户
|
||||
* @param username 接收消息的用户
|
||||
* @param message 消息内容
|
||||
*/
|
||||
// 处理发送到"/app/sendToUser/{username}"的消息
|
||||
@MessageMapping("/sendToUser/{username}")
|
||||
// 将消息处理器的返回值发送到指定用户
|
||||
@SendTo("/queue/user")
|
||||
public String sendToUser(@DestinationVariable("username") String username, String message) {
|
||||
// 处理消息
|
||||
return "Hello, " + username + ", your message is: " + message;
|
||||
//@SendToUser(value = "/queue/greeting")
|
||||
public void sendToUser(Principal principal, @DestinationVariable String username, String message) {
|
||||
log.info("sender:{};receiver:{}", username, principal.getName());
|
||||
messagingTemplate.convertAndSendToUser(username, "/queue/greeting", "Hello," + message);
|
||||
/// return "Hello, " + message;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user