• 业务提前初始化执行


    一 实现  CommandLineRunner接口

    1. package com.example.gatewayacquisitionsystem;
    2. import com.alibaba.fastjson.JSONArray;
    3. import com.alibaba.fastjson.JSONObject;
    4. import com.example.gatewayacquisitionsystem.config.ConfigProperties;
    5. import lombok.Data;
    6. import org.springframework.boot.CommandLineRunner;
    7. import org.springframework.stereotype.Component;
    8. import org.springframework.web.client.RestTemplate;
    9. import javax.annotation.Resource;
    10. import java.util.concurrent.Executors;
    11. import java.util.concurrent.ScheduledExecutorService;
    12. import java.util.concurrent.TimeUnit;
    13. @Component
    14. public class DeviceStatusRunner implements CommandLineRunner {
    15. @Resource
    16. RestTemplate restTemplate;
    17. @Resource
    18. ConfigProperties configProperties;
    19. public static int deviceNum = 0;
    20. public static int activeDeviceNum = 0;
    21. @Override
    22. public void run(String... args) throws Exception {
    23. ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    24. service.scheduleWithFixedDelay(new Runnable() {
    25. @Override
    26. public void run() {
    27. JSONObject jsonObject = restTemplate.getForObject(configProperties.getZDataHandleHost() + "gateway/onlineId", JSONObject.class);
    28. assert jsonObject != null;
    29. if (jsonObject.getInteger("code") != 200) {
    30. return;
    31. }
    32. JSONArray gatewayIds = jsonObject.getJSONArray("data");
    33. int deviceNum = 0;
    34. int activeNum = 0;
    35. for (Object id : gatewayIds) {
    36. JSONObject rep = restTemplate.getForObject(configProperties.getZDataHandleHost() + "gateway/status/" + id, JSONObject.class);
    37. if (rep.getInteger("code") == 200) {
    38. deviceNum += rep.getJSONObject("data").getInteger("deviceNum");
    39. activeNum += rep.getJSONObject("data").getInteger("activeDeviceNum");
    40. }
    41. }
    42. DeviceStatusRunner.deviceNum = deviceNum;
    43. DeviceStatusRunner.activeDeviceNum = activeNum;
    44. }
    45. }, 10, 10, TimeUnit.SECONDS);
    46. }
    47. }

    二 不影响主线程,使用断言关键字进行判断  assert

       代码在上面,查看

    
                    
  • 相关阅读:
    PHP使用 yansongda/pay 实现支付宝-网页支付功能,转账提现功能
    【计算机网络】HTTP 重定向的应用场景
    无人驾驶压路的应用之研华工控机ARK-1123助力
    设计模式之工厂模式
    kibana安装
    学习MySQL 临时表
    Java学习笔记16——4种访问修饰符区别
    JVM
    一名双非程序媛面试蚂蚁、美团、携程等大厂拿offer分享面试过程
    SpringMVC基础篇(二)
  • 原文地址:https://blog.csdn.net/weixin_49591538/article/details/126617795