Quellcode durchsuchen

新增包装机服务文件监听

赵冬冬 vor 3 Jahren
Ursprung
Commit
7e3ae2600f

+ 0 - 3
src/main/java/com/hw/admin/model/controller/WorkPackerController.java

@@ -18,9 +18,6 @@ public class WorkPackerController {
     @Autowired
     private WorkPackerService workPackerService;
 
-    @Autowired
-    private WorkPackerMapper workPackerMapper;
-
     @PostMapping
     @ResponseBody
     public AjaxResultVo add(@RequestBody WorkPacker workPacker) {

+ 5 - 0
src/main/java/com/hw/admin/model/domain/WorkPacker.java

@@ -82,6 +82,11 @@ public class WorkPacker {
      */
     private String insertTime;
 
+    /**
+     * 文件全路径
+     */
+    private String filePath;
+
     /**
      * 备注
      * 列名:remark 类型:VARCHAR(500) 允许空:true 缺省值:null

+ 2 - 0
src/main/java/com/hw/admin/model/service/WorkPackerService.java

@@ -22,4 +22,6 @@ public interface WorkPackerService {
 
     public void task(String time);
 
+    public void task(String time, String fileName);
+
 }

+ 35 - 13
src/main/java/com/hw/admin/model/service/impl/WorkPackerServiceImpl.java

@@ -7,36 +7,50 @@ import com.hw.admin.model.domain.WorkPackerExcel;
 import com.hw.admin.model.mapper.WorkPackerMapper;
 import com.hw.admin.model.service.WorkPackerService;
 import com.hw.admin.system.listener.WorkPackerListener;
+import com.hw.admin.system.utils.DateExUtils;
 import com.hw.admin.system.utils.Sequence;
-import javafx.scene.input.InputMethodTextRun;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
 
+import java.io.File;
 import java.util.ArrayList;
 import java.util.List;
 
 @Service
 public class WorkPackerServiceImpl implements WorkPackerService {
 
+    @Value("${file.path}")
+    private String filepath;
+
     @Autowired
     private WorkPackerMapper workPackerMapper;
 
     @Override
     public int add(WorkPacker workPacker) {
 
-        List<WorkPacker> list = new ArrayList();
-        Sequence sequence = new Sequence(2, 3);
-        WorkPacker workPacker1=new WorkPacker();
-        WorkPacker workPacker2=new WorkPacker();
-        BeanUtils.copyProperties(workPacker,workPacker1);
-        BeanUtils.copyProperties(workPacker,workPacker2);
-        workPacker1.setId(sequence.nextId());
-        list.add(workPacker1);
-        workPacker2.setId(sequence.nextId());
-        list.add(workPacker2);
-        return workPackerMapper.inserList(list);
+        List<WorkPackerExcel> list = new ArrayList();
+        WorkPackerExcel workPacker1 = new WorkPackerExcel();
+        BeanUtils.copyProperties(workPacker, workPacker1);
+        for (int i = 0; i < 10000; i++) {
+            list.add(workPacker1);
+        }
+        // 写法2
+        String filePaht = filepath + DateExUtils.commonDatePath();
+        //不存在创建文件夹
+        File file = new File(filePaht);
+        if (!file.exists()) {
+            file.mkdirs();
+        }
+        String fileName = filePaht + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
+        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
+        // 如果这里想使用03 则 传入excelType参数即可
+        EasyExcel.write(fileName, WorkPackerExcel.class).sheet("模板").doWrite(list);
+
+        return 0;
+        //return workPackerMapper.inserList(list);
     }
 
     @Override
@@ -45,7 +59,15 @@ public class WorkPackerServiceImpl implements WorkPackerService {
         // 写法3:
         String fileName = "D:\\project\\delivery_project\\远程制药\\后台\\ycpharmacy_excel_service\\excel\\包装机数据测试表.xlsx";
         // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
-        EasyExcel.read(fileName, WorkPackerExcel.class, new WorkPackerListener(workPackerMapper)).sheet().doRead();
+        EasyExcel.read(fileName, WorkPackerExcel.class, new WorkPackerListener(workPackerMapper, fileName)).sheet().doRead();
+    }
+
+    @Override
+    public void task(String time, String fileName) {
+        // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
+        // 写法3:
+        // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
+        EasyExcel.read(fileName, WorkPackerExcel.class, new WorkPackerListener(workPackerMapper, fileName)).sheet().doRead();
     }
 
     @Override

+ 9 - 0
src/main/java/com/hw/admin/system/listener/FileListener.java

@@ -1,8 +1,11 @@
 package com.hw.admin.system.listener;
 
+import com.hw.admin.model.service.WorkPackerService;
+import com.hw.admin.system.utils.DateExUtils;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.io.monitor.FileAlterationListener;
 import org.apache.commons.io.monitor.FileAlterationObserver;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import java.io.File;
@@ -10,6 +13,10 @@ import java.io.File;
 @Slf4j
 @Component
 public class FileListener implements FileAlterationListener {
+
+    @Autowired
+    private WorkPackerService workPackerService;
+
     @Override
     public void onStart(FileAlterationObserver fileAlterationObserver) {
         File directory = fileAlterationObserver.getDirectory();
@@ -36,10 +43,12 @@ public class FileListener implements FileAlterationListener {
 
     @Override
     public void onFileCreate(File file) {
+        String time = DateExUtils.commonDatePathStr();
         String name = file.getName();
         String path = file.getPath();
         log.info("文件被创建了..." + name);
         log.info("文件是..." + path);
+        workPackerService.task(time, path);
     }
 
     @Override

+ 7 - 2
src/main/java/com/hw/admin/system/listener/WorkPackerListener.java

@@ -17,6 +17,9 @@ import java.util.List;
 
 // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 public class WorkPackerListener extends AnalysisEventListener<WorkPackerExcel> {
+
+    private String filePath;
+
     private static final Logger LOGGER = LoggerFactory.getLogger(WorkPackerListener.class);
     /**
      * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
@@ -34,8 +37,9 @@ public class WorkPackerListener extends AnalysisEventListener<WorkPackerExcel> {
     /**
      * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
      */
-    public WorkPackerListener(WorkPackerMapper workPackerMapper) {
+    public WorkPackerListener(WorkPackerMapper workPackerMapper, String filePath) {
         this.workPackerMapper = workPackerMapper;
+        this.filePath = filePath;
     }
 
     /**
@@ -48,12 +52,13 @@ public class WorkPackerListener extends AnalysisEventListener<WorkPackerExcel> {
 
     @Override
     public void invoke(WorkPackerExcel data, AnalysisContext context) {
-        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
+        //LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
         WorkPacker workPacker = new WorkPacker();
         BeanUtils.copyProperties(data, workPacker);
         workPacker.setId(sequence.nextId());
         String s = DateExUtils.commonDatePathStr();
         workPacker.setInsertTime(s);
+        workPacker.setFilePath(filePath);
         list.add(workPacker);
         // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
         if (list.size() >= BATCH_COUNT) {

+ 1 - 1
src/main/java/com/hw/admin/system/task/WorkPackerTask.java

@@ -16,7 +16,7 @@ public class WorkPackerTask {
     @Autowired
     private WorkPackerService workPackerService;
 
-    @Scheduled(cron = "0/60 * * * * ?")
+    //@Scheduled(cron = "0/60 * * * * ?")
     public void executeScheduledTask2() {
         String time = DateExUtils.commonDatePathStr();
         LOGGER.info("包装机excel数据读取开始:" + time);

+ 14 - 3
src/main/resources/application.yml

@@ -1,8 +1,19 @@
+file:
+  path: D:\project\delivery_project\远程制药\后台\ycpharmacy_excel_service\excel
+
 server:
   port: 8080
-mybatis-plus:
-  configuration:
-    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
+logging:
+  level:
+    com.chz.mapper: info
+#mybatis-plus:
+  #configuration:
+    #map-underscore-to-camel-case: true
+    #cache-enabled: true
+    #lazy-loading-enabled: true
+    #log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
+    #log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl
+
 # MyBatis配置
 mybatis:
   # 配置mapper的扫描,找到所有的mapper.xml映射文件

+ 31 - 154
src/main/resources/logback-spring.xml

@@ -1,178 +1,55 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<configuration>
-    <include resource="org/springframework/boot/logging/logback/base.xml"/>
-    <jmxConfigurator/>
-    <contextName>car_pay_center</contextName>
-    <property name="LOG_PATH" value="./logs"/>
-    <!--设置系统日志目录-->
-    <property name="APPDIR" value="ycpharmacy-excel-service"/>
-
-    <!-- 彩色日志 -->
-    <!-- 彩色日志依赖的渲染类 -->
-    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
-    <conversionRule conversionWord="wex"
-                    converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
-    <conversionRule conversionWord="wEx"
-                    converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
-    <!-- 彩色日志格式 -->
-    <property name="CONSOLE_LOG_PATTERN"
-              value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
-
-    <!-- 日志记录器,日期滚动记录 -->
-    <appender name="FILEERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
-        <!-- 正在记录的日志文件的路径及文件名 -->
-        <file>${LOG_PATH}/${APPDIR}/log_error.log</file>
-        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
-        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
-            <!-- 归档的日志文件的路径,例如今天是2013-12-21日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
-            而2013-12-21的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
-            <fileNamePattern>${LOG_PATH}/${APPDIR}/error/%d{yyyyMMdd}/%d{HH:mm:ss}.%i.log</fileNamePattern>
-            <!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始,
-            命名日志文件,例如log-error-2013-12-21.0.log -->
-            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
-                <maxFileSize>2MB</maxFileSize>
-            </timeBasedFileNamingAndTriggeringPolicy>
-        </rollingPolicy>
-        <!-- 追加方式记录日志 -->
-        <append>true</append>
-        <!-- 日志文件的格式 -->
-        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
-            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L [%thread] - %msg%n</pattern>
-            <charset>utf-8</charset>
+<configuration scan="true" scanPeriod="60 seconds" debug="false">
+    <contextName>febs</contextName>
+    <springProperty scope="context" name="springAppName" source="spring.application.name"/>
+    <property name="log.path" value="./logs/ycpharmacy-packer-service" />
+    <property name="log.maxHistory" value="15" />
+    <property name="log.colorPattern" value="%magenta(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%-5level) %boldCyan([${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]) %yellow(%thread) %green(%logger) %msg%n"/>
+    <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level [${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}] %thread %logger %msg%n"/>
+
+    <!--输出到控制台-->
+    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
+        <encoder>
+            <pattern>${log.colorPattern}</pattern>
         </encoder>
-        <!-- 此日志文件只记录info级别的 -->
-        <filter class="ch.qos.logback.classic.filter.LevelFilter">
-            <level>error</level>
-            <onMatch>ACCEPT</onMatch>
-            <onMismatch>DENY</onMismatch>
-        </filter>
     </appender>
 
-    <!-- 日志记录器,日期滚动记录 -->
-    <appender name="FILEWARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
-        <!-- 正在记录的日志文件的路径及文件名 -->
-        <file>${LOG_PATH}/${APPDIR}/log_warn.log</file>
-        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+    <!--输出到文件-->
+    <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
-            <!-- 归档的日志文件的路径,例如今天是2013-12-21日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
-            而2013-12-21的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
-            <fileNamePattern>${LOG_PATH}/${APPDIR}/warn/%d{yyyyMMdd}/%d{HH:mm:ss}.%i.log</fileNamePattern>
-            <!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始,
-            命名日志文件,例如log-error-2013-12-21.0.log -->
-            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
-                <maxFileSize>2MB</maxFileSize>
-            </timeBasedFileNamingAndTriggeringPolicy>
+            <fileNamePattern>${log.path}/info/info.%d{yyyy-MM-dd}.log</fileNamePattern>
+            <MaxHistory>${log.maxHistory}</MaxHistory>
         </rollingPolicy>
-        <!-- 追加方式记录日志 -->
-        <append>true</append>
-        <!-- 日志文件的格式 -->
-        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
-            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L [%thread] - %msg%n</pattern>
-            <charset>utf-8</charset>
+        <encoder>
+            <pattern>${log.pattern}</pattern>
         </encoder>
-        <!-- 此日志文件只记录info级别的 -->
         <filter class="ch.qos.logback.classic.filter.LevelFilter">
-            <level>warn</level>
+            <level>INFO</level>
             <onMatch>ACCEPT</onMatch>
             <onMismatch>DENY</onMismatch>
         </filter>
     </appender>
 
-    <!-- 日志记录器,日期滚动记录 -->
-    <appender name="FILEINFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
-        <!-- 正在记录的日志文件的路径及文件名 -->
-        <file>${LOG_PATH}/${APPDIR}/log_info.log</file>
-        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+    <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
-            <!-- 归档的日志文件的路径,例如今天是2013-12-21日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
-            而2013-12-21的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
-            <fileNamePattern>${LOG_PATH}/${APPDIR}/info/%d{yyyyMMdd}/%d{HH:mm:ss}.%i.log</fileNamePattern>
-            <!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始,
-            命名日志文件,例如log-error-2013-12-21.0.log -->
-            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
-                <maxFileSize>20MB</maxFileSize>
-            </timeBasedFileNamingAndTriggeringPolicy>
+            <fileNamePattern>${log.path}/error/error.%d{yyyy-MM-dd}.log</fileNamePattern>
         </rollingPolicy>
-        <!-- 追加方式记录日志 -->
-        <append>true</append>
-        <!-- 日志文件的格式 -->
-        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
-            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger [%thread] - %msg%n</pattern>
-            <charset>utf-8</charset>
+        <encoder>
+            <pattern>${log.pattern}</pattern>
         </encoder>
-        <!-- 此日志文件只记录info级别的 -->
         <filter class="ch.qos.logback.classic.filter.LevelFilter">
-            <level>info</level>
+            <level>ERROR</level>
             <onMatch>ACCEPT</onMatch>
             <onMismatch>DENY</onMismatch>
         </filter>
     </appender>
 
-    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
-        <!--encoder 默认配置为PatternLayoutEncoder-->
-        <encoder>
-            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
-            <charset>utf-8</charset>
-        </encoder>
-        <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
-        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
-            <level>debug</level>
-        </filter>
-    </appender>
-
-    <!--myibatis log configure-->
-    <logger name="com.apache.ibatis" level="TRACE"/>
-    <logger name="java.sql.Connection" level="DEBUG"/>
-    <logger name="java.sql.Statement" level="DEBUG"/>
-    <logger name="java.sql.PreparedStatement" level="DEBUG"/>
-
-
-    <!-- 生产环境下,将此级别配置为适合的级别,以免日志文件太多或影响程序性能 -->
-    <!--
-      <springProfile name="dev">
-      </springProfile>
-      可以使用这个标签实现不同环境不同日志级别
-        <springProfile name="test">
-            <root level="INFO">
-                <appender-ref ref="FILE"/>
-                <appender-ref ref="STDOUT"/>
-            </root>
-        </springProfile>
-     -->
-
-    <!-- 异步输出 -->
-    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
-        <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
-        <discardingThreshold>0</discardingThreshold>
-        <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
-        <queueSize>256</queueSize>
-        <!-- 添加附加的appender,最多只能添加一个 -->
-        <appender-ref ref="FILEINFO"/>
-    </appender>
-
-
-    <!--
-    springProperty 可以读取配置文件中的属性 <file>logs/${logName}.log</file>    使用方法
-    <springProperty scope="context" name="logName"
-    source="spring.application.name" defaultValue="localhost"/>
-    -->
+    <root level="debug">
+        <appender-ref ref="console" />
+    </root>
 
-    <springProfile name="dev">
-        <root level="INFO">
-            <appender-ref ref="FILEERROR" />
-            <appender-ref ref="FILEWARN" />
-            <appender-ref ref="ASYNC" />
-            <!-- 生产环境将请stdout,testfile去掉 -->
-            <!-- <appender-ref ref="STDOUT"/>-->
-        </root>
-    </springProfile>
-    <springProfile name="pro">
-        <root level="INFO">
-            <appender-ref ref="FILEERROR" />
-            <appender-ref ref="FILEWARN" />
-            <appender-ref ref="ASYNC" />
-            <!-- 生产环境将请stdout,testfile去掉 -->
-            <!-- <appender-ref ref="STDOUT"/>-->
-        </root>
-    </springProfile>
+    <root level="info">
+        <appender-ref ref="file_info" />
+        <appender-ref ref="file_error" />
+    </root>
 </configuration>

+ 2 - 0
src/main/resources/mapper/WorkPackerMapper.xml

@@ -15,6 +15,7 @@
         pack_time,
         operator,
         remark,
+        file_path,
         insert_time,
         create_by,
         create_user_id,
@@ -39,6 +40,7 @@
             #{item.packTime},
             #{item.operator},
             #{item.remark},
+            #{item.filePath},
             #{item.insertTime},
             #{item.createBy},
             #{item.createUserId},