Browse Source

fix: 修改系统时间后定时任务不执行的问题

zengweijie 3 years ago
parent
commit
38ebaf2db3
1 changed files with 47 additions and 10 deletions
  1. 47 10
      src/main/java/com/inspur/smsb/gateway/filter/LicenseFilter.java

+ 47 - 10
src/main/java/com/inspur/smsb/gateway/filter/LicenseFilter.java

@@ -5,6 +5,8 @@ import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.inspur.smsb.gateway.dto.license.LicenseDto;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.beans.factory.InitializingBean;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.cloud.gateway.filter.GatewayFilterChain;
 import org.springframework.cloud.gateway.filter.GlobalFilter;
@@ -13,17 +15,17 @@ import org.springframework.core.io.buffer.DataBufferFactory;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.MediaType;
 import org.springframework.http.server.reactive.ServerHttpResponse;
-import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.stereotype.Component;
 import org.springframework.web.server.ServerWebExchange;
 import reactor.core.publisher.Mono;
 
 import javax.annotation.Resource;
 import java.io.*;
+import java.time.Duration;
 import java.time.LocalDateTime;
 import java.util.Objects;
 import java.util.Optional;
-import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
@@ -33,7 +35,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
  **/
 @Slf4j
 @Component
-public class LicenseFilter implements GlobalFilter, Ordered {
+public class LicenseFilter implements GlobalFilter, Ordered, InitializingBean, DisposableBean {
     @Resource
     private ObjectMapper objectMapper;
     private final AtomicBoolean sysLocked = new AtomicBoolean(false);
@@ -42,6 +44,7 @@ public class LicenseFilter implements GlobalFilter, Ordered {
     private static final int STEP = 5;
     @Value("${license-dir}")
     private String licenseDir;
+    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
 
     @Override
     public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
@@ -63,46 +66,80 @@ public class LicenseFilter implements GlobalFilter, Ordered {
         return chain.filter(exchange);
     }
 
-    @Scheduled(fixedRate = 5, timeUnit = TimeUnit.MINUTES)
-    public void checkSysLocked() throws IOException {
+    public boolean checkSysLocked() {
         if (sysLocked.get() || timeRollBack.get()) {
-            return;
+            return false;
         }
         File directory = new File(licenseDir);
         if (!directory.exists() && !directory.mkdirs()) {
-            return;
+            return false;
         }
         File licenseFile = new File(directory.getAbsolutePath() + File.separator + "license.json");
         if (!licenseFile.exists()) {
-            return;
+            return false;
         }
         LicenseDto licenseDto = new LicenseDto();
         try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(licenseFile))) {
             if (inputStream.available() > 0) {
                 licenseDto = objectMapper.readValue(inputStream.readAllBytes(), LicenseDto.class);
             }
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+            return true;
         }
         LocalDateTime now = LocalDateTime.now();
         if (Objects.nonNull(licenseDto.getLastUpdate()) && licenseDto.getLastUpdate().isAfter(now)) {
             timeRollBack.set(true);
-            return;
+            return false;
         }
         int duration = Optional.ofNullable(licenseDto.getDuration()).orElse(DEFAULT_DURATION);
         int account = Optional.ofNullable(licenseDto.getAccount()).orElse(0);
         if (duration <= account) {
             sysLocked.set(true);
-            return;
+            return false;
         }
         licenseDto.setDuration(duration);
         licenseDto.setAccount(account + STEP);
         licenseDto.setLastUpdate(now);
         try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(licenseFile))) {
             outputStream.write(objectMapper.writeValueAsBytes(licenseDto));
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+            return true;
         }
+        return true;
     }
 
     @Override
     public int getOrder() {
         return HIGHEST_PRECEDENCE;
     }
+
+    @Override
+    public void destroy() {
+        threadPoolTaskExecutor.shutdown();
+    }
+
+    @Override
+    public void afterPropertiesSet() {
+        threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
+        threadPoolTaskExecutor.setCorePoolSize(1);
+        threadPoolTaskExecutor.setMaxPoolSize(1);
+        threadPoolTaskExecutor.setQueueCapacity(0);
+        threadPoolTaskExecutor.setKeepAliveSeconds(60);
+        threadPoolTaskExecutor.setThreadNamePrefix("license-Async-Executor-");
+        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(false);
+        threadPoolTaskExecutor.setAwaitTerminationSeconds(0);
+        threadPoolTaskExecutor.initialize();
+        threadPoolTaskExecutor.execute(() -> {
+            while (checkSysLocked()) {
+                try {
+                    Thread.sleep(Duration.ofMinutes(STEP).toMillis());
+                } catch (InterruptedException e) {
+                    log.error(e.getMessage(), e);
+                }
+            }
+            threadPoolTaskExecutor.shutdown();
+        });
+    }
 }