ke
2024-11-26 0f0cd8abae38a873a9a97bd8bda019a197df2637
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cn.gistack.by.nettyUpload;
 
 
import cn.gistack.by.nettyUpload.config.NettyHttpConfig;
import cn.gistack.by.nettyUpload.utils.ExceptionUtils;
import cn.gistack.by.picUpload.service.BaiyiPicService;
import cn.gistack.resource.feign.IOssClient;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
 
/**
 * netty实现http协议上传文件 服务端
 *
 * @author Kai.Shan
 * @date 2024-11-13 14:33
 */
@Slf4j
public class HttpUploadFileServer implements Runnable {
    private NettyHttpConfig nettyHttpConfig;
 
    private IOssClient iOssClient;
 
    private BaiyiPicService baiyiPicService;
 
    public HttpUploadFileServer(NettyHttpConfig nettyHttpConfig, IOssClient iOssClient ,BaiyiPicService baiyiPicService) {
        this.nettyHttpConfig = nettyHttpConfig;
        this.iOssClient = iOssClient;
        this.baiyiPicService = baiyiPicService;
    }
 
    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.nettyHttpConfig.getBossGroupThreads());
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(this.nettyHttpConfig.getWorkerGroupThreads());
 
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, nettyHttpConfig.getNettySoBacklog())
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new HttpUploadFileInitialzer(nettyHttpConfig,iOssClient,baiyiPicService));
 
            Channel channel = bootstrap.bind(this.nettyHttpConfig.getServerSocketIp(),this.nettyHttpConfig.getServerSocketPort())
                    .sync().channel();
            System.out.println("upload server started ....");
 
            channel.closeFuture().sync();
        } catch (Exception exception) {
            exception.printStackTrace();
            log.error(ExceptionUtils.getStackString(exception));
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}