一。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();
}
}