esjob搭建

需要引入的依赖

<dependency>
			<groupId>com.github.kuhn-he</groupId>
			<artifactId>elastic-job-lite-spring-boot-starter</artifactId>
			<version>2.1.53</version>
			<exclusions>
				<exclusion>
					<artifactId>curator-client</artifactId>
					<groupId>org.apache.curator</groupId>
				</exclusion>
				<exclusion>
					<artifactId>curator-framework</artifactId>
					<groupId>org.apache.curator</groupId>
				</exclusion>
				<exclusion>
					<artifactId>curator-recipes</artifactId>
					<groupId>org.apache.curator</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-framework</artifactId>
			<version>2.12.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-recipes</artifactId>
			<version>2.12.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-client</artifactId>
			<version>2.12.0</version>
		</dependency>

application-pro

# zookeeper集群
elaticjob:
  zookeeper:
    server-lists : 192.168.100.220:2181,192.168.100.144:2181,192.168.100.222:2181
    namespace: schedule-task

配置文件

package com.wt.vegatask.core.config;

import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* Created by liben on 2018/8/20.
*/
@Configuration
@ConditionalOnExpression("'${elastic.zookeeper.server-lists}'.length() >0")
public class ElasticJobConfig {
   /**
    * 初始化配置
    * @param serverList
    * @param namespace
    * @return
    */
   @Bean(initMethod = "init")
   public ZookeeperRegistryCenter regCenter(@Value("${elaticjob.zookeeper.server-lists}") String serverList
           , @Value("${elaticjob.zookeeper.namespace}") String namespace) {

       return new ZookeeperRegistryCenter(new ZookeeperConfiguration(serverList, namespace));
   }

}

案例

package com.wt.kronos.schedulehistory.new_jop;

/**
 * @author Jinpan
 * @description 2
 * @createTime 2019/06/28 11:12
 */

import com.aliyuncs.exceptions.ClientException;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob;
import com.wt.base.aliMessage.AliSMSUtil;
import com.wt.base.schedule.model.Schedule;
import com.wt.base.util.DateUtil;
import com.wt.base.util.StringUtil;
import com.wt.gus.api.client.GusQueryRemote;
import com.wt.gus.dto.query.FindUserInfoListDTO;
import com.wt.gus.vo.UserInfoVO;
import com.wt.kronos.schedulehistory.service.RedisService;
import com.wt.kronos.schedulehistory.service.ScheduleService;
import com.wt.vega.api.client.VegaStationRemote;
import com.wt.vega.api.client.WeatherRemote;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

//每5分钟执行一次
@Slf4j
@Component
@ElasticSimpleJob(cron = "0 0/5 * * * ?",jobName = "ScheduleMsgForTwoHoursNew",description = "行程出发时间前2小时[乘车提醒]",dataSource = "masterDataSource")
public class ScheduleMsgForTwoHoursNew implements SimpleJob {

    @Autowired
    private ScheduleService scheduleService;//获取行程
    @Autowired
    private VegaStationRemote vegaStationRemote;//调用发公众号消息
    @Autowired
    private WeatherRemote weatherRemote;//调用天气
    @Autowired
    private GusQueryRemote gusQueryRemote;
    @Autowired
    private RedisService redisService;

    @Value("${wxConfig.appIdCzt}")
    private String appId;//公众号appId
    @Value("${wxConfig.templateIdMsmForBeforStartTwoHour}")
    private String msMtype;//短信模板id
    @Value("${wxConfig.appIdCztXcx}")
    private String appIdXcx;//小程序appId
    @Value("${wxConfig.templateIdCztBeforStartTwoHour}")
    private String templateId;//模板ID
    private static final String pathGlobal = "pages/tabBar/station/index";//跳转小程序路径
    private static final String remark = "以上信息仅供参考,具体以火车站信息公告为准,\\n点击下方查看更多详情信息。";

