设为首页 收藏本站
查看: 1138|回复: 0

[经验分享] 使用Quartz 定时生成话单、把话单上传FTP、把话单移动到备份目录

[复制链接]

尚未签到

发表于 2016-6-11 05:04:35 | 显示全部楼层 |阅读模式
  一、下面是Quartz的配置文件
  <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:soap="http://cxf.apache.org/bindings/soap"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/bindings/soap
http://cxf.apache.org/schemas/configuration/soap.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd"
default-lazy-init="false">
  <!-- 使用QuartzJobBean的定时器 -->
<bean id="usingQuartz" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
   <!-- ftp上传job -->
<value>com.unistore.pay.ftp.MyTaskUsingQuartzJobBean</value>
</property>
</bean>
<bean id="usingbillQuartz" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
   <!-- 生成话单job -->
<value>com.unistore.pay.ftp.GenerateBilInfoQuartz</value>
</property>
</bean>
<bean id="usingbfbillQuartz" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
   <!-- 备份话单job -->
<value>com.unistore.pay.ftp.GenerateBFBilQuartz</value>
</property>
</bean>
<!-- ftp上传定时触发器 -->
<bean id="usingQuartzCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="usingQuartz" />
</property>
<property name="cronExpression">
<value>40 * * * * ?</value>
<!--<value>0 30 01 * * ?</value> -->
</property>
</bean>
<!-- 中间账单生成定时触发器 -->
<bean id="usingbillQuartzCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="usingbillQuartz" />
</property>
<property name="cronExpression">
<value>20 * * * * ?</value>
<!--<value>0 00 00 * * ?</value> -->
</property>
</bean>
<!-- 中间账单备份定时触发器 -->
<bean id="usingbfbillQuartzCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="usingbfbillQuartz" />
</property>
<property name="cronExpression">
<value>59 * * * * ?</value>
<!--<value>0 30 05 * * ?</value> -->
</property>
</bean>
<!-- 启动定时器 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false">
<property name="triggers">
<list>
<ref bean="usingQuartzCronTrigger" />
<ref bean="usingbillQuartzCronTrigger" />
<ref bean="usingbfbillQuartzCronTrigger" />
</list>
</property>
</bean>
</beans>
  
  
  二、下面是关于每个类的说明(这里只是个demo,所以写法有点粗糙)
  
  1、上传FTP的JobDetail类
  
  package com.unistore.pay.ftp;
  import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
  import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
  import com.enterprisedt.net.ftp.FTPException;
  public class MyTaskUsingQuartzJobBean extends QuartzJobBean {
String dateTime =null;
String filepath=null;
  // 该类FTPBiz的写法是重写了com.enterprisedt.net.ftp.FTPClient,请看下面该类的解释
  FTPBiz ftpbiz=new FTPBiz();
Integer result=0;
/**
* 定时任务
* @return
*/
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
filepath=ConstantParameter.FTPLOCALPATH+this.getSuccPayFile();
System.out.println(filepath);
File files=new File(filepath);
try {
result=ftpbiz.saveServer(files);
} catch (IOException e) {
result = CodeResource.FTP_CONNECT_FALSE;
} catch (FTPException e) {
result = CodeResource.FTP_CONNECT_FALSE;
}
System.out.println(result);
}
  /**
* 转换时间格式
* @return
*/
public String getChangeTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取服务器的当前时间
dateTime = sdf.format(new Date(System.currentTimeMillis()));
return dateTime;
}
/**
* 获取成功交易的对账文件名称
* @return
*/
public String getSuccPayFile(){
dateTime=this.getChangeTime();
filepath=ConstantParameter.BUSINESSLOGO+"_"+dateTime+"_1.txt";
return filepath;
}
}
  
  // 该类FTPBiz是重写了com.enterprisedt.net.ftp.FTPClient,区别不大,只是重新包装了自己的异常和业务实现
package com.unistore.pay.ftp;
  
  import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
  import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPException;
  
