JAVA实现多线程处理批量发送短信、APP推送
/**
* 推送消息 APP、短信
* @param message
* @throws Exception
*/
public void sendMsg(Message message) throws Exception{
try {
logger.info("send message start...");
long startTime = System.currentTimeMillis();
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(20000);
ThreadPoolExecutor executors = new ThreadPoolExecutor(5, 6, 60000, TimeUnit.SECONDS, queue); //要推送的用户总数
int count = filterPhonesCount(message);
logger.info("message all count=>{}",count);
//初始每个线程处理的用户数量
final int eveLength = 2000;
//计算处理所有用户需要的线程数量
int eveBlocks = count / eveLength + (count % eveLength != 0 ? 1 : 0);
logger.info("need thread's count=>{}",eveBlocks);
//线程计数器
CountDownLatch doneSignal = new CountDownLatch(eveBlocks); //开启线程处理
int doneCount = 0;
for (int page = 0; page < eveBlocks; page++) { /* blocks太大可以再细分重新调度 */
MessageSendThread ms = new MessageSendThread(messageDao,message,page + 1,eveLength,doneSignal);
executors.execute(ms);
//logger.info("start thread =>{}",page+1);
doneCount++;
}
doneSignal.await();//等待所有计数器线程执行完
long endTime = System.currentTimeMillis();
logger.info("send message all thread ends!time(s)=>{}",(startTime-endTime)/1000);
logger.info("all thread count=>{}",doneCount);
} catch (Exception e) {
logger.error("send message error=>{}",e);
}
}
package com.bankhui.center.business.service.message; import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.cookie.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import com.bankhui.center.business.dao.message.MessageDao;
import com.bankhui.center.business.entity.message.Message;
import com.bankhui.center.common.utils.DateUtil;
import com.bankhui.center.common.utils.SmsUtils;
import com.bankhui.center.jpush.JPushClient;
import com.bankhui.center.jpush.JPushScheduleClient; /**
* 系统消息推送线程(处理 block数据块)
*/
public class MessageSendThread implements Runnable{ private final Logger logger = LoggerFactory.getLogger(MessageSendThread.class); private Integer currentIndex;//当前索引
private Integer rows;//处理数据条数
private CountDownLatch doneSignal;//处理线程条数
private Message message;//消息实体
private MessageDao messageDao;//DAO public MessageSendThread(MessageDao messageDao,Message message,Integer currentIndex,Integer rows, CountDownLatch doneSignal) {
this.message = message;
this.messageDao = messageDao;
this.currentIndex = currentIndex;
this.rows = rows;
this.doneSignal = doneSignal;
} @Override
public void run() {
try {
/**
* ---------1.查询当前的block范围内的发送的手机号=>筛选目标客户群手机号---------
*/
Map<String,Object> smsDataMap = filterPhones(message,currentIndex,rows);
if(MapUtils.isEmpty(smsDataMap)|| null == smsDataMap.get("jgAlias")
||StringUtils.isBlank(smsDataMap.get("jgAlias").toString())){
logger.debug("push param is null,caurse by target customers is nothing");
throw new RuntimeException();
}
logger.info("type of target customers=>{}", message.getReceiverGroupType());
logger.info(" result of filter target customers=>{}", smsDataMap); /**
* ---------2.批量发送消息---------
* TODO://((-?)\d{1,11}\,?){1,n} n个线程分批发送
*/
if("0".equals(message.getType())){//短信发送
sendBatch(smsDataMap.get("phone").toString(),message);
}
if("1".equals(message.getType())){//APP推送
if("0".equals(message.getMethod())){//实时发送
sendNormal(smsDataMap);
}
if("1".equals(message.getMethod())){//定时发送
sendDelay(smsDataMap);
}
}
} catch (Exception e) {
logger.error("send message thread exception=>{}{}{}{}",message,currentIndex,rows,e);
}finally{
doneSignal.countDown();//工人完成工作,计数器减一
}
} /**
* APP实时推送
* @param smsDataMap
*/
private void sendNormal(Map<String,Object> smsDataMap) {
//0为全部发送
if("0".equals(message.getReceiverGroupType())){
JPushClient.appSendAll(message.getTitle(), message.getContent(), message.getId().toString(), StringUtils.isBlank(message.getLink())?"0":"1", message.getLink());
}else{
String[] jgAlias = smsDataMap.get("jgAlias").toString().split(",");
for(String jgAlia:jgAlias){
JPushClient.appSend(message.getTitle(), message.getContent(), jgAlia, message.getId().toString(), StringUtils.isBlank(message.getLink())?"0":"1", message.getLink());
}
}
} /**
* APP定时推送
* @param smsDataMap
*/
private void sendDelay(Map<String,Object> smsDataMap) {
//0为全部发送
if("0".equals(message.getReceiverGroupType())){
JPushScheduleClient.createSingleSchedule(
DateUtil.formatDateToStr("yyyy-MM-dd HH:mm:ss", message.getExpectTime()),
message.getTitle(),
message.getContent(),
message.getId().toString(),
StringUtils.isBlank(message.getLink())?"0":"1",
message.getLink());
}else{
String[] jgAlias = smsDataMap.get("jgAlias").toString().split(",");
JPushScheduleClient.createSingleSchedule(
Arrays.asList(jgAlias),
DateUtil.formatDateToStr("yyyy-MM-dd HH:mm:ss", message.getExpectTime()),
message.getTitle(),
message.getContent(),
message.getId().toString(),
StringUtils.isBlank(message.getLink())?"0":"1",
message.getLink());
}
} /**
* 批量发送消息
* @param smsDataList
* @param message
*/
private void sendBatch(String smsDataListStr,Message message){
try {
//批量发送方法使用异步发送
if(!message.getContent().contains("退订回T")){
message.setContent(message.getContent()+"退订回T");
}
SmsUtils.batchExecuteTask(smsDataListStr, message.getContent());
//短信测试方法
//SmsUtils.batchExecuteTask(smsDataListStr, message.getContent(),true);
} catch (Exception e) {
e.printStackTrace();
logger.error("批量发送消息异常=>{}{}",smsDataListStr,e);
}
} }
/**
* 批量发送消息
* @param smsDataList
* @param message
*/
private void sendBatch(String smsDataListStr,Message message){
try {
//批量发送方法使用异步发送
if(!message.getContent().contains("退订回T")){
message.setContent(message.getContent()+"退订回T");
}
SmsUtils.batchExecuteTask(smsDataListStr, message.getContent());
//短信测试方法
//SmsUtils.batchExecuteTask(smsDataListStr, message.getContent(),true);
} catch (Exception e) {
e.printStackTrace();
logger.error("批量发送消息异常=>{}{}",smsDataListStr,e);
}
}
public static String sendSmsCL(String mobile, String content,String urlStr,String un, String pw, String rd) {
// 创建StringBuffer对象用来操作字符串
StringBuffer sb = new StringBuffer(urlStr+"?");
// 用户账号
sb.append("un="+un); //用户密码
sb.append("&pw="+pw); // 是否需要状态报告,0表示不需要,1表示需要
sb.append("&rd="+rd); // 向StringBuffer追加手机号码
sb.append("&phone="+mobile); // 返回发送结果
String inputline;
BufferedReader in = null;
InputStreamReader isr = null;
try {
// 向StringBuffer追加消息内容转URL标准码
sb.append("&msg="+URLEncoder.encode(content,"UTF8"));
// 创建url对象
URL url = new URL(sb.toString()); // 打开url连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置url请求方式 ‘get’ 或者 ‘post’
connection.setRequestMethod("POST");
isr = new InputStreamReader(url.openStream());
// 发送
in = new BufferedReader(isr);
inputline = in.readLine();
if(inputline.contains(",0")){
logger.info("手机号:【{}】发送短信成功", mobile);
}else{
logger.info("手机号:【{}】发送短信失败,errorMsg is:{}", mobile,inputline);
}
// 输出结果
return inputline;
} catch (Exception e) {
logger.error("发送短信请求异常:{}", e.getMessage());
return e.getMessage();
} finally{
if(null != isr){
try {
isr.close();
} catch (IOException e) {
logger.error("关闭流异常:{}", e.getMessage());
}
}
if(null != in){
try {
in.close();
} catch (IOException e) {
logger.error("关闭流异常:{}", e.getMessage());
}
}
} }
package com.bankhui.center.jpush; import java.util.HashMap;
import java.util.Map; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* The entrance of JPush API library.
*
*/
public class JPushClient extends BaseClient {
private static Logger logger = LoggerFactory.getLogger(JPushClient.class);
//在极光注册上传应用的 appKey 和 masterSecret
private static final String appKeyStr ="******************";////必填, private static final String masterSecretStr = "******************";//必填,每个应用都对应一个masterSecret private static JPushClient jpush = null; /*
* 保存离线的时长。秒为单位。最多支持10天(864000秒)。
* 0 表示该消息不保存离线。即:用户在线马上发出,当前不在线用户将不会收到此消息。
* 此参数不设置则表示默认,默认为保存1天的离线消息(86400秒
*/
private static long timeToLive = 60 * 60 * 24; protected static HttpPostClient httpClient = new HttpPostClient(); /**
* 给指定用户推送消息
* @param msgTitle 标题
* @param msgContent 内容
* @param jgAlias 极光通讯id
* @param sysMsgId 系统保存的消息id
* @param type 跳转类型0不带链接跳转,1带链接跳转 2 站内信
* @param url 跳转url
* @author wxz
* @date 2017年2月27日
*/
public static void appSend(String msgTitle,String msgContent,String jgAlias,String sysMsgId,String type,String url) {
try {
Map<String, Object> extra1 =new HashMap<String, Object>();
extra1.put("sysMsgId", sysMsgId);
extra1.put("type", type);//0不带链接跳转,1带链接跳转
extra1.put("url", url);
if(null == jpush){
jpush = new JPushClient(masterSecretStr, appKeyStr, timeToLive);
}
MessageResult msgResult = jpush.sendNotificationWithAlias(getRandomSendNo(), jgAlias, msgTitle, msgContent, 0, extra1); if (null != msgResult) {
logger.info("服务器返回数据: " + msgResult.toString());
if (msgResult.getErrcode() == ErrorCodeEnum.NOERROR.value()) {
logger.info("发送成功, sendNo=" + msgResult.getSendno());
} else {
logger.error("发送失败, 错误代码=" + msgResult.getErrcode() + ", 错误消息=" + msgResult.getErrmsg());
}
} else {
logger.error("无法获取数据");
}
} catch (Exception e) {
logger.error("发送失败,error msg is :"+e);
}
}
/**
* 给所有用户推送消息
* @param msgTitle 标题
* @param msgContent 内容
* @param sysMsgId 消息id
* @param type 跳转类型0不带链接跳转,1带链接跳转
* @param url 跳转url
* @author wxz
* @date 2017年2月27日
*/
public static void appSendAll(String msgTitle,String msgContent,String sysMsgId,String type,String url) {
/*
* IOS设备扩展参数,
* 设置badge,设置声音
*/ Map<String, Object> extra1 =new HashMap<String, Object>();
extra1.put("sysMsgId", sysMsgId);
extra1.put("type", type);//0不带链接跳转,1带链接跳转
extra1.put("url", url);
if(null == jpush){
jpush = new JPushClient(masterSecretStr, appKeyStr, timeToLive);
}
MessageResult msgResult = jpush.sendNotificationWithAppKey(getRandomSendNo(), msgTitle, msgContent, 0, extra1); if (null != msgResult) {
logger.info("服务器返回数据: " + msgResult.toString());
if (msgResult.getErrcode() == ErrorCodeEnum.NOERROR.value()) {
logger.info("发送成功, sendNo=" + msgResult.getSendno());
} else {
logger.error("发送失败, 错误代码=" + msgResult.getErrcode() + ", 错误消息=" + msgResult.getErrmsg());
}
} else {
logger.error("无法获取数据");
} } public JPushClient(String masterSecret, String appKey) {
this.masterSecret = masterSecret;
this.appKey = appKey;
} public JPushClient(String masterSecret, String appKey, long timeToLive) {
this.masterSecret = masterSecret;
this.appKey = appKey;
this.timeToLive = timeToLive;
} public JPushClient(String masterSecret, String appKey, DeviceEnum device) {
this.masterSecret = masterSecret;
this.appKey = appKey;
devices.add(device);
} public JPushClient(String masterSecret, String appKey, long timeToLive, DeviceEnum device) {
this.masterSecret = masterSecret;
this.appKey = appKey;
this.timeToLive = timeToLive;
devices.add(device);
} /*
* @description 发送带IMEI的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithImei(String sendNo, String imei, String msgTitle, String msgContent) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.IMEI);
p.setReceiverValue(imei);
return sendNotification(p, sendNo, msgTitle, msgContent, 0, null);
} /*
* @params builderId通知栏样式
* @description 发送带IMEI的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithImei(String sendNo, String imei, String msgTitle, String msgContent, int builderId, Map<String, Object> extra) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.IMEI);
p.setReceiverValue(imei);
return sendNotification(p, sendNo, msgTitle, msgContent, builderId, extra);
} /*
* @description 发送带IMEI的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithImei(String sendNo, String imei, String msgTitle, String msgContent) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.IMEI);
p.setReceiverValue(imei);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, null, null);
} /*
* @params msgContentType消息的类型,extra附属JSON信息
* @description 发送带IMEI的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithImei(String sendNo, String imei, String msgTitle, String msgContent, String msgContentType, Map<String, Object> extra) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.IMEI);
p.setReceiverValue(imei);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, msgContentType, extra);
} /*
* @description 发送带TAG的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithTag(String sendNo, String tag, String msgTitle, String msgContent) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.TAG);
p.setReceiverValue(tag);
return sendNotification(p, sendNo, msgTitle, msgContent, 0, null);
} /*
* @params builderId通知栏样式
* @description 发送带TAG的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithTag(String sendNo, String tag, String msgTitle, String msgContent, int builderId, Map<String, Object> extra) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.TAG);
p.setReceiverValue(tag);
return sendNotification(p, sendNo, msgTitle, msgContent, builderId, extra);
} /*
* @description 发送带TAG的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithTag(String sendNo, String tag, String msgTitle, String msgContent) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.TAG);
p.setReceiverValue(tag);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, null, null);
} /*
* @params msgContentType消息的类型,extra附属JSON信息
* @description 发送带TAG的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithTag(String sendNo, String tag, String msgTitle, String msgContent, String msgContentType, Map<String, Object> extra) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.TAG);
p.setReceiverValue(tag);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, msgContentType, extra);
} /*
* @description 发送带ALIAS的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithAlias(String sendNo, String alias, String msgTitle, String msgContent) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.ALIAS);
p.setReceiverValue(alias);
return sendNotification(p, sendNo, msgTitle, msgContent, 0, null);
} /*
* @params builderId通知栏样式
* @description 发送带ALIAS的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithAlias(String sendNo, String alias, String msgTitle, String msgContent, int builderId, Map<String, Object> extra) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.ALIAS);
p.setReceiverValue(alias);
return sendNotification(p, sendNo, msgTitle, msgContent, builderId, extra);
} /*
* @description 发送带ALIAS的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithAlias(String sendNo, String alias, String msgTitle, String msgContent) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.ALIAS);
p.setReceiverValue(alias);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, null, null);
} /*
* @params msgContentType消息的类型,extra附属JSON信息
* @description 发送带ALIAS的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithAlias(String sendNo, String alias, String msgTitle, String msgContent, String msgContentType, Map<String, Object> extra) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.ALIAS);
p.setReceiverValue(alias);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, msgContentType, extra);
} /*
* @description 发送带AppKey的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithAppKey(String sendNo, String msgTitle, String msgContent) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.APPKEYS);
return sendNotification(p, sendNo, msgTitle, msgContent, 0, null);
} /*
* @params builderId通知栏样式
* @description 发送带AppKey的通知
* @return MessageResult
*/
public MessageResult sendNotificationWithAppKey(String sendNo, String msgTitle, String msgContent, int builderId, Map<String, Object> extra) {
NotifyMessageParams p = new NotifyMessageParams();
p.setReceiverType(ReceiverTypeEnum.APPKEYS);
return sendNotification(p, sendNo, msgTitle, msgContent, builderId, extra);
} /*
* @description 发送带AppKey的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithAppKey(String sendNo, String msgTitle, String msgContent) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.APPKEYS);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, null, null);
} /*
* @params msgContentType消息的类型,extra附属JSON信息
* @description 发送带AppKey的自定义消息
* @return MessageResult
*/
public MessageResult sendCustomMessageWithAppKey(String sendNo, String msgTitle, String msgContent, String msgContentType, Map<String, Object> extra) {
CustomMessageParams p = new CustomMessageParams();
p.setReceiverType(ReceiverTypeEnum.APPKEYS);
return sendCustomMessage(p, sendNo, msgTitle, msgContent, msgContentType, extra);
} protected MessageResult sendCustomMessage(CustomMessageParams p, String sendNo, String msgTitle, String msgContent, String msgContentType, Map<String, Object> extra) {
if (null != msgContentType) {
p.getMsgContent().setContentType(msgContentType);
}
if (null != extra) {
p.getMsgContent().setExtra(extra);
}
return sendMessage(p, sendNo, msgTitle, msgContent);
} protected MessageResult sendNotification(NotifyMessageParams p, String sendNo, String msgTitle, String msgContent, int builderId, Map<String, Object> extra) {
p.getMsgContent().setBuilderId(builderId);
if (null != extra) {
p.getMsgContent().setExtra(extra);
}
return sendMessage(p, sendNo, msgTitle, msgContent);
} protected MessageResult sendMessage(MessageParams p,String sendNo, String msgTitle, String msgContent) {
p.setSendNo(sendNo);
p.setAppKey(this.getAppKey());
p.setMasterSecret(this.masterSecret);
p.setTimeToLive(this.timeToLive);
p.setSendDescription(this.getSendDescription());
for (DeviceEnum device : this.getDevices()) {
p.addPlatform(device);
} if (null != msgTitle) {
p.getMsgContent().setTitle(msgTitle);
}
p.getMsgContent().setMessage(msgContent); return sendMessage(p);
} protected MessageResult sendMessage(MessageParams params) {
return httpClient.post(BaseURL.ALL_PATH, this.enableSSL, params);
} public static final int MAX = Integer.MAX_VALUE;
public static final int MIN = (int) MAX/2; /**
* 保持 sendNo 的唯一性是有必要的
* It is very important to keep sendNo unique.
* @return sendNo
*/
public static String getRandomSendNo() {
return String.valueOf((int) (MIN + Math.random() * (MAX - MIN)));
}
}
package com.bankhui.center.jpush; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import cn.jpush.api.JPushClient;
import cn.jpush.api.common.TimeUnit;
import cn.jpush.api.common.Week;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
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.schedule.ScheduleListResult;
import cn.jpush.api.schedule.ScheduleResult;
import cn.jpush.api.schedule.model.SchedulePayload;
import cn.jpush.api.schedule.model.TriggerPayload; public class JPushScheduleClient { protected static final Logger LOG = LoggerFactory.getLogger(JPushScheduleClient.class); private static final String appKey ="*********";
private static final String masterSecret = "*******";
/*
* 保存离线的时长。秒为单位。最多支持10天(864000秒)。
* 0 表示该消息不保存离线。即:用户在线马上发出,当前不在线用户将不会收到此消息。
* 此参数不设置则表示默认,默认为保存1天的离线消息(86400秒
*/
private static int timeToLive = 60 * 60 * 24; public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("22");
// testGetScheduleList();
// testUpdateSchedule();
String scheduleId = "***************";
String time = "2017-03-07 09:55:00";
String msgTitle = "push schedule jpush,TEST\"\"";
String msgContent = "测试定时发送";
String sysMsgId = "26";
String type = "1";
String url = "https://www.baidu.com";
//指定接收者的定时发送
scheduleId = createSingleSchedule(list,time,msgTitle,msgContent,sysMsgId,type,url);
//全部用户的定时发送
// scheduleId = createSingleSchedule(time,msgTitle,msgContent,sysMsgId,type,url);
testGetSchedule(scheduleId);
// testDeleteSchedule(scheduleId);
}
/**
* 添加指定接收者定时发送消息的
* @param aliases List<String> 接收者极光id列表
* @param time 定时发送时间(yyyy-MM-dd HH:mm:ss)
* @param msgTitle 标题
* @param msgContent 内容
* @param sysMsgId 系统保存的消息id
* @param type 跳转类型0不带链接跳转,1带链接跳转
* @param url 跳转url
* @return
* @author wxz
* @date 2017年3月7日
*/
public static String createSingleSchedule(List<String> aliases,
String time, String msgTitle, String msgContent,
String sysMsgId, String type, String url) {
if(CollectionUtils.isEmpty(aliases)){
LOG.info("aliases is empty");
return null;
}
JPushClient jpushClient = new JPushClient(masterSecret, appKey, timeToLive);
String name = "schedule_"+time.replaceAll(" ", "").replaceAll(":", "").replaceAll("-", "");
Map<String, String> extra = new HashMap<String, String>();
extra.put("sysMsgId", sysMsgId);
extra.put("type", type);//0不带链接跳转,1带链接跳转
extra.put("url", url); // Message message = new cn.jpush.api.push.model.Message.Builder()
// .setMsgContent(msgContent).addExtras(extra)
// .build();
// Audience audience = new cn.jpush.api.push.model.audience.Audience.Builder().build().alias(aliases);
//初始化android消息通知
cn.jpush.api.push.model.notification.AndroidNotification androidNotification = new cn.jpush.api.push.model.notification.AndroidNotification.Builder().setAlert(msgContent).setTitle(msgTitle).addExtras(extra).build();
//初始化ios消息通知
cn.jpush.api.push.model.notification.IosNotification iosNotification = new cn.jpush.api.push.model.notification.IosNotification.Builder().setAlert(msgContent).addExtras(extra).build();
//初始化消息通知,将android和ios赋值
cn.jpush.api.push.model.notification.Notification notification = new cn.jpush.api.push.model.notification.Notification.Builder()
.addPlatformNotification(androidNotification)
.addPlatformNotification(iosNotification)
.build();
//初始化push
PushPayload push = new cn.jpush.api.push.model.PushPayload.Builder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(aliases))
.setNotification(notification)
.build();
// PushPayload pucsh = PushPayload.alertAll("----test schedule example0000001111111.");
try {
ScheduleResult result = jpushClient.createSingleSchedule(name, time, push);
LOG.info("schedule result is " + result);
return result.getSchedule_id();
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
return null;
}
/**
* 添加所有用户定时发送消息的
* @param time 定时发送时间(yyyy-MM-dd HH:mm:ss)
* @param msgTitle 标题
* @param msgContent 内容
* @param sysMsgId 系统保存的消息id
* @param type 跳转类型0不带链接跳转,1带链接跳转
* @param url 跳转url
* @return
* @author wxz
* @date 2017年3月7日
*/
public static String createSingleSchedule(String time, String msgTitle,
String msgContent, String sysMsgId, String type, String url) {
JPushClient jpushClient = new JPushClient(masterSecret, appKey, timeToLive);
String name = "schedule_"+time.replaceAll(" ", "").replaceAll(":", "").replaceAll("-", "");
Map<String, String> extra = new HashMap<String, String>();
extra.put("sysMsgId", sysMsgId);
extra.put("type", type);//0不带链接跳转,1带链接跳转
extra.put("url", url); // Message message = new cn.jpush.api.push.model.Message.Builder()
// .setMsgContent(msgContent).addExtras(extra)
// .build();
// PushPayload push = new cn.jpush.api.push.model.PushPayload.Builder().setPlatform(Platform.all())
// .setAudience(Audience.all())
// .setMessage(message)
//// .setOptions(new cn.jpush.api.push.model.Options.Builder().setApnsProduction(true).build())
// .build();
//初始化android消息通知
cn.jpush.api.push.model.notification.AndroidNotification androidNotification = new cn.jpush.api.push.model.notification.AndroidNotification.Builder().setAlert(msgContent).setTitle(msgTitle).addExtras(extra).build();
//初始化ios消息通知
cn.jpush.api.push.model.notification.IosNotification iosNotification = new cn.jpush.api.push.model.notification.IosNotification.Builder().setAlert(msgContent).addExtras(extra).build();
//初始化消息通知,将android和ios赋值
cn.jpush.api.push.model.notification.Notification notification = new cn.jpush.api.push.model.notification.Notification.Builder()
.addPlatformNotification(androidNotification)
.addPlatformNotification(iosNotification)
.build();
//初始化push
PushPayload push = new cn.jpush.api.push.model.PushPayload.Builder()
.setPlatform(Platform.all())
.setAudience(Audience.all())
.setNotification(notification)
.build();
// PushPayload push = new cn.jpush.api.push.model.PushPayload.Builder()
// .setPlatform(Platform.all())
// .setAudience(Audience.all())
// .setNotification(new cn.jpush.api.push.model.notification.Notification.Builder().addPlatformNotification(new cn.jpush.api.push.model.notification.AndroidNotification.Builder().setAlert(msgContent).setTitle(msgTitle).addExtras(extra).build())
// .addPlatformNotification(new cn.jpush.api.push.model.notification.IosNotification.Builder().setAlert(msgContent).addExtras(extra).build())
// .build())
// .build();
// PushPayload pucsh = PushPayload.alertAll("----test schedule example0000001111111.");
try {
ScheduleResult result = jpushClient.createSingleSchedule(name, time, push);
LOG.info("schedule result is " + result);
return result.getSchedule_id();
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
return null;
} private static void testCreateDailySchedule() {
JPushClient jPushClient = new JPushClient(masterSecret, appKey);
String name = "test_daily_schedule";
String start = "2015-08-06 12:16:13";
String end = "2115-08-06 12:16:13";
String time = "14:00:00";
PushPayload push = PushPayload.alertAll("test daily example.");
try {
ScheduleResult result = jPushClient.createDailySchedule(name, start, end, time, push);
LOG.info("schedule result is " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
} private static void testCreateWeeklySchedule() {
JPushClient jPushClient = new JPushClient(masterSecret, appKey);
String name = "test_weekly_schedule";
String start = "2015-08-06 12:16:13";
String end = "2115-08-06 12:16:13";
String time = "14:00:00";
Week[] days = {Week.MON, Week.FRI};
PushPayload push = PushPayload.alertAll("test weekly example.");
try {
ScheduleResult result = jPushClient.createWeeklySchedule(name, start, end, time, days, push);
LOG.info("schedule result is " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
} private static void testCreateMonthlySchedule() {
JPushClient jPushClient = new JPushClient(masterSecret, appKey);
String name = "test_monthly_schedule";
String start = "2015-08-06 12:16:13";
String end = "2115-08-06 12:16:13";
String time = "14:00:00";
String[] points = {"01", "02"};
PushPayload push = PushPayload.alertAll("test monthly example.");
try {
ScheduleResult result = jPushClient.createMonthlySchedule(name, start, end, time, points, push);
LOG.info("schedule result is " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later.", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
} private static void testDeleteSchedule(String scheduleId) {
// String scheduleId = "************************8";
JPushClient jpushClient = new JPushClient(masterSecret, appKey); try {
jpushClient.deleteSchedule(scheduleId);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
} private static void testGetScheduleList() {
int page = 1;
JPushClient jpushClient = new JPushClient(masterSecret, appKey); try {
ScheduleListResult list = jpushClient.getScheduleList(page);
LOG.info("total " + list.getTotal_count());
for(ScheduleResult s : list.getSchedules()) {
LOG.info(s.toString());
}
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
} private static void testUpdateSchedule() {
String scheduleId = "*******************";
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
String[] points = {Week.MON.name(), Week.FRI.name()};
TriggerPayload trigger = TriggerPayload.newBuilder()
.setPeriodTime("2015-08-01 12:10:00", "2015-08-30 12:12:12", "15:00:00")
.setTimeFrequency(TimeUnit.WEEK, 2, points)
.buildPeriodical();
SchedulePayload payload = SchedulePayload.newBuilder()
.setName("test_update_schedule")
.setEnabled(false)
.setTrigger(trigger)
.build();
try {
jpushClient.updateSchedule(scheduleId, payload);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
} private static void testGetSchedule(String scheduleId) {
// String scheduleId = "************************";
JPushClient jpushClient = new JPushClient(masterSecret, appKey); try {
ScheduleResult result = jpushClient.getSchedule(scheduleId);
LOG.info("schedule " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
}
} /**
* 组建push,若发送全部,则aliases传null
* @param aliases List<String> 接收者极光id列表
* @param msgTitle 标题
* @param msgContent 内容
* @param sysMsgId 系统保存的消息id
* @param type 跳转类型0不带链接跳转,1带链接跳转
* @param url 跳转url
* @return
* @author wxz
* @date 2017年3月7日
*/
private static PushPayload buildPush(List<String> aliases,String msgTitle, String msgContent,
String sysMsgId, String type, String url) {
Map<String, String> extra = new HashMap<String, String>();
extra.put("sysMsgId", sysMsgId);
extra.put("type", type);//0不带链接跳转,1带链接跳转
extra.put("url", url);
//初始化android消息通知
cn.jpush.api.push.model.notification.AndroidNotification androidNotification = new cn.jpush.api.push.model.notification.AndroidNotification.Builder().setAlert(msgContent).setTitle(msgTitle).addExtras(extra).build();
//初始化ios消息通知
cn.jpush.api.push.model.notification.IosNotification iosNotification = new cn.jpush.api.push.model.notification.IosNotification.Builder().setAlert(msgContent).addExtras(extra).build();
//初始化消息通知,将android和ios赋值
cn.jpush.api.push.model.notification.Notification notification = new cn.jpush.api.push.model.notification.Notification.Builder()
.addPlatformNotification(androidNotification)
.addPlatformNotification(iosNotification)
.build();
//初始化push
PushPayload push = new cn.jpush.api.push.model.PushPayload.Builder()
.setPlatform(Platform.all())
.setAudience(CollectionUtils.isEmpty(aliases)?Audience.all():Audience.alias(aliases))
.setNotification(notification)
.build();
return push;
}
}
JAVA实现多线程处理批量发送短信、APP推送的更多相关文章
- 个人永久性免费-Excel催化剂功能第85波-灵活便捷的批量发送短信功能(使用腾讯云接口)
微信时代的今天,短信一样不可缺席,大系统都有集成短信接口.若只是临时用一下,若能够直接在Excel上加工好内容就可以直接发送,这些假设在此篇批量群发短信功能中都为大家带来完美答案. 业务场景 不多说, ...
- (转)短信vs.推送通知vs.电子邮件:app什么时候该用哪种方式来通知用户?
转:http://www.360doc.com/content/15/0811/00/19476362_490860835.shtml 现在,很多公司都关心的一个问题是:要提高用户互动,到底采取哪一种 ...
- python 阿里云短信群发推送
本篇文章是使用Python的Web框架Django提供发送短信接口供前端调用,Python版本2.7 阿里云入驻.申请短信服务.创建应用和模板等步骤请参考:阿里云短信服务入门 1.下载sdk 阿里云短 ...
- php批量发送短信或邮件的方案
最近遇到在开发中遇到一个场景,后台管理员批量审核用户时候,需要给用户发送审核通过信息,有人可能会想到用foreach循环发送,一般的短信接口都有调用频率,循环发送,肯定会导致部分信息发送失败,有人说用 ...
- Cocos2d-x3.3RC0通过JNI调用Android的Java层URI代码发送短信
1.Jni不在赘述.翻看前面博客 2.直接上代码 1)Java层,直接加在AppActivity.java中 public class AppActivity extends Cocos2dxActi ...
- 发送短信——java
闲来无事研究一下调用第三方接口发送短信的技术 这一次我们使用阿里的短信服务 一.进行平台相关服务的注册和设置 下面请参照阿里的短信服务文档进行设置,只要按照文档步骤来差不多30分钟就能搞定服务注册: ...
- java攻城师之路(Android篇)--搭建开发环境、拨打电话、发送短信、布局例子
一.搭建开发环境 1.所需资源 JDK6以上 Eclipse3.6以上 SDK17, 2.3.3 ADT17 2.安装注意事项 不要使用中文路径 如果模拟器默认路径包含中文, 可以设置android_ ...
- 利用阿里大于实现发送短信(JAVA版)
本文是我自己的亲身实践得来,喜欢的朋 友别忘了点个赞哦! 最近整理了一下利用阿里大于短信平台来实现发送短信功能. 闲话不多说,直接开始吧. 首先,要明白利用大于发送短信这件事是由两部分组成: 一.在阿 ...
- Java调用腾讯云短信接口,完成验证码的发送(不成功你来砍我!!)
一.前言 我们在一些网站注册页面,经常会见到手机验证码的存在,这些验证码一般的小公司都是去买一些大的厂家的短信服务,自己开发对小公司的成本花费太大了!今天小编就带着大家来学习一下腾讯云的短信接口,体验 ...
随机推荐
- 开源的 .Net Core MVC CMS 推荐
简介 ZKEACMS Core 是基于 ZKEACMS 的 Asp.Net Core 版本. 架设环境: .Net Core 跨平台 Microsoft Sql Serverl 2008 或以上 .N ...
- OI网络流 简单学习笔记
持续更新! 基本上只是整理了一下框架,具体的学习给出了个人认为比较好的博客的链接. ..怎么说呢,最基础的模板我就我不说了吧qwq,具体可以参考一下这位大佬写的博客:最大流,最小割,费用流 费用流 跑 ...
- Windows系统下安装 CMake
在安装caffe框架的时候需要用到cmake,特将cmake的安装总结如下: 1 什么是cmake CMake是一个跨平台的编译(Build)工具,可以用简单的语句来描述所有平台的编译过程.CMake ...
- Mysql 索引原理《一》索引原理与慢查询1
为何要有索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,在生产环境中,我们遇到最多的,也是最容易出问题的,还是一些复杂的查询操作,因此对查询语句的优化显然 ...
- jquery之链式调用,层级菜单
一. 链式调用的含义 jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法可以连起来写: $('#div1') // id为div1的元素 .children('ul ...
- ORACLE中的KEEP()使用方法
转载至:http://blog.csdn.net/aqszhuaihuai/article/details/6434160 ====================================== ...
- 题目1018:统计同成绩学生人数(hash简单应用)
问题来源 http://ac.jobdu.com/problem.php?pid=1018 问题描述 给你n位同学的成绩,问获得某一成绩的学生有多少位. 问题分析 初见此题,有人会想到先将所有成绩存入 ...
- python高级(四)—— 文本和字节序列(编码问题)
本文主要内容 字符 字节 结构体和内存视图 字符和字节之间的转换——编解码器 BOM鬼符 标准化Unicode字符串 Unicode文本排序 python高级——目录 文中代码均放在github上: ...
- BT网站-IBMID.COM
最近把網站改版了,主要是更改了搜索引擎. 大家可以訪問 什么是磁力链接(IBMID.COM)(Magnet URI)? 简单的说:类似下面这样以“magnet:?”开头的字符串,就是一条“磁力链接” ...
- 2019年华南理工大学程序设计竞赛(春季赛) K Parco_Love_String(后缀自动机)找两个串的相同字串有多少
https://ac.nowcoder.com/acm/contest/625/K 题意: 给出Q 个询问 i , 求 s[0..i-1] 与 s[i...len-1] 有多少相同的字串 分析: 给出 ...