Office转换pdf(oppenOffice和jodconverter-core-3.0-beta-4)解决并发问题

转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/94783897 谢谢

Office转换pdf解决并发问题

由于项目之前的代码 https://blog.csdn.net/Amor_Leo/article/details/89389321
不能支持并发 于是用了锁机制和阻塞队列实现
方法 一 :

@Component
public class Office2PDFUtils {

    private static Logger logger = LoggerFactory.getLogger(Office2PDFUtils.class);

    @Value("${oppenOffice.winPath}")
    private String winPath;
   
    @Value("${oppenOffice.linuxPath}")
    private String linuxPath;

    @Value("${oppenOffice.port}")
    private String port;

    private static BlockingQueue<OfficeManager> OfficeManagerQueue = new LinkedBlockingDeque<>();

    private static Lock lock = new ReentrantLock();

    /** * @Description: 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件 * @method: openOfficeToPDF * @Param: inputFilePath * @Param: outputFilePath * @return: boolean * @auther: LHL */
    public boolean openOfficeToPDF(String inputFilePath, String outputFilePath) {
        return office2Pdf(inputFilePath, outputFilePath);
    }

    /** * @Description: 根据操作系统的名称,获取OpenOffice.org 的安装目录 * @method: getOfficeHome * @Param: * @return: java.lang.String OpenOffice.org 的安装目录 * @auther: LHL */
     private String getOfficeHome() {
        String osName = System.getProperty("os.name");
        logger.debug("操作系统名称:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return linuxPath;
        } else if (Pattern.matches("Windows.*", osName)) {
            return winPath;
        } else if (Pattern.matches("Mac.*", osName)) {
            return winPath;
        }
        return null;
    }
  
