日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的方法

這篇文章主要講解了SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的方法,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

南沙網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),南沙網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為南沙上千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的南沙做網(wǎng)站的公司定做!

大概實(shí)現(xiàn)思路:

  • 前端使用webSocket與服務(wù)端創(chuàng)建連接的時(shí)候,將用戶ID傳給服務(wù)端
  • 服務(wù)端將用戶ID與channel關(guān)聯(lián)起來存儲(chǔ),同時(shí)將channel放入到channel組中
  • 如果需要給所有用戶發(fā)送消息,直接執(zhí)行channel組的writeAndFlush()方法
  • 如果需要給指定用戶發(fā)送消息,根據(jù)用戶ID查詢到對(duì)應(yīng)的channel,然后執(zhí)行writeAndFlush()方法
  • 前端獲取到服務(wù)端推送的消息之后,將消息內(nèi)容展示到文本域中

下面是具體的代碼實(shí)現(xiàn),基本上每一步操作都配有注釋說明,配合注釋看應(yīng)該還是比較容易理解的。

第零步:引入Netty的依賴,和一個(gè)工具包(只用到了json工具,可用其他json工具代替)


 io.netty
 netty-all 
 4.1.33.Final



 cn.hutool
 hutool-all
 5.2.3

第一步:在NettyConfig中定義一個(gè)channel組,管理所有的channel,再定義一個(gè)map,管理用戶與channel的對(duì)應(yīng)關(guān)系。

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 {
  /**
   * 定義一個(gè)channel組,管理所有的channel
   * GlobalEventExecutor.INSTANCE 是全局的事件執(zhí)行器,是一個(gè)單例
   */
  private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

  /**
   * 存放用戶與Chanel的對(duì)應(yīng)信息,用于給指定用戶發(fā)送消息
   */
  private static ConcurrentHashMap userChannelMap = new ConcurrentHashMap<>();

  private NettyConfig() {}
  
  /**
   * 獲取channel組
   * @return
   */
  public static ChannelGroup getChannelGroup() {
    return channelGroup;
  }

  /**
   * 獲取用戶channel map
   * @return
   */
  public static ConcurrentHashMap getUserChannelMap(){
    return userChannelMap;
  }
}

