如何用java實現(xiàn)觸發(fā)短信提醒?這個是很多利用短信接口要實現(xiàn)的一個功能,如一個監(jiān)控項目,其中當達到警告要求就要發(fā)送短信提醒,下面就介紹下具體的實現(xiàn)步驟,和接入的時部分代碼供大家參考:
首先需要注冊動力思維樂信短信接口平臺賬號,注冊地址:http://www.iium.cn/acc/x5?i=110792
其次,完善該賬戶企業(yè)信息,申請sdk接口試用。
第三,就是下載樂信短信接口的API文檔和對應(yīng)語言的demo示例,然后進行對接。
最后,就是進行測試。
下面是有關(guān)短信接口接入的部分代碼示例,供大家參考。
1、通過定時任務(wù)對要監(jiān)控的項目進行定時掃描通知
package com.jeeplus.modules.jk.service; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import me.chanjar.weixin.cp.bean.WxCpMessage.Textcard; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.jeeplus.common.utils.IdGen; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.modules.jk.dao.JkListMapper; import com.jeeplus.modules.jk.dao.JkNoticeLogMapper; import com.jeeplus.modules.jk.entity.JkList; import com.jeeplus.modules.jk.entity.JkNoticeLog; @Service @Lazy(false) public class DlswScanService { @Autowired private JkListMapper jkListMapper; @Autowired private JkNoticeLogMapper jkNoticeLogMapper; private final static Logger LOGGER=Logger.getLogger(DlswScanService.class); @Scheduled(cron = "0/3 * * * * ?") public void scan(){ //查詢所有可用的監(jiān)控項目 List<JkList> jkList=jkListMapper.selectByExample(null); for(JkList jkItem:jkList){ DlswJkInterface djsDlswJkInterface=SpringContextHolder.getBean(jkItem.getFclassname()); LOGGER.info("scan:"+jkItem.getFname()+" begin"); if(djsDlswJkInterface==null){//如果得不到實例 LOGGER.info("scan:"+jkItem.getFname()+" can't getInstance"); continue; } if(!djsDlswJkInterface.hasFinish(jkItem)){//如果上次未完成 LOGGER.info("scan:"+jkItem.getFname()+" didn't finish"); continue; } JkList jkList2=new JkList(); jkList2.setFid(jkItem.getFid()); String scanResult=null; //需要掃描的項目 if(djsDlswJkInterface.needScan(jkItem)){ LOGGER.info("scan:"+jkItem.getFname()+" scanBegin"); scanResult=djsDlswJkInterface.scan(jkItem); jkList2.setFlastScanTime(new Date()); LOGGER.info("scan:"+jkItem.getFname()+" scan fisnish :"+scanResult); } //需要通知 if(djsDlswJkInterface.needNotice(jkItem, scanResult)){ String noticeResult=sendNotice(jkItem, scanResult);//發(fā)送短信通知 LOGGER.info("scan:"+jkItem.getFname()+" sendNotice fisnish:"+noticeResult); jkList2.setFlastnottime(new Date()); saveNoticeLog(jkItem,noticeResult,scanResult);//保存通知日志 } jkListMapper.updateByPrimaryKeySelective(jkList2); LOGGER.info("scan:"+jkItem.getFname()+" end"); } } //保存通知日志 private void saveNoticeLog(JkList jkItem, String noticeResult, String scanResult) { JkNoticeLog jkNoticeLog = new JkNoticeLog(); jkNoticeLog.setFid(IdGen.uuid()); jkNoticeLog.setFlistId(jkItem.getFid()); jkNoticeLog.setFnoticeContent(scanResult); jkNoticeLog.setFnoticeDate(new Date()); jkNoticeLog.setFnoticeResult(noticeResult!=null?"0":"1"); jkNoticeLog.setFnoticeMsg(noticeResult); jkNoticeLog.setFnoticeUser(jkItem.getFnoticeRole()); jkNoticeLog.setFnoticeType(jkItem.getFnoticeType()); jkNoticeLogMapper.insert(jkNoticeLog); } 調(diào)用第三方接口發(fā)送短信通知 /** * 調(diào)用第三方接口發(fā)送短信通知 * @param accName 第三方接口用戶名 * @param accPwd 第三方接口密碼 * @param seed 當前時間 格式:YYYYMMDD HHMISS 例如:20130806102030 * @param aimcodes 手機號多個手機號之間英文半角逗號隔開 * @param content 內(nèi)容后加簽名 * @param schTime 定時時間格式如:2010-01-01 08:00:00 * @return 服務(wù)端返回的結(jié)果 ok:業(yè)務(wù)id 或者 錯誤代碼 */ private String sendNotice(JkList jkItem,String scanResult,String accName,String accPwd,String schTime){ StringBuffer sb = new StringBuffer("https://sdk.lx198.com/sdk/send2?"); try { //獲得要通知角色的電話號碼 String role=jkItem.getFnoticeRole(); List<User> user = userDao.findByRoleCode(role); accName = user.getAccMob(); String roles=jkItem.getFnoticeRole(); String[] roleArr=roles.split(","); Set<User> userSet=new HashSet<User>(); for(String role:roleArr){ userSet.addAll(userDao.findByRoleCode(role)); } StringBuffer sb=new StringBuffer(); for(User user:userSet){ sb.append(user.getAccMob()).append(","); } String seed=new SimpleDateFormat(dateFormatStr).format(new Date()); sb.append("&accName="+accName); sb.append("&seed="+seed); sb.append("&accPwd="+MD5.getMd5String(MD5.getMd5String(accPwd)+seed)); sb.append("&aimcodes="+sb.toString()); sb.append("&schTime="+URLEncoder.encode(schTime,"UTF-8")); //空格標點符號做encode轉(zhuǎn)換 sb.append("&content="+URLEncoder.encode(scanResult,"UTF-8")); //中文做encode轉(zhuǎn)換 URL url = new URL(sb.toString()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); return in.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } }
2、具體監(jiān)控類實現(xiàn)代碼如下
/**實現(xiàn)類代碼如下:
*這是對通道一定時間內(nèi)數(shù)據(jù)數(shù)的監(jiān)控
*在特定時間內(nèi)超過特定值達到次數(shù)要求就會觸發(fā)發(fā)送短信通知
*
*/
package com.jeeplus.modules.jk.service.imp; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jeeplus.modules.jk.dao.SmsQueueMapper; import com.jeeplus.modules.jk.entity.JkList; import com.jeeplus.modules.jk.service.DlswJkAbstractImp; import com.jeeplus.modules.jk.service.DlswJkInterface; import com.jeeplus.modules.jk.service.DlswJkSysConfService; @Service public class DlswJkRealTimeQueueImp extends DlswJkAbstractImp implements DlswJkInterface { private static HashMap<String,Integer> gchHashMap=new HashMap<String, Integer>(); private static HashMap<String,Long> gchHashLastTimeMap=new HashMap<String,Long>(); @Autowired private DlswJkSysConfService dlswJkSysConfService; @Autowired private SmsQueueMapper smsQueueMapper; /** * 即時隊列通道數(shù)據(jù)掃描 * @param jkItem 監(jiān)控項目 */ @Override public String scan(JkList jkItem) { String scanResult=null; StringBuffer sbf = new StringBuffer(); List<HashMap<String, Object>> slist =smsQueueMapper.selectByExample2();//有效通道 即時隊列數(shù)集合 //查詢 int Confvalue = dlswJkSysConfService.getSysConf1("RQ_COUNT"); int redCount = dlswJkSysConfService.getSysConf1("RED_COUNT"); for (HashMap<String, Object> statusMap : slist) { int recordCount = gchHashMap.get(String.valueOf(statusMap.get("GCHID"))==null?0:Integer.parseInt(String.valueOf(statusMap.get("GCHID")))); if(Integer.parseInt(statusMap.get("QUEUECOUNT").toString())>=Confvalue){ if(!gchHashLastTimeMap.containsKey(String.valueOf(statusMap.get("GCHID")))){ gchHashLastTimeMap.put(String.valueOf(statusMap.get("GCHID")), System.currentTimeMillis()); } recordCount++; gchHashMap.put(String.valueOf(statusMap.get("GCHID")),recordCount); }else{ recordCount = 0; gchHashLastTimeMap.remove(String.valueOf(statusMap.get("GCHID"))); gchHashMap.put(String.valueOf(statusMap.get("GCHID")),recordCount); continue; } if(recordCount>=redCount&&(System.currentTimeMillis()-gchHashLastTimeMap.get(String.valueOf(statusMap.get("GCHID"))))>60*1000){ //觸發(fā)通知,發(fā)送短信 scanResult= statusMap.get("GCHNAME")+"通道,1分鐘內(nèi)即時隊列數(shù)據(jù)無變化,請關(guān)注處理##"; sbf.append(scanResult); } } return sbf.toString(); } }
3、短信接口
package com.jeeplus.modules.jk.service; import org.springframework.stereotype.Service; import com.jeeplus.modules.jk.entity.JkList; @Service public interface DlswJkInterface { /** * 判斷上次掃描是否結(jié)束 * @param lock * @param jkItem * @return */ public boolean hasFinish(JkList jkItem); /** * 結(jié)束掃描 * @param lock * @param jkItem */ public void finishItem(JkList jkItem); /** * 是否需要掃描 * @param jkItem 監(jiān)控項目 * @return true 為需要 */ public boolean needScan(JkList jkItem); /** * 是否需要通知 * @param jkItem * @return */ public boolean needNotice(JkList jkItem,String scanResult); /** * 掃描 * @param jkItem * @return 如果不需要通知返回null 否則返回通知內(nèi)容 */ public String scan(JkList jkItem); } // 判斷是否需要掃描或通知 package com.jeeplus.modules.jk.service; import java.util.Date; import java.util.concurrent.locks.ReentrantLock; import com.jeeplus.modules.jk.entity.JkList; import com.jeeplus.modules.jk.utils.NoticeUtil; public abstract class DlswJkAbstractImp implements DlswJkInterface{ protected ReentrantLock lock=new ReentrantLock(); public boolean hasFinish(JkList jkItem){ return lock.tryLock(); } public void finishItem(JkList jkItem){ lock.unlock(); } /** * 是否需要掃描 默認實現(xiàn)為掃描間隔達到上次掃描時間后 * @param jkItem 監(jiān)控項目 * @return true 為需要 */ public boolean needScan(JkList jkItem){ return System.currentTimeMillis()-jkItem.getFlastScanTime().getTime()>jkItem.getFcron().doubleValue()*1000; } /** * 是否需要通知 默認實現(xiàn)為達到通知間隔,且掃描結(jié)果為需要通知,通知時間符合當前時間 * @param jkItem * @return */ public boolean needNotice(JkList jkItem,String scanResult){ return scanResult!=null&&System.currentTimeMillis()-jkItem.getFlastnottime().getTime()>jkItem.getFtzjg().doubleValue()*1000&&NoticeUtil.isNoticeTime(new Date(),jkItem); } }
4、//只列舉jklist類的屬性,get,set方法以及構(gòu)造函數(shù)就不放了,可以根據(jù)自己業(yè)務(wù)需要設(shè)置類
package com.jeeplus.modules.jk.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class JkList implements Serializable { private String fid; private String fname;//監(jiān)控名稱 private BigDecimal fcron;//監(jiān)控頻率 private BigDecimal ftzjg;//通知間隔時間 private String fnoticeRole;// 通知角色 private String ftitle;//標題 private String fnoticeType;//通知類型 private String fnoticeTime;//通知時間 private String fclassname;//監(jiān)控實現(xiàn)類 private Date flastnottime;//最后通知時間 private String fcreateuser; private Date fcreatedate; private BigDecimal forder; private Date flastScanTime;