//单线程运行+睡眠运行
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
面向开发过程,记录学习之路。