    @Override
    public void execute(ShardingContext shardingContext) {
        Date dateNow = DateUtil.parse(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:00"));//防止秒的影响
        //minuteEnd应该是125,126是冗余1分钟
        Schedule schedule = Schedule.builder().startTime(DateUtil.addMinutes(dateNow, 120)).endTime(DateUtil.addMinutes(dateNow, 125)).build();
        List<Schedule> list = scheduleService.findMsgStartList(schedule);
        if (null == list || list.size() == 0) {
            return;
        }
        //短信发送
        for (Schedule sc:list
             ) {
            Map<String, Object> sms1=new HashMap<>();
            sms1.put("trainNo", sc.getTrainNo());
            sms1.put("statrTime",DateUtil.format(sc.getStartTime(), "yyyy年M月d日 HH:mm"));
            sms1.put("stationName", sc.getStartStation());
            sms1.put("signName", "车站通");
            List<Long> ids = new ArrayList<>();
            ids.add(sc.getUserId());
            FindUserInfoListDTO findUserInfoListDTO= FindUserInfoListDTO.builder().userType(30).idlist(ids).build();
            List<UserInfoVO> userInfoList = gusQueryRemote.findUserInfoList(findUserInfoListDTO).getData();
            String phone=userInfoList.get(0).getMobile();
            if(StringUtil.isBlank(redisService.get("CztMsmBeforeTwoHours"+phone+sc.getId()))){
                try {
                    AliSMSUtil.sendSingleSMS(sms1, msMtype, phone);
                    redisService.set("CztMsmBeforeTwoHours"+phone+sc.getId(),phone,72000L);
                } catch (ClientException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //微信公众号推送
        //根据批量的userId来获取批量openId
        List<UserInfoVO> listUserAll = scheduleService.getUserOpenId(list.stream().map(Schedule::getUserId).collect(Collectors.toList()));
        if (null == listUserAll || listUserAll.size() == 0) {
            return;//无数据
        }
        String body = "";
        String touser = "";
        String first = "";
        String keyword1 = "";
        String keyword2 = "";
        String keyword3 = "";
        String keyword4 = "";
        String keyword5 = "";
        String[] strArr;
        for (Schedule item : list) {
            strArr = item.getMgsType().split(",");
            if ("1".equals(strArr[0])) {
                continue;//已经发送过
            }
            List<UserInfoVO> listUser = listUserAll.stream().filter(val -> val.getUserId().equals(item.getUserId())).collect(Collectors.toList());
            if (null == listUser || listUser.size() == 0) {
                continue;//该用户未关注公众号
            }
            touser = listUser.get(0).getOpenId();
            //touser = "oFfVg0zbget9cpKV4vlz6zmTO5To";//*****************本人铁旅畅行openId//从批量里过滤
            first = "您所乘坐的列车预计2小时后出发,请关注目的地天气,做好出行准备";
            keyword1 =item.getStartStation() + "-" + item.getEndStation();
            keyword2 =item.getTrainNo();
            keyword3 =DateUtil.format(item.getStartTime(), "yyyy年M月d日 HH:mm");
            keyword4 =item.getTicketCheck();
            body = this.getBodyTwo(touser, pathGlobal, first, keyword1, keyword2, keyword3, keyword4,remark);
            //发送公众号消息-->订阅了车站通公众号的用户
            String type=appId;
            Map<String, Object> map = vegaStationRemote.SendTemplateNormal(body,type);
            if (!"0".equals(map.get("errcode").toString())) {
                log.error("vegaStationRemote.SendTemplate失败" + map.get("errcode").toString() + "{}", body);
                return;//发送失败,不执行更新
            }
            //发送成功后标记MsgType
            strArr[0] = "1";
            item.setMgsType(StringUtil.join(strArr, ","));
            int intCount = scheduleService.updateMsgTypeById(item);
            if (intCount != 1) {
                log.error("scheduleService.updateMsgTypeById失败{}", item);
            }
        }
    }

    //组装消息对象
    private String getBody(String touser, String pagepath,String first, String keyword1, String keyword2, String keyword3, String keyword4, String keyword5, String remark) {

        String body = "{\n" +
                "    \"touser\": \"" + touser + "\", \n" +
                "    \"template_id\": \"" + templateId + "\", \n" +
                "    \"url\": \"http://weixin.qq.com/download\", \n" +
                "           \"miniprogram\":{\n" +
                "             \"appid\":\"" + appId + "\",\n" +
                "             \"pagepath\":\"" + pagepath + "\"\n" +
                "           }, " +
                "    \"data\": {\n" +
                "        \"first\": {\n" +
                "            \"value\": \"" + first + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword1\": {\n" +
                "            \"value\": \"" + keyword1 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword2\": {\n" +
                "            \"value\": \"" + keyword2 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword3\": {\n" +
                "            \"value\": \"" + keyword3 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword4\": {\n" +
                "            \"value\": \"" + keyword4 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword5\": {\n" +
                "            \"value\": \"" + keyword5 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }," +
                "        \"remark\": {\n" +
                "            \"value\": \"" + remark + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        return body;
    }

    //组装消息对象
    private String getBodyTwo(String touser, String pagepath,String first, String keyword1, String keyword2, String keyword3, String keyword4,String remark) {

        String body = "{\n" +
                "    \"touser\": \"" + touser + "\", \n" +
                "    \"template_id\": \"" + templateId + "\", \n" +
                "    \"url\": \"http://weixin.qq.com/download\", \n" +
                "           \"miniprogram\":{\n" +
                "             \"appid\":\"" + appIdXcx + "\",\n" +
                "             \"pagepath\":\"" + pagepath + "\"\n" +
                "           }, " +
                "    \"data\": {\n" +
                "        \"first\": {\n" +
                "            \"value\": \"" + first + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword1\": {\n" +
                "            \"value\": \"" + keyword1 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword2\": {\n" +
                "            \"value\": \"" + keyword2 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword3\": {\n" +
                "            \"value\": \"" + keyword3 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"keyword4\": {\n" +
                "            \"value\": \"" + keyword4 + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }, \n" +
                "        \"remark\": {\n" +
                "            \"value\": \"" + remark + "\", \n" +
                "            \"color\": \"#173177\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        return body;
    }


    //组装天气
    private String getTheWeather(String startStation, String endStation) {
        Map<String, Object> mapWeather1 = weatherRemote.getWeatherCity(startStation);
        String strReturn = this.getTheWeatherExt(startStation, mapWeather1);//起点站天气

        Map<String, Object> mapWeather2 = weatherRemote.getWeatherCity(endStation);
        String strTemp = this.getTheWeatherExt(endStation, mapWeather2);//终点站天气

        if (!StringUtils.isBlank(strReturn)) {
            strReturn += " - ";//两个站天气连接
        }
        strReturn += strTemp;

        //两个站都没有天气时
        if (StringUtils.isBlank(strReturn)) {
            strReturn = "当前暂无天气信息";
        }

        return strReturn;
    }

    //组装天气-2
    private String getTheWeatherExt(String station, Map<String, Object> mapWeather) {
        String strReturn = "";
        try {
            if ("1".equals(mapWeather.get("state").toString())) {
                Map<String, Object> mapData = (Map<String, Object>) mapWeather.get("data");
                if ("1".equals(mapData.get("status"))) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) mapData.get("lives");
                    strReturn += station + ":" + list.get(0).get("weather");
                }
            }
        } catch (Exception Ex) {
            log.error("ScheduleMsgJob1.getTheWeatherExt获取天气失败!", Ex);
        }

        return strReturn;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值