如何搭建springboot+websocket+redis
本篇内容主要讲解“如何搭建springboot+websocket+redis”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何搭建springboot+websocket+redis”吧!
在多负载环境下使用websocket。
一、原因
在某些业务场景,我们需要页面对于后台的操作进行实时的刷新,这时候就需要使用websocket。
通常在后台单机的情况下没有任何的问题,如果后台经过nginx等进行负载的话,则会导致前台不能准备的接收到后台给与的响应。socket属于长连接,其session只会保存在一台服务器上,其他负载及其不会持有这个session,此时,我们需要使用redis的发布订阅来实现,session的共享。
二、环境准备
在https://mvnrepository.com/里,查找websocket的依赖。使用springboot的starter依赖,注意对应自己springboot的版本。
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.2.10.RELEASE</version></dependency>
除此之外添加redis的依赖,也使用starter版本:
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
三、代码
redis监听配置:
@Configurationpublic class RedisConfig { @Bean public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); return container; }}
webSocket配置:
@Configurationpublic class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); }}
redis工具类:
@Componentpublic class RedisUtil { @Autowired private StringRedisTemplate stringRedisTemplate; public void publish(String key, String value) { stringRedisTemplate.convertAndSend(key, value); }}
WebSocket服务提供类:
@Slf4j@Component@ServerEndpoint("/websocket/server/{loginName}")public class WebSocketServer { private RedisMessageListenerContainer redisMessageListenerContainer = ApplicationContextProvider.getBean(RedisMessageListenerContainer.class); private static AtomicInteger onlineCount = new AtomicInteger(0); private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); private Session session; private SubscribeListener subscribeListener; @OnOpen public void onOpen(@PathParam("loginName") String loginName, Session session) { this.session = session; //加入set中 webSocketSet.add(this); //在线数加1 addOnlineCount(); log.info("有新连接[" + loginName + "]加入!当前在线人数为{}", getOnlineCount()); subscribeListener = new SubscribeListener(); subscribeListener.setSession(session); //设置订阅topic redisMessageListenerContainer.addMessageListener( subscribeListener, new ChannelTopic(Constants.TOPIC_PREFIX + loginName)); } @OnClose public void onClose() throws IOException { //从set中删除 webSocketSet.remove(this); //在线数减1 subOnlineCount(); redisMessageListenerContainer.removeMessageListener(subscribeListener); log.info("有一连接关闭!当前在线人数为{}", getOnlineCount()); } @OnMessage public void onMessage(String message, Session session) { log.info("来自客户端的消息:{}", message); //群发消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { log.info("发送消息异常:msg = {}", e); continue; } } } @OnError public void onError(Session session, Throwable error) { log.info("发生错误,{}", error); } public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } public int getOnlineCount() { return onlineCount.get(); } public void addOnlineCount() { WebSocketServer.onlineCount.getAndIncrement(); } public void subOnlineCount() { WebSocketServer.onlineCount.getAndDecrement(); }}
redis消息发布:
@Autowired private RedisUtil redisUtil; @Override public Result send(String loginName, String msg) { //推送站内信webSocket redisUtil.publish("TOPIC" + loginName, msg); return Result.success(); }
前端vue代码:
<template> <div class="dashboard-container"> <div class="dashboard-text">消息内容: {{ responseData }}</div> </div></template><script> import {mapGetters} from 'vuex' export default { data() { return { websocket: null, responseData: null } }, created() { this.initWebSocket(); }, destroyed() { this.websock.close() //离开路由之后断开websocket连接 }, methods: { //初始化websocket initWebSocket() { const wsUri = "ws://127.0.0.1:21116/websocket/server/" + "admin"; this.websock = new WebSocket(wsUri); this.websock.onmessage = this.websocketonmessage; this.websock.onopen = this.websocketonopen; this.websock.onerror = this.websocketonerror; this.websock.onclose = this.websocketclose; }, websocketonopen() { //连接建立之后执行send方法发送数据 let actions = {"用户账号": "admin"}; this.websocketsend(JSON.stringify(actions)); }, websocketonerror() {//连接建立失败重连 this.initWebSocket(); }, websocketonmessage(e) { //数据接收 const redata = JSON.parse(e.data); this.responseData = redata; }, websocketsend(Data) {//数据发送 this.websock.send(Data); }, websocketclose(e) { //关闭 console.log('断开连接', e); }, }, name: 'Dashboard', computed: { ...mapGetters([ 'name', 'roles' ]) } }</script>
四、测试
发送前
发送后
到此,相信大家对“如何搭建springboot+websocket+redis”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341