利用netty实现企业级websocket功能

利用netty实现企业级websocket功能

1.业务服务中集成netty并实现websocket功能

1.1引入netty依赖

<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.79.Final</version>
</dependency>

2.netty实现websocket功能

public void start() {
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            // 核心的业务处理逻辑
                            pipeline.addLast(new TextWebSocketFrameHandler());
                            // 升级ws
                            // 注意该处理器与自定义业务处理器的顺序,如果需要获取http请求时的参数信息,该处理器应该位于http请求参数处理器之前
                            pipeline.addLast(new WebSocketServerProtocolHandler("/netty/toAll/websocket",true,10000L));

                        }
                    });
            Channel channel = serverBootstrap.bind().syncUninterruptibly().channel();
            channel.closeFuture().syncUninterruptibly();
        } catch (Exception e) {
            log.error("netty启动异常", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
  }
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.ImmediateEventExecutor;

import java.util.concurrent.ConcurrentHashMap;

/*
* 存储channel和用户id与channel的映射关系,方便后续给指定用户发送消息
*/
public class ChannelPool {

    public static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    public static final ConcurrentHashMap<String, Channel> USER_CHANNEL_MAP = new ConcurrentHashMap<>();
}

自定义业务处理器

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 该类主要用于处理业务逻辑,该示例中用来统计在线人数
 */
@Slf4j
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private String userId;
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ChannelPool.CHANNEL_GROUP.add(ctx.channel());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ChannelPool.CHANNEL_GROUP.remove(ctx.channel());
        if (userId != null) {
            ChannelPool.USER_CHANNEL_MAP.remove(userId);
        }
        super.channelInactive(ctx);
    }
	/**
	* 客户端首次通过http请求创建连接时,消息类型为FullHttpRequest,截取url中的用户id信息
	*/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            if (request.decoderResult().isSuccess() && Objects.equals("websocket", request.headers().get("Upgrade"))) {
                String uri = request.uri();
                if (uri.contains("/toAll/websocket")) {
                    String split = uri.split("\\?")[0];
                    String[] split1 = split.split("/");
                    int length = split1.length;
                    userId = split1[length - 1];
                }
            }

        }
        super.channelRead(ctx,msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        ChannelPool.CHANNEL_GROUP.writeAndFlush(new TextWebSocketFrame("连接netty----------->"));
		// TODO 发送消息业务逻辑
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("netty连接异常", cause);
        ChannelPool.CHANNEL_GROUP.remove(ctx.channel());
        ChannelPool.USER_CHANNEL_MAP.remove(userId);
        ctx.close();
    }
}

netty服务手动注册到注册中心

由于netty是集成到业务服务中的,且netty启动需要单独占用一个端口,无法与业务服务的端口公用,如需将netty实现的ws功能连接到网关,则需手动注册

public void init() throws UnknownHostException {
		// nacos注册中心
        NacosDiscoveryProperties nacosDiscoveryProperties = new NacosDiscoveryProperties();
        // 服务名
        nacosDiscoveryProperties.setService(serverName);
        // 端口
        nacosDiscoveryProperties.setPort(port);
        // ip地址,容器化环境中获取ip地址可以使用spring-cloud-commons包中的inetUtils.findFirstNonLoopbackHostInfo().getIpAddress()
        nacosDiscoveryProperties.setIp(InetAddress.getLocalHost().getHostAddress());
        // 注册中心地址
        nacosDiscoveryProperties.setServerAddr(serverAddress);
        Registration registration = new NacosRegistration(null, nacosDiscoveryProperties, applicationContext);
        nacosServiceRegistry.register(registration);
        new Thread(this::start).start();
    }

websocket连接网关

spring:
 #配置网关
    gateway:
      discovery:
        locator:
          enabled: false
      httpclient:
        connect-timeout: 1000
        response-timeout: 2s
      #配置路由规则
      routes:
      	- id: NACOS-NETTY
          uri: lb:ws://netty-server
          predicates:
            - Path=/netty/toAll/**
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值