1. 程式人生 > >訊息推送,定時任務

訊息推送,定時任務

package com.idorabox.manage.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller
; import com.alibaba.fastjson.JSON; import com.google.gson.Gson; import com.idorabox.entity.JdToken; import com.idorabox.entity.MallProductCare; import com.idorabox.entity.Notice; import com.idorabox.entity.SuUser; import com.idorabox.manage.entity.jd.GetNewStockByIdEntity; import com.idorabox.manage
.jpush.DolaGouJPushUtil; import com.idorabox.manage.jpush.JPushConstantUtil; import com.idorabox.manage.service.jd.JdTokenService; import com.idorabox.manage.service.mall.MallProductCareService; import com.idorabox.manage.service.su.SuUserService; import com.idorabox.manage.service.sys.NoticeSrvice;
import com.idorabox.manage.web.util.HttpUtils; /** * 京東到貨通知 * @author chen * */ @Controller public class JdDaoHuoNotice { @Resource MallProductCareService mallProductCareService; @Resource JdTokenService jdTokenService; @Resource NoticeSrvice noticeSrvice; @Resource SuUserService userService; /** * 早上8:00的任務,京東到貨通知推送 */ @Scheduled(cron="0 0 8 * * ?") public void toGetJdImgs(){ String addressId = null; Long sku = null; Long userId = null; Long productId = null; String token = null; List skuNums = null; Map<String,Object> jpush=new HashMap<String,Object>(); jpush.put("type", JPushConstantUtil.DH_MSG); MallProductCare address = new MallProductCare(); //查詢京東token Notice notice=new Notice(); Date date = new Date(); List<JdToken> tokenList = jdTokenService.queryList(); if(tokenList != null){ token = tokenList.get(0).getToken(); } //查詢關心列表 List <MallProductCare> careList = mallProductCareService.selectProductCareList(); if(careList != null){ for(MallProductCare care:careList){ sku = care.getSku(); userId = care.getUserId(); productId = care.getProductId(); addressId = care.getAddressId(); if(addressId != null){ Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("skuId", sku); map1.put("num", 1); skuNums = new ArrayList(); skuNums.add(map1); if(token != null){ Map<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("skuNums",JSON.toJSON(skuNums).toString());//轉化為json資料 params.put("area",addressId); //呼叫京東介面,獲取json資料。有的介面直接返回正確的json資料,就不用再處理。 //反正就要對資料進行處理,得到正確的json資料。 String jsonStr = HttpUtils.sendPost(GetNewStockByIdEntity.jd_url, params); String str = jsonStr.replace("\\", "").replace(":\"[{", ":[{").replace("}]\"}", "}]}"); //通過gson將json字串轉物件,進行序列化 Gson g = new Gson(); GetNewStockByIdEntity pd = g.fromJson(str, GetNewStockByIdEntity.class); if(pd != null){ if(pd.isSuccess()){ String stockStateId = pd.getResult().get(0).getStockStateId(); //33 有貨 現貨-下單立即發貨,39 有貨 在途-正在內部配貨,預計2~6天到達本倉庫 //40 有貨 可配貨-下單後從有貨倉庫配貨,36 預訂,34 無貨 if(stockStateId == "33" || "33".equals(stockStateId)){//說明有貨 notice.setProductId(productId); notice.setPushType((byte)3);//有貨推送 notice.setNoticeTypeId(1l);//不需要首頁彈框 notice.setUserId(userId); notice.setCreateDateTime(date); notice.setUpdateTime(date); notice.setStatus((byte)0); notice.setInvalid(false); noticeSrvice.insertSelective(notice); //將推送時間新增進去 address.setId(care.getId()); address.setUpdateTime(date); address.setNoticeTime(date); mallProductCareService.updateByPrimaryKeySelective(address); SuUser user = userService.selectByPrimaryKey(userId); DolaGouJPushUtil.SendPush_To_One(user.getRegId(),userId.toString(),"朵拉購",jpush); } } } } } } } } }

GetNewStockByIdEntity的實體類,可以通過工具生成:

package com.idorabox.manage.entity.jd;

import java.util.List;

/**
 * 查詢庫存
 * @author Administrator
 *
 */
public class GetNewStockByIdEntity {
    public static String jd_url = "https://bizapi.jd.com/api/stock/getNewStockById";
    private boolean success;
    private String resultMessage;
    private String resultCode;
    private List<ResultBeanX> result;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getResultMessage() {
        return resultMessage;
    }

    public void setResultMessage(String resultMessage) {
        this.resultMessage = resultMessage;
    }

    public String getResultCode() {
        return resultCode;
    }

    public List<ResultBeanX> getResult() {
        return result;
    }

    public void setResult(List<ResultBeanX> result) {
        this.result = result;
    }

    public void setResultCode(String resultCode) {
        this.resultCode = resultCode;
    }
    public static class ResultBeanX {
        /**
         * id : 1785319316
         * result : {"price":"","skuId":723749,"jdPrice":""}
         * time : 2017-06-30 01:02:20
         * type : 2
         */

        private Long skuId;
        private String areaId;
        private String stockStateId;
        private String stockStateDesc;
        private String remainNum;
        public Long getSkuId() {
            return skuId;
        }
        public void setSkuId(Long skuId) {
            this.skuId = skuId;
        }
        public String getAreaId() {
            return areaId;
        }
        public void setAreaId(String areaId) {
            this.areaId = areaId;
        }
        public String getStockStateId() {
            return stockStateId;
        }
        public void setStockStateId(String stockStateId) {
            this.stockStateId = stockStateId;
        }
        public String getStockStateDesc() {
            return stockStateDesc;
        }
        public void setStockStateDesc(String stockStateDesc) {
            this.stockStateDesc = stockStateDesc;
        }
        public String getRemainNum() {
            return remainNum;
        }
        public void setRemainNum(String remainNum) {
            this.remainNum = remainNum;
        }


    }

}

JPushConstantUtil 實體類,作為推送的標誌


package com.idorabox.manage.jpush;


/**
 * 
    * @ClassName: JPushConstantUtil
    * @Description: 極光推送常量類
    * @author qinzz
    * @date 2016年9月23日 
    * @time 下午1:29:57
 */
public class JPushConstantUtil {

    /**
     * 朵拉購APP_KEY
     */
    public static final String APP_KEY_BUSINESS="77857a3190fca8f9af0f735b";
    /**
     * 朵拉購 master_key
     */
    public static final String MASTER_SECRET_BUSINESS="ebfa8ca1913e2f3ca7eefc7a";

    /**
     * 訂單訊息推送
     */
    public static final String ORDER_MSG="1";

    /**
     * 回購訊息推送
     */
    public static final String BACK_MSG="2";

    /**
     * 一般訊息推送
     */
    public static final String MSG="3";

    /**
     * 產品詳情 推送  (推送此型別的訊息,附帶productId)
     */
    public static final String PRODUCT_MSG="4";

    /**
     * 商品url詳情 推送
     */
    public static final String URL_MSG="5";
    /**
     * 紅包快過期推送
     */
    public static final String REDPACKET_MSG="6";
    /**
     * 到貨提醒推送
     */
    public static final String DH_MSG="7";

}

推送類:

package com.idorabox.manage.jpush;

import java.util.Map;


import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

public class DolaGouJPushUtil {         
    /**
     * 
        * @Title: SendPush_To_One
        * @Description: 朵拉購推送給單個使用者
        * @param masterKey
        * @param appKey
        * @param registrationId  使用者的reg_id
        * @param content  推送內容
        * @param title   推送的標題
        * @param alert   顯示的內容
        * void   返回型別
        * @throws
     */
    public static void SendPush_To_One(String registrationId,String alert, String title,Map map){
//      JPushClient jpushClient = new JPushClient(JPushConstantUtil.MASTER_SECRET_BUSINESS,
//              JPushConstantUtil.APP_KEY_BUSINESS);
        //使用單例模式創建極光推送客戶端
        JPushClient jpushClient=SingletonJPushClient.getJpushClient();
        try {
            PushPayload paylosd=PushPayload.newBuilder()
                    .setPlatform(Platform.android_ios())//設定接受的平臺
                    .setAudience(Audience.registrationId(registrationId))//推送給單個使用者
                    .setNotification(Notification.newBuilder()
                        .setAlert(alert)
                        .addPlatformNotification(AndroidNotification.newBuilder()
                        .setTitle(title)//推送給安卓端的標題                     
                        .addExtras(map).build())
                        .addPlatformNotification(IosNotification.newBuilder()
                        .incrBadge(1)
                        .setBadge(0)
                        .addExtras(map).build())
                        .build())
                        .setOptions(Options.newBuilder()
                                .setApnsProduction(true)
                                .build())
                    .build();//ApnsProduction:true:正式環境,false:測試環境
             PushResult result = jpushClient.sendPush(paylosd);
             if(result!=null){
              System.out.println("result......"+result);
              System.out.println("推送成功!!!!!!");
           }
           else{
            System.out.println("result is null..........");
           }

        } catch (APIConnectionException e) {
            System.out.println("Connection error. Should retry later");
            e.printStackTrace();

        } catch (APIRequestException e) {
            System.out.println("Error response from JPush server. Should review and fix it.");
            e.printStackTrace();
        } finally {
            System.out.println("推送已經推出");
        }

    }   

}