当前位置: 首页 > 后端技术 > PHP

各语言一个消息聚合推送demo代码示例

时间:2023-03-29 21:01:29 PHP

各语言一个消息聚合推送demo代码示例拼接在url上完成推送。针对body数据量较大的情况,这里给出各语言实现的demo代码。Tips:下面代码中的trigger相当于API文档中的send。trigger在send的基础上增加了高级特性。可以参考:一个消息聚合推送高级特性API任何用户都可以随意选择调用任何一个API,API的使用方式没有区别。PHP语言$head,'body'=>$body));$opts=array('http'=>array('method'=>'POST','header'=>'Content-type:application/json','content'=>$postdata));$context=stream_context_create($opts);$api_url='https://www.phprm.com/services/push/trigger/'.$channel_code;$result=file_get_contents($api_url,false,$context);回声$结果;如果更喜欢使用curl库,可以自己实现或者参考下面开源的第三方库中的curl代码。一些开源的第三方库如果想使用专业的推送库,可以参考这个开源项目。[留言]聚合推送SDK已经提交到Github和Gitee,可以直接通过composer安装SDK:Github:https://github.com/guanguans/notifyGitee:https://gitee.com/guanguans/notify提供了博客系统新注册用户和新评论提醒插件,可以参考插件源码或者直接在自己的网站上使用:WordPress插件:https://github.com/teakong/wordpress-tixing或https://gitee.com/teakong/wordpress-tixingTypecho插件:https://gitee.com/teakong/wordpress-tixing或https://gitee.com/teakong/TypechoTixing其他博客或网站插件:https://github.com/teakong/liuyan-weixin或https://gitee.com/teakong/liuyan-weixinJAVA语言推荐使用Guava自带的限流工具,比如10秒报警防止大量请求消耗你自己的服务器,还是用redis分布式限流比较好,这里也用到了Hutool工具包下的http请求类。Hutool官网文档:https://hutool.cn/docs/#/最新的maven如下cn.hutoolhutool-all5.8.11java报警工具类演示:importcom.alibaba.fastjson2.JSONObject;importcom.google.common.util.concurrent.RateLimiter;importjava.util.HashMap;importjava.util.map;importjava.util.concurrent.TimeUnit;importcn.hutool.http.HttpRequest;importcn.hutool.http.HttpResponse;/***Java系统报警工具类*/publicclassSystemAlarmUtil{privatefinalstaticRateLimiterrateLimiter=RateLimiter.create(1d);私有SystemAlarmUtil(){超级();}publicstaticStringsendAlarmMessage(Stringtitle,Stringmessage){try{//count每次消耗10个token,然后每10秒超时一次等待时间,等待超过1秒后拒绝发送if(!rateLimiter.tryAcquire(10,1,TimeUnit.SECONDS)){返回null;}//创建一个json对象作为requestBodyJSONObjectjsonObject=newJSONObject();jsonObject.put("头部",标题);jsonObject.put("正文",消息);//添加请求头信息Mapheads=newHashMap<>();//使用json发送请求,需要以下内容heads.put("Content-Type","application/json;charset=UTF-8");HttpResponse响应=HttpRequest.post("https://www.phprm.com/services/push/trigger/4d2dac865118761a14d10d7d3afe??7c35").headerMap(heads,false).body(String.valueOf(jsonObject)).timeout(5*1000))。执行();System.out.println("报警推送结果:"+response.body());返回响应体();}catch(Exception异常){}返回null;}publicstaticvoidmain(String[]args){SystemAlarmUtil.sendAlarmMessage("系统故障报警","故障模块:订单模块\n订单ID=xxxx\n订单金额:100元\n故障原因:xxxx");}}由于java生态比较丰富,几乎每个人都有自己实现POST请求的工具,所以没有提供SDKPython语言Pythonlocale使用demo:#coding:utf-8importrequestsimportjson#channelcode/passwordcodechannel_code='4d2dac865118761a14d10d7d3afe??7c35'head='testtitle'body='testcontent'headers={'Content-Type':'application/json'}url='https://www.phprm.com/services/push/send/'+channel_codedata={'head':head,'body':body}res=requests.post(headers=headers,url=url,data=json.dumps(data),timeout=10)print(json.dumps(res))Go语言Golanglocale使用demo:packagemainimport("bytes""encoding/json""fmt""io/ioutil""net/http""unsafe")funcSendMessage()error{channelCode:="4d2dac865118761a14d10d7d3afe??7c35"message1:=make(map[string]interface{})message1["head"]="测试头"message1["body"]="测试内容"bytesData,err:=json.Marshal(message1)iferr!=nil{fmt.Println(err.Error())returnnil}reader:=bytes.NewReader(bytesData)url:=fmt.Sprintf("https://www.phprm.com/services/push/send/%s",channelCode)请求,err:=http.NewRequest("POST",url,reader)iferr!=nil{fmt.Println(err.Error())返回nil}request.Header.Set("Content-Type","application/json;charset=UTF-8")client:=http.Client{}resp,err:=client.Do(request)iferr!=nil{fmt.Println(err.Error())returnnil}respBytes,err:=ioutil.ReadAll(resp.Body)iferr!=nil{fmt.Println(err.Error())returnnil}str:=(*string)(unsafe.Pointer(&respBytes))fmt.Println(*str)returnnil}funcmain(){SendMessage()}C#作者没有安装C#到runEnvironment所以这里只提供GET请求,不过相信熟悉C#的同学写POSTapplication/json请求并不困难//获取请求字符串url="https://www.phprm.com/services/push/send/4d2dac865118761a14d10d7d3afe??7c35?head="+HttpUtility.UrlEncode("测试标题")+"&body="+HttpUtility.UrlEncode("测试内容"+DateTime.Now);varresponse=awaithttpClient.GetAsync(url);stringres=awaitresponse.Content.ReadAsStringAsync();Console.WriteLine("推送状态:"+response.StatusCode);Console.WriteLine(res);其他语言请期待参考:https://www.phprm.com/push/h5/http://push.phprm.com/doc/#/p/demo一个消息推送工具API文档行的代码实现微信消息推送、一条消息、聚合推送、高级功能API