public class FTPBiz {
private static final Logger logger = Logger
.getLogger(FTPBiz.class);
private static final FTPBiz singleton = new FTPBiz();
// 获取FTP服务器联接
FtpVO ftpVO =null;
private FTPClient client = null;
  // public FtpVO ftpVO = new FtpVO();
  /**
* 获取单实例
*
* @return FtpBiz
*/
public static FTPBiz getInstance() {
return singleton;
}
  public FTPBiz() {
  }
  /**
* 获取存在服务器的文件名 文件名+当前时间(yyyyMMdd)+文件类型(.txt)
*
* @param tfName
* @return
*/
public String changeFileName(String tfName) {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
   // 获取服务器的当前时间
String dateTime = sdf.format(new Date(System.currentTimeMillis()));
   // 获取文件名的类型
String fileType = tfName.substring(tfName.lastIndexOf("."), tfName
.length());
   return tfName.substring(0, tfName.lastIndexOf(".") > 110 - fileType
.length() ? 110 - fileType.length() : tfName.lastIndexOf("."))
+ dateTime + fileType;
}
  /**
* 上传文件操作
*
* @param fileName
* String
* @param file
* FormFile
* @return
* @throws IOException
* @throws FTPException
* @throws FTPException
*/
public int saveServer(File file) throws IOException, FTPException {
int result = CodeResource.FTP_OPERATION_SUCCESS;
String fileName=file.getName();
   MyFTPClient ftpClient = null;
// 参数校验,判断file 是否为空
if (null == file) {
result=CodeResource.FILE_ISNULL;
logger.debug("File is empty");
return result;
}
//文件是否存在
if (!file.exists()){
result=CodeResource.FILE_ISEXIST;
logger.debug("File does not exist");
//return result;
}
//文件是否是一个文件夹
if (!file.isFile()){
result=CodeResource.FILE_ISFILE;
logger.debug("Whether a file is a file folder");
return result;
}
//判断文件是否太大
long filesize=Long.parseLong(ConstantParameter.FTPFILEMAX);
if (file.length() > filesize) {
result=CodeResource.FILE_OVER;
logger.debug("File is too large");
return result;
}
try {
// FTP客户端对象
ftpClient = new MyFTPClient();
// 执行FTP连接初始化
ftpVO=new FtpVO();
//服务器IP
ftpVO.setServer(ConstantParameter.FTPSERVER);
//服务器端口
ftpVO.setPort(Integer.parseInt(ConstantParameter.FTPPORT));
//ftp服务器访问用户名
ftpVO.setUser(ConstantParameter.FTPUSER);
//ftp服务器密码
ftpVO.setPassword(ConstantParameter.FTPPASSWORD);
//ftp服务器文件存放路径
ftpVO.setServerPath(ConstantParameter.FTPSERVERPATH);
ftpClient.init(ftpVO.getServer(), ftpVO.getPort(), ftpVO.getUser(),
ftpVO.getPassword());
logger.info("FTP link successfully");
} catch (Exception fe) {
result = CodeResource.FTP_CONNECT_FALSE;
logger.info("FTP link failure");
return result;
}
// 判断该文件在ftp服务器上面是否已存在,若存在,则删除文件
try {
String b[] = ftpClient.dir(ConstantParameter.FTPSERVERPATH,fileName);
if (b != null && b.length != 0) {
ftpClient.delete(ConstantParameter.FTPSERVERPATH,fileName);
logger.info("File deleted successfully");
}
} catch (Exception e) {
result = CodeResource.FTP_CONNECT_FALSE;
logger.info("File deleted failure");
return result;
}
FileInputStream is = new FileInputStream(file);
   // 将文件上传到FTP服务器
try {
ftpClient.put(ftpVO.getServerPath(),is,fileName);
}catch (IOException e) {
result = CodeResource.IO_CODE_ERROR;
logger.info("File upload successfully");
}
if (ftpClient != null) {
ftpClient.close();
logger.info("closed ftpserver");
}
   // 返回成功标识
return result;
}


/**
* 删除文件操作
*
* @param tfName
* String
* @return int
* @throws IOException
* @throws FTPException
*/
public int deleteFtpFile(String fileName) throws Exception {
// 是否成功标识
int result = CodeResource.FTP_OPERATION_SUCCESS;
   MyFTPClient ftpClient = null;
   // 执行FTP连接初始化
try {
// FTP客户端对象
ftpClient = new MyFTPClient();
// 执行FTP连接初始化
ftpVO=new FtpVO();
ftpVO.setServer(ConstantParameter.FTPSERVER);
//服务器端口
ftpVO.setPort(Integer.parseInt(ConstantParameter.FTPPORT));
//ftp服务器访问用户名
ftpVO.setUser(ConstantParameter.FTPUSER);
//ftp服务器密码
ftpVO.setPassword(ConstantParameter.FTPPASSWORD);
//ftp服务器文件存放路径
ftpVO.setServerPath(ConstantParameter.FTPSERVERPATH);

ftpClient.init(ftpVO.getServer(), ftpVO.getPort(), ftpVO.getUser(),
ftpVO.getPassword());
   // 判断文件是否存在
try {
String b[] = ftpClient.dir(ConstantParameter.FTPSERVERPATH,fileName);
if (b == null || b.length == 0) {
result = CodeResource.FTP_FILENULL;
return result;
} else {
ftpClient.delete(ConstantParameter.FTPSERVERPATH,fileName);
System.out.println("删除成功!");
}
} catch (Exception e) {
result = CodeResource.FTP_CONNECT_FALSE;
return result;
}
} catch (FTPException fe) {
result = CodeResource.FTP_OPERATION_FAILURE;
} finally {
if (ftpClient != null) {
ftpClient.close();
}
}
return result;
}

/**
* 编码转换
*
* @param fileName
* String
* @return String
*/
public String convert(String fileName) {
   try {
byte bt[] = fileName.getBytes("iso-8859-1");
String vfName = new String(bt, "ISO-8859-1");
   return vfName;
} catch (Exception e) {
return fileName;
}
  }
  }
  
  
  2、从数据库读取数据,并生成话单文件的JobDetail类
  
  package com.unistore.pay.ftp;
  import java.text.SimpleDateFormat;
import java.util.Date;
  
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
  
