springboot在啓動項目時初始化自定義方法,以netty爲例,三種方式對比

上一篇博客中我實現了客戶端的斷線重連,斷開連接後無限重試,並在連接之後無限發送消息給客戶端,有興趣的朋友可以查看我的這篇博客netty客戶端連接後無限發送數據,連接不上時無限重試,斷線重連

需求是這樣的,在springboot項目啓動後,需要自動啓動啓動Netty的客戶端,並且無限給服務端發送消息,並將返回的消息利用mybatis存儲進數據庫。(存庫這一步我就不說了,主要實現在項目啓動時啓動netty)

有四種方法

一、實現CommandLineRunner接口,重寫run方法

package com.ning.myrun;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.ning.nett.NettyClient;

@Component
public class MyStart1 implements CommandLineRunner{

	@Override
	public void run(String... args) throws Exception {
		NettyClient.connect(10007, "127.0.0.1");
	}

}

二、實現ApplicationRunner接口,重寫un方法

package com.ning.myrun;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.ning.nett.NettyClient;

@Component
public class MyStart2 implements ApplicationRunner {
	@Override
	public void run(ApplicationArguments args) throws Exception {
		NettyClient.connect(10007, "127.0.0.1");
	}

}

三、初始化方法加上@PostConstruct註解

package com.ning.myrun;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.ning.nett.NettyClient;

@Component
public class MyStart3{
	@PostConstruct
	public void test() throws Exception {
		NettyClient.connect(10007, "127.0.0.1");
	}

}

四、其他實現思路

我們只需要讓方法得以執行就可以,比如這樣做: 

package com.ning.myrun;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ning.nett.NettyClient;

@Configuration
public class MyStart4 {
	@Bean
	public String startNetty() {
		try {
			NettyClient.connect(10007, "127.0.0.1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "startNetty";
	}
}

在或者,直接扔進靜態代碼塊:(不斷探索嘛)

 

package com.ning.myrun;

import org.springframework.stereotype.Component;

import com.ning.nett.NettyClient;
@Component
public class MyStart5 {
	static {
		try {
			NettyClient.connect(10007, "127.0.0.1");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

這樣可能不規範,但也可以實現

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