//單線程運行+睡眠運行
package com.heart.beat.runner;
import com.heart.beat.heatbeat.HeartSenderHttp;
import com.heart.beat.heatbeat.HeartSenderSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 類描述:心跳組件插件
* Created by 李澤陽 on 2019/8/6
*/
@Component//把對象實例化到spring容器中,等於配置文件
@PropertySource("classpath:heart.properties")
public class HeartPluginRunner implements Runnable {
private Logger logger = LoggerFactory.getLogger(HeartPluginRunner.class);
private static boolean isStart = false;//初始化默認未啓動獲取配置文件
@Value("${heart.beatKey}")//獲取配置文件基礎文件參數
private String heartKey;
@Value("${heart.url}")//心跳返回url
private String heartUrl;
@Autowired
private HeartSenderHttp heartSenderHttp;
//組件啓動
public synchronized void start() {
if (isStart) {
//防止重複啓動
return;
}
try {
//文件地址靜態加載
buildConfig();
logger.info("[心跳服務器組件]啓用成功......");
run();
isStart = true;//修改啓動狀態
} catch (Exception e) {
e.printStackTrace();
logger.info("[心跳服務器組件]啓用失敗!!!");
}
}
//心跳記錄發送 http請求
@Override
public void run() {
try {
while (true) {
heartSenderHttp.getInstance().sendHttpPost();
synchronized (HeartSenderSocket.class) {
//單線程等待,激活時間,
this.wait(15 * 1000);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.info("【心跳服務發送失敗!!!】");
logger.info(e.getMessage());
logger.info(e.getStackTrace().toString());
}
}
//加載靜態參數對象
private void buildConfig() {
try {
HeartPluginConfig hpc = HeartPluginConfig.getInstance();
//參數必填校驗
if ("".equals(heartKey) || "".equals(heartUrl))
return;
//靜態資源加載
hpc.setUrl("http://" + heartUrl + "/monitor/heartBeatController/beat?key=" + heartKey);//封裝前、後綴
hpc.setKey(heartKey);
} catch (Exception e) {
logger.info("【文件地址路徑加載失敗!!!】");
}
}
}
//靜態類加載
package com.heart.beat.runner;
/**
* 類描述:靜態加載類
* Created by 李澤陽 on 2019/8/7
*/
public class HeartPluginConfig {
public static HeartPluginConfig instance;
public static HeartPluginConfig getInstance() {
if (instance == null) {
instance = new HeartPluginConfig();
}
return instance;
}
//private String url="/monitor/heartBeatController/beat";//訪問路徑前綴
private String url;//請求地址
private String key;//發送key值
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
//this.url = ("http://" + url + "/monitor/heartBeatController/beat");
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
//監聽啓動類
package com.heart.beat.listener;
import com.heart.beat.runner.HeartPluginRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 類描述:伴隨組件啓動類
* Created by 李澤陽 on 2019/8/6
*/
@Component
@Order(Ordered.LOWEST_PRECEDENCE)//過濾器,最低過濾權限,最後執行過濾操作
//@Order(Ordered.HIGHEST_PRECEDENCE)//最高過濾權限
public class HeartUploadListener implements ApplicationListener<ContextRefreshedEvent>, ApplicationRunner {
//ApplicationListener spring 監聽
@Autowired
private HeartPluginRunner heartPluginRunner;
@Override
public void run(ApplicationArguments args) throws Exception {
startHearts();
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() != null) {
startHearts();
}
}
private void startHearts() {
//啓動心跳組件
heartPluginRunner.start();
}
}
//http請求
package com.heart.beat.heatbeat;
import com.heart.beat.runner.HeartPluginConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
/**
* 類描述:心跳客戶端發送類
* Created by 李澤陽 on 2019/8/7
*/
@Repository
public class HeartSenderHttp {
private Logger logger = LoggerFactory.getLogger(HeartSenderHttp.class);
private static HeartSenderHttp instance;
//初始化類對象>>>單例模式
public static HeartSenderHttp getInstance() {
if (instance == null) {
synchronized (HeartSenderHttp.class) {
instance = new HeartSenderHttp();
}
}
return instance;
}
//心跳發送 http請求
public String sendHttpPost() {
HttpURLConnection connection = null;
InputStream inputStream = null;//輸入流
OutputStream outputStream = null;//輸出流
BufferedReader bufferedReader = null;
String result = null;
try {
URL url = new URL(HeartPluginConfig.getInstance().getUrl());
//通過遠程連接對象
connection = (HttpURLConnection) url.openConnection();
//設置連接方式
connection.setRequestMethod("POST");
//設置連接主機服務超時時間 15000毫秒
connection.setConnectTimeout(15000);
//設置讀取主機服務返回數據超時時間:60000毫秒
connection.setReadTimeout(60000);
//是否向遠程服務寫入數據/默認false
connection.setDoOutput(true);
//設置傳入參數格式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 設置鑑權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//connection.setRequestProperty("Authorization", "");
connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 通過連接對象獲取一個輸出流
outputStream = connection.getOutputStream();
// 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
outputStream.write(HeartPluginConfig.getInstance().getKey().getBytes());
//通過連接對象獲取一個輸入流,向遠程讀取
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
// 對輸入流對象進行包裝:charset根據工作項目組的要求來設置
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
// 循環遍歷一行一行讀取數據
while ((temp = bufferedReader.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
logger.info(HeartPluginConfig.getInstance().getKey() + ":[心跳發送成功!]" + new Date());
} catch (Exception e) {
e.printStackTrace();
logger.info(HeartPluginConfig.getInstance().getKey() + ":[心跳消息發送失敗!]" + new Date());
} finally {
//關閉資源
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//斷開與遠程地址url的連接
connection.disconnect();
}
return result;
}
}
git項目地址:https://github.com/lizyangcoco/monitor_heart.git
面向開發過程,記錄學習之路。