SpringBoot+WebSocket+Netty實現訊息推送的示例程式碼
上一篇文章講了Netty的理論基礎,這一篇講一下Netty在專案中的應用場景之一:訊息推送功能,可以滿足給所有使用者推送,也可以滿足給指定某一個使用者推送訊息,建立的是SpringBoot專案,後臺服務端使用Netty技術,前端頁面使用WebSocket技術。
大概實現思路:
- 前端使用webSocket與服務端建立連線的時候,將使用者ID傳給服務端
- 服務端將使用者ID與channel關聯起來儲存,同時將channel放入到channel組中
- 如果需要給所有使用者傳送訊息,直接執行channel組的writeAndFlush()方法
- 如果需要給指定使用者傳送訊息,根據使用者ID查詢到對應的channel,然後執行writeAndFlush()方法
- 前端獲取到服務端推送的訊息之後,將訊息內容展示到文字域中
下面是具體的程式碼實現,基本上每一步操作都配有註釋說明,配合註釋看應該還是比較容易理解的。
第零步:引入Netty的依賴,和一個工具包(只用到了json工具,可用其他json工具代替)
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.33.Final</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.2.3</version> </dependency>
第一步:在NettyConfig中定義一個channel組,管理所有的channel,再定義一個map,管理使用者與channel的對應關係。
package com.sixj.nettypush.config; import io.netty.channel.Channel; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.util.concurrent.GlobalEventExecutor; import java.util.concurrent.ConcurrentHashMap; /** * @author sixiaojie * @date 2020-03-28-15:07 */ public class NettyConfig { /** * 定義一個channel組,管理所有的channel * GlobalEventExecutor.INSTANCE 是全域性的事件執行器,是一個單例 */ private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); /** * 存放使用者與Chanel的對應資訊,用於給指定使用者傳送訊息 */ private static ConcurrentHashMap<String,Channel> userChannelMap = new ConcurrentHashMap<>(); private NettyConfig() {} /** * 獲取channel組 * @return */ public static ChannelGroup getChannelGroup() { return channelGroup; } /** * 獲取使用者channel map * @return */ public static ConcurrentHashMap<String,Channel> getUserChannelMap(){ return userChannelMap; } }
第二步:建立NettyServer,定義兩個EventLoopGroup,bossGroup輔助客戶端的tcp連線請求,workGroup負責與客戶端之前的讀寫操作,需要說明的是,需要開啟一個新的執行緒來執行netty server,要不然會阻塞主執行緒,到時候就無法呼叫專案的其他controller介面了。
package com.sixj.nettypush.websocket; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.serialization.ObjectEncoder; import io.netty.handler.stream.ChunkedWriteHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.net.InetSocketAddress; /** * @author sixiaojie * @date 2020-03-28-13:44 */ @Component public class NettyServer{ private static final Logger log = LoggerFactory.getLogger(NettyServer.class); /** * webSocket協議名 */ private static final String WEBSOCKET_PROTOCOL = "WebSocket"; /** * 埠號 */ @Value("${webSocket.netty.port:58080}") private int port; /** * webSocket路徑 */ @Value("${webSocket.netty.path:/webSocket}") private String webSocketPath; @Autowired private WebSocketHandler webSocketHandler; private EventLoopGroup bossGroup; private EventLoopGroup workGroup; /** * 啟動 * @throws InterruptedException */ private void start() throws InterruptedException { bossGroup = new NioEventLoopGroup(); workGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); // bossGroup輔助客戶端的tcp連線請求,workGroup負責與客戶端之前的讀寫操作 bootstrap.group(bossGroup,workGroup); // 設定NIO型別的channel bootstrap.channel(NioServerSocketChannel.class); // 設定監聽埠 bootstrap.localAddress(new InetSocketAddress(port)); // 連線到達時會建立一個通道 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 流水線管理通道中的處理程式(Handler),用來處理業務 // webSocket協議本身是基於http協議的,所以這邊也要使用http編解碼器 ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast(new ObjectEncoder()); // 以塊的方式來寫的處理器 ch.pipeline().addLast(new ChunkedWriteHandler()); /* 說明: 1、http資料在傳輸過程中是分段的,HttpObjectAggregator可以將多個段聚合 2、這就是為什麼,當瀏覽器傳送大量資料時,就會發送多次http請求 */ ch.pipeline().addLast(new HttpObjectAggregator(8192)); /* 說明: 1、對應webSocket,它的資料是以幀(frame)的形式傳遞 2、瀏覽器請求時 ws://localhost:58080/xxx 表示請求的uri 3、核心功能是將http協議升級為ws協議,保持長連線 */ ch.pipeline().addLast(new WebSocketServerProtocolHandler(webSocketPath,WEBSOCKET_PROTOCOL,true,65536 * 10)); // 自定義的handler,處理業務邏輯 ch.pipeline().addLast(webSocketHandler); } }); // 配置完成,開始繫結server,通過呼叫sync同步方法阻塞直到繫結成功 ChannelFuture channelFuture = bootstrap.bind().sync(); log.info("Server started and listen on:{}",channelFuture.channel().localAddress()); // 對關閉通道進行監聽 channelFuture.channel().closeFuture().sync(); } /** * 釋放資源 * @throws InterruptedException */ @PreDestroy public void destroy() throws InterruptedException { if(bossGroup != null){ bossGroup.shutdownGracefully().sync(); } if(workGroup != null){ workGroup.shutdownGracefully().sync(); } } @PostConstruct() public void init() { //需要開啟一個新的執行緒來執行netty server 伺服器 new Thread(() -> { try { start(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }
第三步: 具體實現業務的WebSocketHandler,具體實現邏輯看註釋
package com.sixj.nettypush.websocket; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.sixj.nettypush.config.NettyConfig; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.AttributeKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * TextWebSocketFrame型別, 表示一個文字幀 * @author sixiaojie * @date 2020-03-28-13:47 */ @Component @ChannelHandler.Sharable public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private static final Logger log = LoggerFactory.getLogger(NettyServer.class); /** * 一旦連線,第一個被執行 * @param ctx * @throws Exception */ @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { log.info("handlerAdded 被呼叫"+ctx.channel().id().asLongText()); // 新增到channelGroup 通道組 NettyConfig.getChannelGroup().add(ctx.channel()); } /** * 讀取資料 */ @Override protected void channelRead0(ChannelHandlerContext ctx,TextWebSocketFrame msg) throws Exception { log.info("伺服器收到訊息:{}",msg.text()); // 獲取使用者ID,關聯channel JSONObject jsonObject = JSONUtil.parseObj(msg.text()); String uid = jsonObject.getStr("uid"); NettyConfig.getUserChannelMap().put(uid,ctx.channel()); // 將使用者ID作為自定義屬性加入到channel中,方便隨時channel中獲取使用者ID AttributeKey<String> key = AttributeKey.valueOf("userId"); ctx.channel().attr(key).setIfAbsent(uid); // 回覆訊息 ctx.channel().writeAndFlush(new TextWebSocketFrame("伺服器連線成功!")); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { log.info("handlerRemoved 被呼叫"+ctx.channel().id().asLongText()); // 刪除通道 NettyConfig.getChannelGroup().remove(ctx.channel()); removeUserId(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception { log.info("異常:{}",cause.getMessage()); // 刪除通道 NettyConfig.getChannelGroup().remove(ctx.channel()); removeUserId(ctx); ctx.close(); } /** * 刪除使用者與channel的對應關係 * @param ctx */ private void removeUserId(ChannelHandlerContext ctx){ AttributeKey<String> key = AttributeKey.valueOf("userId"); String userId = ctx.channel().attr(key).get(); NettyConfig.getUserChannelMap().remove(userId); } } **第四步:**具體訊息推送的介面 public interface PushService { /** * 推送給指定使用者 * @param userId * @param msg */ void pushMsgToOne(String userId,String msg); /** * 推送給所有使用者 * @param msg */ void pushMsgToAll(String msg); }
介面實現類:
import java.util.concurrent.ConcurrentHashMap; /** * @author sixiaojie * @date 2020-03-30-20:10 */ @Service public class PushServiceImpl implements PushService { @Override public void pushMsgToOne(String userId,String msg){ ConcurrentHashMap<String,Channel> userChannelMap = NettyConfig.getUserChannelMap(); Channel channel = userChannelMap.get(userId); channel.writeAndFlush(new TextWebSocketFrame(msg)); } @Override public void pushMsgToAll(String msg){ NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg)); } }
controller:
package com.sixj.nettypush.controller; import com.sixj.nettypush.service.PushService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author sixiaojie * @date 2020-03-30-20:08 */ @RestController @RequestMapping("/push") public class PushController { @Autowired private PushService pushService; /** * 推送給所有使用者 * @param msg */ @PostMapping("/pushAll") public void pushToAll(@RequestParam("msg") String msg){ pushService.pushMsgToAll(msg); } /** * 推送給指定使用者 * @param userId * @param msg */ @PostMapping("/pushOne") public void pushMsgToOne(@RequestParam("userId") String userId,@RequestParam("msg") String msg){ pushService.pushMsgToOne(userId,msg); } }
第五步:前端html頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> var socket; // 判斷當前瀏覽器是否支援webSocket if(window.WebSocket){ socket = new WebSocket("ws://192.168.174.25:58080/webSocket") // 相當於channel的read事件,ev 收到伺服器回送的訊息 socket.onmessage = function (ev) { var rt = document.getElementById("responseText"); rt.value = rt.value + "\n" + ev.data; } // 相當於連線開啟 socket.onopen = function (ev) { var rt = document.getElementById("responseText"); rt.value = "連線開啟了..." socket.send( JSON.stringify({ // 連線成功將,使用者ID傳給服務端 uid: "123456" }) ); } // 相當於連線關閉 socket.onclose = function (ev) { var rt = document.getElementById("responseText"); rt.value = rt.value + "\n" + "連線關閉了..."; } }else{ alert("當前瀏覽器不支援webSocket") } </script> <form onsubmit="return false"> <textarea id="responseText" style="height: 150px; width: 300px;"></textarea> <input type="button" value="清空內容" onclick="document.getElementById('responseText').value=''"> </form> </body> </html>
目前為止,所有程式碼已經寫完了,測試一下
首先執行這個html檔案,會看到服務端給前端返回的訊息“伺服器連線成功了!”,後端日誌會列印伺服器收到訊息:{"uid":"123456"}
然後使用postman測試推送的介面
測試成功,打完收工
到此這篇關於SpringBoot+WebSocket+Netty實現訊息推送的示例程式碼的文章就介紹到這了,更多相關SpringBoot+WebSocket+Netty訊息推送內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!