‘liusuyi’
2023-06-25 0b25d230881ce4d56233a4834eb520d120f9a7a9
增加nettyTcp客户端
已添加2个文件
已修改3个文件
123 ■■■■■ 文件已修改
src/main/java/com/ard/alarm/camera/service/impl/ArdCamerasServiceImpl.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ard/alarm/tube/service/TubeAlarmService.java 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ard/utils/tcp/NettyTcpClient.java 47 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ard/utils/tcp/NettyTcpClientHandler.java 43 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/resources/logback-spring.xml 26 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/ard/alarm/camera/service/impl/ArdCamerasServiceImpl.java
@@ -18,7 +18,7 @@
 * @date 2023-02-11
 */
@Service
@Slf4j
@Slf4j(topic = "camera")
public class ArdCamerasServiceImpl implements IArdCamerasService {
    @Resource
    private ArdCamerasMapper ardCamerasMapper;
src/main/java/com/ard/alarm/tube/service/TubeAlarmService.java
@@ -3,6 +3,7 @@
import com.alibaba.fastjson2.JSON;
import com.ard.utils.DateUtils;
import com.ard.utils.mqtt.MqttConsumer;
import com.ard.utils.tcp.NettyTcpClient;
import com.ard.utils.udp.NettyUdpServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
@@ -28,6 +29,8 @@
public class TubeAlarmService {
    @Resource
    NettyUdpServer nettyUdpServer;
    @Resource
    NettyTcpClient nettyTcpClient;
    @Value("${spring.netty.port}")
    private Integer udpPort;
    @Value("${spring.netty.enabled}")
@@ -40,6 +43,8 @@
        }
        nettyUdpServer.init(udpPort);
        log.info("UDP服务已经启动");
        nettyTcpClient.init("112.98.126.2",1200);
        log.info("TCP客户端已连接");
    }
    @Async("alarm")
src/main/java/com/ard/utils/tcp/NettyTcpClient.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,47 @@
package com.ard.utils.tcp;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
/**
 * @Description:
 * @ClassName: NettyTcpClient
 * @Author: åˆ˜è‹ä¹‰
 * @Date: 2023å¹´06月25日17:00
 * @Version: 1.0
 **/
@EnableAsync
@Component
@Slf4j(topic = "radar")
public class NettyTcpClient {
    @Async
    public void init(String host, Integer port) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyTcpClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port).sync();
            future.channel().closeFuture().sync();
        } catch (Exception ex) {
            log.error("nettyTcp客户端初始化异常:" + ex.getMessage());
        } finally {
            group.shutdownGracefully();
        }
    }
}
src/main/java/com/ard/utils/tcp/NettyTcpClientHandler.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,43 @@
package com.ard.utils.tcp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import javax.xml.bind.DatatypeConverter;
/**
 * @Description: tcp客户端处理
 * @ClassName: NettyTcpClientHandler
 * @Author: åˆ˜è‹ä¹‰
 * @Date: 2023å¹´06月25日17:02
 * @Version: 1.0
 **/
@Slf4j
public class NettyTcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg){
        // å¤„理接收到的消息
        byte[] byteArray = new byte[msg.readableBytes()];
        msg.getBytes(msg.readerIndex(), byteArray);
        String hexString = DatatypeConverter.printHexBinary(byteArray);
        log.info("Received: " + hexString);
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // å½“客户端连接成功后,发送消息给服务器
        ByteBuf message = ctx.alloc().buffer();
        message.writeBytes("Hello, Server!".getBytes());
        ctx.writeAndFlush(message);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        // å‘生异常时的处理
        cause.printStackTrace();
        ctx.close();
    }
}
src/main/resources/logback-spring.xml
@@ -54,6 +54,28 @@
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <!--通用光电报警日志输出-->
    <appender name="camera" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/camera.log</file>
        <!--循环政策:基于时间创建日志文件-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件名格式-->
            <fileNamePattern>${log.path}/camera.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!--日志最大的历史60天-->
            <maxHistory>60</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--过滤的级别-->
            <level>INFO</level>
            <!--匹配时的操作:接收(记录)-->
            <onMatch>ACCEPT</onMatch>
            <!--不匹配时的操作:拒绝(不记录)-->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <root level="DEBUG">
        <appender-ref ref="console"/>
    </root>
@@ -65,5 +87,9 @@
    <root level="INFO">
        <appender-ref ref="tube"/>
    </root>
    <!--通用光电报警操作日志-->
    <root level="INFO">
        <appender-ref ref="camera"/>
    </root>
</configuration>