Springboot Bean 的@PostConstruct,@PreDestroy

1、@PostConstruct

spring 在執行完bean 的構造方法之後,init 方法之前,會執行該方法

 構造方法 > @Autowired > @PostConstruct

 

2、@PreDestroy

spring 在執行完bean 的destroy() 方法後,並在servlet 容器完全銷燬之前執行該方法

 

 

使用示例

package com.ahies.stm.app.gatenetty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

@Component
@Slf4j
public class GateNettyServer {
    /**
     * boss 線程組用於處理連接工作
     */
    private EventLoopGroup boss = new NioEventLoopGroup();
    /**
     * work 線程組用於數據處理
     */
    private EventLoopGroup work = new NioEventLoopGroup();
    @Value("${gate.netty.port}")
    private Integer port;


    /**
     * 啓動Netty Server
     *
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {
        //bean 初始化執行
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, work)
                // 指定Channel
                .channel(NioServerSocketChannel.class)
                //使用指定的端口設置套接字地址
                .localAddress(new InetSocketAddress(port))

                //服務端可連接隊列數,對應TCP/IP協議listen函數中backlog參數
                .option(ChannelOption.SO_BACKLOG, 2048)

                //設置TCP長連接,一般如果兩個小時內沒有數據的通信時,TCP會自動發送一個活動探測數據報文
                .childOption(ChannelOption.SO_KEEPALIVE, true)

                //將小的數據包包裝成更大的幀進行傳送,提高網絡的負載
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_REUSEADDR, true)

                .childHandler(new GateNettyServerHandlerInitializer());
        ChannelFuture future = bootstrap.bind().sync();
        if (future.isSuccess()) {
            log.info("啓動 GATE Netty Server");
        }
    }

    @PreDestroy
    public void destory() throws InterruptedException {
        log.info("關閉GATE Netty");
        GateTcpServerHandler.channels.close();
        boss.shutdownGracefully().sync();
        work.shutdownGracefully().sync();

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章