    /** * @Description: 在bean创建实例时, 连接OpenOffice.org 并且启动OpenOffice.org * @method: initOpenOfficeService * @Param: * @return: void * @auther: LHL */
    @PostConstruct
    public void initOpenOfficeService() {
        DefaultOfficeManagerConfiguration builder = new DefaultOfficeManagerConfiguration();
        builder.setOfficeHome(getOfficeHome());        
        //设置任务执行超时为15分钟
        builder.setTaskExecutionTimeout(1000 * 60 * 15L);
        //设置任务队列超时为24小时
        builder.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        for (String port : port.split(",")) {
            builder.setPortNumbers(Integer.valueOf(port));
            OfficeManager OfficeManager = builder.buildOfficeManager();
            try {
                OfficeManager.start();
                logger.debug("***********************officeManager 启动!***********************");
            } catch (OfficeException e) {
                //打印日志
                logger.debug("***********************启动 openOffice 失败!***********************");
                e.printStackTrace();
            }
            try {
                OfficeManagerQueue.put(OfficeManager);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /** * @Description: bean销毁时停止 * @method: destroyOpenOfficeService * @Param: * @return: void * @auther: LHL */
    @PreDestroy
    public void destroyOpenOfficeService() {
        for (OfficeManager manager : OfficeManagerQueue) {
            try {
                logger.debug("关闭 officeManager");
                manager.stop();
            } catch (OfficeException e) {
                logger.debug("officeManager关闭失败!" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /** * @Description: 转换文件 * @method: convertFile * @Param: inputFile * @Param: outputFilePath * @Param: officeManager * @return: java.io.File * @auther: LHL */
    private File convertFile(File inputFile, String outputFilePath, OfficeManager officeManager) throws OfficeException {
        File outputFile = new File(outputFilePath);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        // 锁
        lock.lock();
        converter.convert(inputFile, outputFile);
        //释放锁
        lock.unlock();
        try {
            OfficeManagerQueue.put(officeManager);
            logger.debug("blockingQueue puted OfficeManagerQueue size :" + OfficeManagerQueue.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.debug("文件:" + inputFile.getAbsolutePath() + "\n转换为目标文件:" + outputFile + "\n成功!");
        return outputFile;
    }
	/** * 文件名需要唯一 */
    public boolean office2Pdf(String inputFilePath, String outputFilePath) {
        OfficeManager officeManager = null;
        try {
            if (StringUtils.isEmpty(inputFilePath)) {
                logger.debug("输入文件地址为空,转换终止!");
                return false;
            }
            File inputFile = new File(inputFilePath);
            if (!inputFile.exists()) {
                logger.debug("输入文件不存在,转换终止!");
                return false;
            }
            officeManager = OfficeManagerQueue.take();
            logger.debug("blockingQueue taked , OfficeManagerQueue size :" + OfficeManagerQueue.size());
            File file = convertFile(inputFile, outputFilePath, officeManager);
            if (!file.exists()) {
                logger.debug("转换文件不存在!转换失败!!");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("转换异常");
            return false;
        }
    }
}

方法 二 :
初始化OpenOffice

@Component
public class InitOpenOfficeUtil {

    private static Logger logger = LoggerFactory.getLogger(InitOpenOfficeUtil.class);

    @Value("${oppenOffice.winPath}")
    private String winPath;
    @Value("${oppenOffice.linuxPath}")
    private String linuxPath;
    @Value("${oppenOffice.port}")
    private String port;

    private static BlockingQueue<OfficeManager> OfficeManagerQueue = new LinkedBlockingDeque<>();
    /** * @Description: 根据操作系统的名称,获取OpenOffice.org 的安装目录 * @method: getOfficeHome * @Param: * @return: java.lang.String OpenOffice.org 的安装目录 * @auther: LHL */
    private String getOfficeHome() {
        String osName = System.getProperty("os.name");
        logger.debug("操作系统名称:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return linuxPath;
        } else if (Pattern.matches("Windows.*", osName)) {
            return winPath;
        } else if (Pattern.matches("Mac.*", osName)) {
            return winPath;
        }
        return null;
    }

    /** * @Description: 在bean创建实例时, 连接OpenOffice.org 并且启动OpenOffice.org * @method: initOpenOfficeService * @Param: * @return: void * @auther: LHL */
    @PostConstruct
    public void initOpenOfficeService() {
        DefaultOfficeManagerConfiguration builder = new DefaultOfficeManagerConfiguration();
        builder.setOfficeHome(getOfficeHome());
        //设置任务执行超时为15分钟
        builder.setTaskExecutionTimeout(1000 * 60 * 15L);
        //设置任务队列超时为24小时
        builder.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        for (String port : port.split(",")) {
            builder.setPortNumbers(Integer.valueOf(port));
            OfficeManager OfficeManager = builder.buildOfficeManager();
            try {
                OfficeManager.start();
                logger.debug("***********************officeManager 启动!***********************");
            } catch (OfficeException e) {
                //打印日志
                logger.debug("***********************启动 openOffice 失败!***********************");
                e.printStackTrace();
            }
            try {
                OfficeManagerQueue.put(OfficeManager);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /** * @Description: bean销毁时停止 * @method: destroyOpenOfficeService * @Param: * @return: void * @auther: LHL */
    @PreDestroy
    public void destroyOpenOfficeService() {
        for (OfficeManager manager : OfficeManagerQueue) {
            try {
                logger.debug("关闭所有 officeManager");
                manager.stop();
            } catch (OfficeException e) {
                logger.debug("officeManager 关闭 失败!" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public  OfficeManager  take(){
        OfficeManager take = null;
        try {
            take = OfficeManagerQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return take;
    }

    public  void  put(OfficeManager officeManager){
        try {
            OfficeManagerQueue.put(officeManager);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public  int  size(){
        return  OfficeManagerQueue.size();
    }

OppenOffice工具类

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)  //多例
public class Office2PDFUtils {

    private static Logger logger = LoggerFactory.getLogger(Office2PDFUtils.class);

    @Autowired
    private InitOpenOfficeUtil initOpenOfficeUtil;

    /** * @Description: 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件 * @method: openOfficeToPDF * @Param: inputFilePath * @Param: outputFilePath * @return: boolean * @auther: LHL */
    public boolean openOfficeToPDF(String inputFilePath, String outputFilePath) {
        return office2Pdf(inputFilePath, outputFilePath);
    }


    /** * @Description: 转换文件 * @method: convertFile * @Param: inputFile * @Param: outputFilePath * @Param: officeManager * @return: java.io.File * @auther: LHL */
    private File convertFile(File inputFile, String outputFilePath, OfficeManager officeManager) throws OfficeException {
        File outputFile = new File(outputFilePath);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.convert(inputFile, outputFile);
        initOpenOfficeUtil.put(officeManager);
        logger.debug("blockingQueue puted OfficeManagerQueue size :" + initOpenOfficeUtil.size());
        logger.debug("文件:" + inputFile.getAbsolutePath() + "\n转换为目标文件:" + outputFile + "\n成功!");
        return outputFile;
    }

    /** * 文件名需要唯一 */
    public boolean office2Pdf(String inputFilePath, String outputFilePath) {
        OfficeManager officeManager = null;
        try {
            if (StringUtils.isEmpty(inputFilePath)) {
                logger.debug("输入文件地址为空,转换终止!");
                return false;
            }
            File inputFile = new File(inputFilePath);
            if (!inputFile.exists()) {
                logger.debug("输入文件不存在,转换终止!");
                return false;
            }
            officeManager = initOpenOfficeUtil.take();
            logger.debug("blockingQueue taked , OfficeManagerQueue size :" + initOpenOfficeUtil.size());
            File file = convertFile(inputFile, outputFilePath, officeManager);
            if (!file.exists()) {
                logger.debug("转换文件不存在!转换失败!!");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("转换异常");
            initOpenOfficeUtil.put(officeManager);
            logger.debug("blockingQueue puted OfficeManagerQueue size :" + initOpenOfficeUtil.size());
            return false;
        }
    }
}

yml

#配置OpenOffice的目录
oppenOffice:
  winPath: D:/SoftWare/OpenOffice
  linuxPath: /usr/local/OpenOffice
  port: 9200,9201,9202,9203,9204,9205,9206,9207,9208,9209

pom


		
			org.artofsolving.jodconverter
			jodconverter-core
			3.0-beta-4
		
		
		
			org.openoffice
			juh
			4.1.2
		

		
			org.openoffice
			jurt
			4.1.2
		

		
			org.openoffice
			ridl
			4.1.2
		

		
			org.openoffice
			unoil
			4.1.2
		

		
			org.apache.commons
			commons-io
			1.3.2
		

你可能感兴趣的:(JAVA)