第二步:創(chuàng)建NettyServer,定義兩個(gè)EventLoopGroup,bossGroup輔助客戶端的tcp連接請(qǐng)求, workGroup負(fù)責(zé)與客戶端之前的讀寫操作,需要說明的是,需要開啟一個(gè)新的線程來執(zhí)行netty server,要不然會(huì)阻塞主線程,到時(shí)候就無法調(diào)用項(xiàng)目的其他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協(xié)議名
   */
  private static final String WEBSOCKET_PROTOCOL = "WebSocket";

  /**
   * 端口號(hào)
   */
  @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;

  /**
   * 啟動(dòng)
   * @throws InterruptedException
   */
  private void start() throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    // bossGroup輔助客戶端的tcp連接請(qǐng)求, workGroup負(fù)責(zé)與客戶端之前的讀寫操作
    bootstrap.group(bossGroup,workGroup);
    // 設(shè)置NIO類型的channel
    bootstrap.channel(NioServerSocketChannel.class);
    // 設(shè)置監(jiān)聽端口
    bootstrap.localAddress(new InetSocketAddress(port));
    // 連接到達(dá)時(shí)會(huì)創(chuàng)建一個(gè)通道
    bootstrap.childHandler(new ChannelInitializer() {

      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        // 流水線管理通道中的處理程序(Handler),用來處理業(yè)務(wù)
        // webSocket協(xié)議本身是基于http協(xié)議的,所以這邊也要使用http編解碼器
        ch.pipeline().addLast(new HttpServerCodec());
        ch.pipeline().addLast(new ObjectEncoder());
        // 以塊的方式來寫的處理器
        ch.pipeline().addLast(new ChunkedWriteHandler());
        /*
        說明:
        1、http數(shù)據(jù)在傳輸過程中是分段的,HttpObjectAggregator可以將多個(gè)段聚合
        2、這就是為什么,當(dāng)瀏覽器發(fā)送大量數(shù)據(jù)時(shí),就會(huì)發(fā)送多次http請(qǐng)求
         */
        ch.pipeline().addLast(new HttpObjectAggregator(8192));
        /*
        說明:
        1、對(duì)應(yīng)webSocket,它的數(shù)據(jù)是以幀(frame)的形式傳遞
        2、瀏覽器請(qǐng)求時(shí) ws://localhost:58080/xxx 表示請(qǐng)求的uri
        3、核心功能是將http協(xié)議升級(jí)為ws協(xié)議,保持長(zhǎng)連接
        */
        ch.pipeline().addLast(new WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL, true, 65536 * 10));
        // 自定義的handler,處理業(yè)務(wù)邏輯
        ch.pipeline().addLast(webSocketHandler);

      }
    });
    // 配置完成,開始綁定server,通過調(diào)用sync同步方法阻塞直到綁定成功
    ChannelFuture channelFuture = bootstrap.bind().sync();
    log.info("Server started and listen on:{}",channelFuture.channel().localAddress());
    // 對(duì)關(guān)閉通道進(jìn)行監(jiān)聽
    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() {
    //需要開啟一個(gè)新的線程來執(zhí)行netty server 服務(wù)器
    new Thread(() -> {
      try {
        start();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
  }
}

第三步:具體實(shí)現(xiàn)業(yè)務(wù)的WebSocketHandler,具體實(shí)現(xiàn)邏輯看注釋

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類型, 表示一個(gè)文本幀
 * @author sixiaojie
 * @date 2020-03-28-13:47
 */
@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler {
  private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

  /**
   * 一旦連接,第一個(gè)被執(zhí)行
   * @param ctx
   * @throws Exception
   */
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    log.info("handlerAdded 被調(diào)用"+ctx.channel().id().asLongText());
    // 添加到channelGroup 通道組
    NettyConfig.getChannelGroup().add(ctx.channel());
  }

  /**
   * 讀取數(shù)據(jù)
   */
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
    log.info("服務(wù)器收到消息:{}",msg.text());

    // 獲取用戶ID,關(guān)聯(lián)channel
    JSONObject jsonObject = JSONUtil.parseObj(msg.text());
    String uid = jsonObject.getStr("uid");
    NettyConfig.getUserChannelMap().put(uid,ctx.channel());

    // 將用戶ID作為自定義屬性加入到channel中,方便隨時(shí)channel中獲取用戶ID
    AttributeKey key = AttributeKey.valueOf("userId");
    ctx.channel().attr(key).setIfAbsent(uid);

    // 回復(fù)消息
    ctx.channel().writeAndFlush(new TextWebSocketFrame("服務(wù)器連接成功!"));
  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    log.info("handlerRemoved 被調(diào)用"+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的對(duì)應(yīng)關(guān)系
   * @param ctx
   */
  private void removeUserId(ChannelHandlerContext ctx){
    AttributeKey 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);
}

接口實(shí)現(xiàn)類:

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 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頁(yè)面




  
  Title



  

目前為止,所有代碼已經(jīng)寫完了,測(cè)試一下

首先運(yùn)行這個(gè)html文件,會(huì)看到服務(wù)端給前端返回的消息“服務(wù)器連接成功了!”,后端日志會(huì)打印服務(wù)器收到消息:{"uid":"123456"}

SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的方法

然后使用postman測(cè)試推送的接口

SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的方法

測(cè)試成功,打完收工

看完上述內(nèi)容,是不是對(duì)SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。


網(wǎng)站名稱:SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的方法
標(biāo)題鏈接:http://www.dlmjj.cn/article/jcsodo.html