让一个类跟着springboot项目的启动而启动——InitializingBean接口和@PostConstruct注解,CommandLineRunner接口

一。InitializingBean接口

1.类上加注解@Component
2.实现InitializingBean接口,重新afterPropertiesSet方法
如下案例SpringBoot项目启动netty客户端

@Component
public class BusiClient implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        NettyClient nettyClient = new NettyClient();
        new Thread(nettyClient).start();
        while(!nettyClient.isConnected()){
            synchronized (nettyClient){
                nettyClient.wait();
            }
        }
        System.out.println("网络通信已准备好,可以进行业务操作了........");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String msg = scanner.next();
            if (msg == null) {
                continue;
            } else if ("q".equals(msg.toLowerCase())) {
                nettyClient.close();
                while(nettyClient.isConnected()){
                    synchronized (nettyClient){
                        nettyClient.wait();
                    }
                }
                scanner.close();
                System.exit(1);
            } else {
                nettyClient.send(msg);
            }
        }
    }
}

二。@PostConstruct注解 netty客户端或者服务端

1.类上加注解@Component
2.方法上加注解@PostConstruct

@Component
public class TIMServer {
    /**
     * 启动 tim server
     *
     * @return
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(boss, work)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(nettyPort))
                //保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new TIMServerInitializer());

        ChannelFuture future = bootstrap.bind().sync();
        if (future.isSuccess()) {
            LOGGER.info("Start tim server success!!!");
        }
    }

    /**
     * 销毁
     */
    @PreDestroy
    public void destroy() {
        boss.shutdownGracefully().syncUninterruptibly();
        work.shutdownGracefully().syncUninterruptibly();
        LOGGER.info("Close tim server success!!!");
    }

}

三。CommandLineRunner接口或者ApplicationRunner接口

1.SpringBoot主启动类实现CommandLineRunner接口,调用注册类的注册方法


@SpringBootApplication
public class TIMServerApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(TIMServerApplication.class, args);
        
    }

    @Override
    public void run(String... args) throws Exception {
        //获得本机IP
        String addr = InetAddress.getLocalHost().getHostAddress();
        Thread thread = new Thread(new RegistryZK(addr, appConfiguration.getTimServerPort(), httpPort));
        thread.setName("registry-zk");
        thread.start();
        new Thread(() -> nettyServer.startr()).start();
    }
}

2.注册类实现Runnable接口

public class RegistryZK implements Runnable {

    private ZKit zKit;

    private AppConfiguration appConfiguration ;

    private String ip;
    private int timServerPort;
    private int httpPort;

    public RegistryZK(String ip, int timServerPort,int httpPort) {
        this.ip = ip;
        this.timServerPort = timServerPort;
        this.httpPort = httpPort ;
        zKit = SpringBeanFactory.getBean(ZKit.class) ;
        appConfiguration = SpringBeanFactory.getBean(AppConfiguration.class) ;
    }

    @Override
    public void run() {
    
        //创建父节点
        zKit.createRootNode();

        //是否要将自己注册到 ZK
        if (appConfiguration.isZkSwitch()){
            String path = appConfiguration.getZkRoot() + "/ip-" + ip + ":" + timServerPort + ":" + httpPort;
            zKit.createNode(path);
        }
        new Thread(() -> nettyServer.startr()).start();


    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飘然生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值