需要在春季将Websocket连接到数据库的帮助

时间:2019-04-03 19:21:07

标签: database spring spring-boot

我需要在春季启动中将WebSocket连接到数据库的帮助。

我知道数据库访问发生在控制器中,但我不知道如何。

@Controller
public class ChatController {

    @MessageMapping("/chat.register")
    @SendTo("/topic/public")
    public ChatMessage register(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        return chatMessage;

    }

    @MessageMapping("/chat.send")
    @SendTo("/topic/public")
    public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
        return chatMessage;
    } 

}

我将在哪里连接到数据库

1 个答案:

答案 0 :(得分:0)

将存储库添加到控制器不是一个好主意。更好的方法是在控制器和数据库之间添加服务层。

@Controller
public class ChatController {

@Autowired
private Chatservice chatservice;

    @MessageMapping("/chat.register")
    @SendTo("/topic/public")
    public ChatMessage register(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        chatservice.saveChatMessage(chatMessage); // save this too?
        return chatMessage;

    }

    @MessageMapping("/chat.send")
    @SendTo("/topic/public")
    public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
        chatservice.saveChatMessage(chatMessage);
        return chatMessage;
    } 

}

@Service
private class ChatService {

@Autowired
private ChatRepository repository;

public void saveChatMessage(ChatMessage chatMessage) {
  // do more business stuff here e.g. Mapping to Entity ....
  repository.save(chatMessage);
}

}

public interface ChatRepository extends CrudRepository<ChatMessage, Long>  {
}