我正在为我的应用程序使用简单的聊天模块,使用Spring WebFlux和后端的ReactiveMongoRepository以及前面的Angular 4。我能够通过WebSocketSession接收数据,但在从db传输所有消息后,我想保持连接,以便我可以更新消息列表。任何人都可以给我提供如何实现这一点的线索,或者我可能会遵循错误的假设吗?
Java Backend负责WebSocket,我的订阅者只记录当前状态,与此无关:
WebFluxConfiguration:
@Configuration
@EnableWebFlux
public class WebSocketConfig {
private final WebSocketHandler webSocketHandler;
@Autowired
public WebSocketConfig(WebSocketHandler webSocketHandler) {
this.webSocketHandler = webSocketHandler;
}
@Bean
@Primary
public HandlerMapping webSocketMapping() {
Map<String, Object> map = new HashMap<>();
map.put("/websocket-messages", webSocketHandler);
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(10);
mapping.setUrlMap(map);
return mapping;
}
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
}
WebSocketHandler实现
@Component
public class MessageWebSocketHandler implements WebSocketHandler {
private final MessageRepository messageRepository;
private ObjectMapper mapper = new ObjectMapper();
private MessageSubscriber subscriber = new MessageSubscriber();
@Autowired
public MessageWebSocketHandler(MessageRepository messageRepository) {
this.messageRepository = messageRepository;
}
@Override
public Mono<Void> handle(WebSocketSession session) {
session.receive()
.map(WebSocketMessage::getPayloadAsText)
.map(this::toMessage)
.subscribe(subscriber::onNext, subscriber:: onError, subscriber::onComplete);
return session.send(
messageRepository.findAll()
.map(this::toJSON)
.map(session::textMessage));
}
private String toJSON(Message message) {
try {
return mapper.writeValueAsString(message);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private Message toMessage(String json) {
try {
return mapper.readValue(json, Message.class);
} catch (IOException e) {
throw new RuntimeException("Invalid JSON:" + json, e);
}
}
}
和MongoRepo
@Repository
public interface MessageRepository extends
ReactiveMongoRepository<Message,String> {
}
前端处理:
@Injectable()
export class WebSocketService {
private subject: Rx.Subject<MessageEvent>;
constructor() {
}
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
console.log('Successfully connected: ' + url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent> {
const ws = new WebSocket(url);
const observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
});
const observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
};
return Rx.Subject.create(observer, observable);
}
}
在其他服务中我将observable从响应映射到我的类型
constructor(private wsService: WebSocketService) {
this.messages = <Subject<MessageEntity>>this.wsService
.connect('ws://localhost:8081/websocket-messages')
.map((response: MessageEvent): MessageEntity => {
const data = JSON.parse(response.data);
return new MessageEntity(data.id, data.user_id, data.username, data.message, data.links);
});
}
最后订阅了send函数,由于关闭连接我无法使用:
ngOnInit() {
this.messages = [];
this._ws_subscription = this.chatService.messages.subscribe(
(message: MessageEntity) => {
this.messages.push(message);
},
error2 => {
console.log(error2.json());
},
() => {
console.log('Closed');
}
);
}
sendTestMessage() {
this.chatService.messages.next(new MessageEntity(null, '59ca30ac87e77d0f38237739', 'mickl', 'test message angular', null));
}
答案 0 :(得分:1)
假设您的聊天消息在收到时被持久保存到数据存储区,您可以使用Spring Data MongoDB Reactive中的tailable游标功能(请参阅reference documentation)。
因此,您可以在存储库中创建一个新方法,如:
public interface MessageRepository extends ReactiveSortingRepository< Message, String> {
@Tailable
Flux<Message> findWithTailableCursor();
}
请注意,tailable游标有一些限制:您需要对mongo集合进行限制,并按照插入顺序对条目进行流式处理。
Spring WebFlux websocket支持尚不支持STOMP和消息代理,但对于这样的用例,这可能是更好的选择。