import com.unistore.pay.service.IPayOptLogService;
import com.unistore.pay.utils.UtilDateTime;
  
  public class GenerateBilInfoQuartz extends QuartzJobBean {
   //读取数据库并生成话单的service
private IPayOptLogService payOptLogService;

/**
* 定时任务
* @return
*/
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
this.getpaysucc();
}

/**
* 转换时间格式
* @return
*/
public String getChangeTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 获取服务器的当前时间
String dateTime = sdf.format(new Date(System.currentTimeMillis()));
return dateTime;
}
/**
* 打印交易成功记录
* @return
*/
public void getpaysucc(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("/applicationContext.xml");
payOptLogService = (IPayOptLogService) ctx.getBean("payOptLogService");
String datetime=this.getChangeTime();
Long createds=UtilDateTime.getTimetoss(datetime);
Long created=UtilDateTime.getTimetoss(datetime)-86400;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取服务器的当前时间
String dateTime = sdf.format(new Date(System.currentTimeMillis()));
String filepath=ConstantParameter.FTPLOCALPATH+ConstantParameter.BUSINESSLOGO+"_"+dateTime+"_1.txt";
boolean f=payOptLogService.selectBetweenBlock(5, created,createds,filepath);
System.out.println(f);
}
}
  
  
  //读取数据库并生成话单的service
public class PayOptLogService implements IPayOptLogService {
private static final Logger logger = Logger
.getLogger(PayOptLogService.class);
  // 日志操作Dao
private PayOptLogDao payOptLogDao;
  
/**
* 打印中间账户交易记录
* @param createds
* @param way
* @param created
* @return
*/
public boolean selectBetweenBlock(int way,long created,long createds,String filepath) {
// TODO Auto-generated method stub
boolean f=false;
Map map=new HashMap<Object,Object>();
if(way!=0){
map.put("way", way);
}
map.put("createds", createds);
map.put("created", created);
  
   //数据库是mysql,持久层框架是ibatis
List<PayOptLog> list=payOptLogDao.find("selectBetweenBlock", map);

logger.debug("select success");
PrintWriter pw=null;
try {
File file=new File(filepath);
if(!file.exists())//如果文件不存在,则新建.
{
File parentDir=new File(file.getParent());
if(!parentDir.exists())//如果所在目录不存在,则新建.
parentDir.mkdirs();
file.createNewFile();
logger.debug("Successfully create the file");
}else{
logger.debug("File is exists");
return f;
}
pw = new PrintWriter( new FileWriter(filepath,true) );
} catch (IOException e) {
logger.debug("File printing failure");
e.printStackTrace();
}
  //下面是生成话单文件
  话单头:行数|总金额
  话单体:
pw.println(list.size()+"|"+list.get(0).getTotalPrice());
for (PayOptLog payOptLog : list) {
payOptLog.setBusinessFoot(ConstantParameter.BUSINESSFOOT);
payOptLog.setParlogo(ConstantParameter.BUSINESSLOGO);
pw.println(payOptLog.getPayFloodId()+"|"+payOptLog.getOrderSn()+"|"+payOptLog.getBusinessFoot()+"|"+payOptLog.getPaytime()+"|"+payOptLog.getCount()+"|"+payOptLog.getParlogo()+"|"+payOptLog.getDescription());
logger.debug("File printing success");
pw.close();
f=true;
}
return f;
}
}
  
  
  3、把话单临时生成的文件夹里面的话单文件移动到备份文件夹
  
  package com.unistore.pay.ftp;
  import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
  import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
  
public class GenerateBFBilQuartz extends QuartzJobBean {
String dateTime =null;
String filepath=null;
private static final Logger logger = Logger
.getLogger(GenerateBFBilQuartz.class);
/**
* 定时任务
* @return
*/
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
filepath=ConstantParameter.FTPLOCALPATH+this.getSuccPayFile();
File dstFile = new File(filepath);
File upFile = new File(ConstantParameter.BFBUYPATH+this.getSuccPayFile());
try {
if(!upFile.exists())//如果文件不存在,则新建.
{
File parentDir=new File(upFile.getParent());
if(!parentDir.exists())//如果所在目录不存在,则新建.
parentDir.mkdirs();
upFile.createNewFile();
logger.debug("Successfully create the file");
}
FileUtils.copyFile(dstFile,upFile);
logger.info("Successfully bf the file");
if(dstFile.exists()){
dstFile.delete();
logger.debug("Successfully delete the file");
}
} catch (IOException e) {
logger.info("File bf failure");
e.printStackTrace();
}
}
/**
* 转换时间格式
* @return
*/
public String getChangeTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取服务器的当前时间
dateTime = sdf.format(new Date(System.currentTimeMillis()));
return dateTime;
}
/**
* 获取成功交易的对账文件名称
* @return
*/
public String getSuccPayFile(){
dateTime=this.getChangeTime();
filepath=ConstantParameter.BUSINESSLOGO+"_"+dateTime+"_1.txt";
return filepath;
}
}
  
  
  //后续将继续完善 ^_^
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228764-1-1.html 上篇帖子: java写的从ftp上找到文件并把文件里的数据插入到数据库的工具类 下篇帖子: FTP协议结构简析及其相应状态响应码细则
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表