- 主动查看线上服务节点
- 查看服务节点资源使用情况
- 服务离线通知
- 服务资源(CPU、内存、硬盘)超出阀值通知
- root-manger // 根节点
- server00001 :<json> //服务节点 1
- server00002 :<json>//服务节点 2
- server........n :<json>//服务节点 n
服务状态信息:
-
- ip
- cpu
- memory
- disk
- 创建临时节点:
- 定时变更节点状态信息:
1、实时查询 zookeeper 获取集群节点的状态信息。
- 监听根节点下子节点的变化情况,如果CPU 等硬件资源低于警告位则发出警报。
private String server = "192.168.0.149:2181";
ZkClient zkClient;
private static Agent instance;
private static final String rootPath = "/root-manger";
private static final String servicePath = rootPath + "/service";
private String nodePath;
private Thread stateThread;
List<OsBean> list = new ArrayList<>();
public static void premain(String args, Instrumentation instrumentation) {
instance = new Agent();
if (args != null) {
instance.server = args;
}
instance.init();
}
// 初始化连接
public void init() {
zkClient = new ZkClient(server, 5000, 10000);
System.out.println("zk连接成功" + server);
buildRoot();
createServerNode();
stateThread = new Thread(() -> {
while (true) {
updateServerNode();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "zk_stateThread");
stateThread.setDaemon(true);
stateThread.start();
}
// 构建根节点
public void buildRoot() {
if (!zkClient.exists(rootPath)) {
zkClient.createPersistent(rootPath);
}
}
// 生成服务节点
public void createServerNode() {
nodePath = zkClient.createEphemeralSequential(servicePath, getOsInfo());
System.out.println("创建节点:" + nodePath);
}
// 监听服务节点状态改变
public void updateServerNode() {
zkClient.writeData(nodePath, getOsInfo());
}
// 更新服务节点状态
public String getOsInfo() {
OsBean bean = new OsBean();
bean.lastUpdateTime = System.currentTimeMillis();
bean.ip = getLocalIp();
bean.cpu = CPUMonitorCalc.getInstance().getProcessCpu();
MemoryUsage memoryUsag = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
bean.usableMemorySize = memoryUsag.getUsed() / 1024 / 1024;
bean.usableMemorySize = memoryUsag.getMax() / 1024 / 1024;
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(bean);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public void updateNode(String path, Object data) {
if (zkClient.exists(path)) {
zkClient.writeData(path, data);
} else {
zkClient.createEphemeral(path, data);
}
}
public static String getLocalIp() {
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
return addr.getHostAddress();
}
}