Spring Reactive WebSocket

在某些场景下 我们会使用webSocket 去做数据的实时动态对接,http协议 与长链接(Server Sent Event)都解决不了此类问题。

下面介绍一下基于Spring Reactive 的WebSocket Server 端和client端的简单实现。

Server 端:

@SpringBootApplication
public class PracticeApplication {

	public static void main(String[] args) {
		System.setProperty("spring.profiles.active", "wsserver");
		SpringApplication.run(PracticeApplication.class, args);
	}


	//WebSocket
	@Bean
	SimpleUrlHandlerMapping greetingsHm() {
		Map<String,WebSocketHandler> webSocketHandlerMap = new HashMap<>();
		webSocketHandlerMap.put("/ws/greetings", greetingsWsh());
		return new SimpleUrlHandlerMapping(webSocketHandlerMap, 10);
	}

	@Bean
	WebSocketHandler greetingsWsh() {
		return session -> {

			Flux<WebSocketMessage> out = session.receive().map(WebSocketMessage::getPayloadAsText)
												.flatMap(name -> Flux.just("Hi, " + name).map(session::textMessage));

			return session.send(out);
		};
	}

}

  Client 端:

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

		System.setProperty("spring.profiles.active", "wsclient");
		SpringApplication.run(DemoApplication.class, args);
	}

	@Bean
	WebSocketClient webSocketClient() {
		return new ReactorNettyWebSocketClient();
	}

	@Bean
	ApplicationListener<ApplicationReadyEvent> ready(WebSocketClient client) {
		return event -> client.execute(URI.create("ws://localhost:8080/ws/greetings"), webSocketSession -> {
			List<String> name = Arrays.asList("a","b","c","d");
			WebSocketMessage[] webSocketMessages = new WebSocketMessage[4];
					name.stream().map(fan->webSocketSession.textMessage(fan)).collect(Collectors.toList()).toArray(webSocketMessages);
			return webSocketSession.send(Flux.fromArray(webSocketMessages))
								   .thenMany(webSocketSession.receive().map(WebSocketMessage::getPayloadAsText).log()).then();
		}).subscribe();
	}

}

  

posted on 2021-02-03 21:29  涤生-三省吾身  阅读(495)  评论(0编辑  收藏  举报

导航