首页 > 编程语言 > 详细

Spring Reactive WebSocket

时间:2021-02-03 23:18:14      阅读:36      评论:0      收藏:0      [点我收藏+]

在某些场景下 我们会使用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();
	}

}

  

Spring Reactive WebSocket

原文:https://www.cnblogs.com/lgtrajectory/p/14369860.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!