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调用腾讯云短信接口,完成验证码的发送(不成功你来砍我!!)
一.前言 我们在一些网站注册页面,经常会见到手机验证码的存在,这些验证码一般的小公司都是去买一些大的厂家的短信服务,自己开发对小公司的成本花费太大了!今天小编就带着大家来学习一下腾讯云的短信接口,体验 ...
随机推荐
- 升级实体框架EntityFramework6.0
首先安装nuget 管理器 https://visualstudiogallery.msdn.microsoft.com/4ec1526c-4a8c-4a84-b702-b21a8f5293ca 安装 ...
- python学习之路 六 :装饰器
本节重点: 掌握装饰器相关知识 python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函 ...
- PageAdmin环境配置要求
1.操作系统要求: Win7/win8/win2008/win2012及以上版本都可以,建议用64位的操作系统,服务器建议选择win2012或以上版本. 2.net framework版本要求: ne ...
- 支付机构MRC模
一.电商RFM模型 RFM模型是一个简单的根据客户的活跃程度和交易金额贡献所做的分类.因为操作简单,所以较为常用. 近度R:R代表客户最近的活跃时间距离数据采集点的时间距离,R越大,表示客户越久未发生 ...
- NFS共享服务
一.网络文件系统共享服务 NFS( Network File System,网络文件系统 )是一种基于TCP/IP传输的网络文件系统协议,最初由SUN公司开发,通过使用NFS协议,客户机可以像访问本地 ...
- 针对myeclipse6.5无法自动生成toString方法
public void getToStringSTR(){ Field[] fs = this.getClass().getDeclaredFields(); for (int i = 0; i &l ...
- C#-函数的传值与传址
传值就是将实参的值传到所调用的函数里面,实参的值并没有发生变化,默认传值的有int型,浮点型,bool型,char字符型,结构体等等. 传址就是将地址传到所调用的函数里面操作,实参的值也会跟着变化,传 ...
- js 常用js正则表达式大全
一.校验数字的js正则表达式 1 数字:^[0-9]*$ 2 n位的数字:^d{n}$ 3 至少n位的数字:^d{n,}$ 4 m-n位的数字:^d{m,n}$ 5 ...
- Java非静态代码块和静态代码块
类中存在两种特殊的代码块,即非静态代码块和静态代码块,前者是直接由 { } 括起来的代码,而后者是由 static{ } 括起来的代码. 非静态代码块在类初始化创建实例时,将会被提取到类的构造器中执行 ...
- 「BZOJ3998」[TJOI2015] 弦论(第K小子串)
https://www.lydsy.com/JudgeOnline/problem.php?id=3998 Description 对于一个给定长度为N的字符串,求它的第K小子串是什么. Input ...