- package com.example.gatewayacquisitionsystem;
-
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.example.gatewayacquisitionsystem.config.ConfigProperties;
- import lombok.Data;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.stereotype.Component;
- import org.springframework.web.client.RestTemplate;
-
- import javax.annotation.Resource;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
-
- @Component
- public class DeviceStatusRunner implements CommandLineRunner {
-
- @Resource
- RestTemplate restTemplate;
- @Resource
- ConfigProperties configProperties;
-
- public static int deviceNum = 0;
- public static int activeDeviceNum = 0;
-
- @Override
- public void run(String... args) throws Exception {
-
- ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
-
- service.scheduleWithFixedDelay(new Runnable() {
- @Override
- public void run() {
- JSONObject jsonObject = restTemplate.getForObject(configProperties.getZDataHandleHost() + "gateway/onlineId", JSONObject.class);
- assert jsonObject != null;
- if (jsonObject.getInteger("code") != 200) {
- return;
- }
- JSONArray gatewayIds = jsonObject.getJSONArray("data");
- int deviceNum = 0;
- int activeNum = 0;
- for (Object id : gatewayIds) {
- JSONObject rep = restTemplate.getForObject(configProperties.getZDataHandleHost() + "gateway/status/" + id, JSONObject.class);
- if (rep.getInteger("code") == 200) {
- deviceNum += rep.getJSONObject("data").getInteger("deviceNum");
- activeNum += rep.getJSONObject("data").getInteger("activeDeviceNum");
- }
- }
- DeviceStatusRunner.deviceNum = deviceNum;
- DeviceStatusRunner.activeDeviceNum = activeNum;
- }
- }, 10, 10, TimeUnit.SECONDS);
- }
- }
代码在上面,查看