预发环境与生产环境共享数据库时定时任务重复执行问题解决

背景:

为保证预发环境的真实性,预发与生产环境往往共享数据库,在定时任务列表中,预发与生产环境都会从任务列表中获取定时任务,然后执行,这会导致定时任务会执行重复。

解决方法:

在job中增加一个环境变量字段,如test,stg,prod等,当创建任务的时候获取执行创建任务服务器的profile,根据profile插入到jod的上述字段中。定时任务执行时判断任务是否符合执行机器的profile,符合则执行,不符合则不执行。

具体可执行操作:

1.在tomcat或者启动脚本中加入vm参数,例如

  -Dspring.profiles.active=stg 
2.代码获取profile的办法示例:

@Autowired
Environment env;

简单的controller获取如下:

  @RequestMapping(value="/getProfiles")
  @ResponseBody
  public String getProfiles() throws ParseException {
      StringBuffer sb=new StringBuffer();
      String[] profiles= env.getActiveProfiles();
      for(String profile:profiles){
          sb.append(profile).append("
");
      }
    return sb.toString();
  }
原文地址:https://www.cnblogs.com/davidwang456/p/6839751.html