首先是使用IntelliJ IDEA建立一個SpringBoot的工程,具體怎麼建立能夠自行百度,項目結構以下圖所示:android
程序啓動和開始接收mqtt服務器的消息,而後接收以後推送給安卓或者IOS客戶端等,就是一個簡單的接收消息並推送的小Demo。ios
接收MQTT消息的代碼以下:api
private static Logger logger = LoggerFactory.getLogger(MqttMessageServer.class); private static MqttClient mqttClient = null; private static int allQos = 2; private MemoryPersistence persistence = new MemoryPersistence(); private final BlockingQueue<PostedMsg> messageQueue = new LinkedBlockingQueue<PostedMsg>(); @Resource private MqttConfiguration mqttConfiguration; @Resource private MqttMessageProcessService mqttMessageProcessService; @Override public void run(ApplicationArguments args) throws Exception { String clientUrl = mqttConfiguration.getClientUrl(); String clientTopic = mqttConfiguration.getClientTopic(); String clientId = mqttConfiguration.getClientId(); //初始化參數 MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); connOpts.setConnectionTimeout(30); connOpts.setKeepAliveInterval(60); connOpts.setAutomaticReconnect(true); try { mqttClient = new MqttClient(clientUrl, clientId, persistence); mqttClient.setCallback(new MqttCallbackExtended() { @Override public void connectComplete(boolean arg0, String arg1) { //訂閱主題 subscribeInformation(mqttClient,clientTopic, allQos); logger.info(">>>>>>>>訂閱全部主題成功>>>>>>>>"); } @Override public void connectionLost(Throwable throwable) { logger.info(">>>>>>>>MQTT服務器失去鏈接!!!>>>>>>>>"); } @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { System.err.println("========================"); logger.info(">>>>>>>>接收到MQTT推送的消息:" + topic); logger.info(">>>>>>>>接收到MQTT推送的消息內容:" + new String(mqttMessage.getPayload(), 0, mqttMessage.getPayload().length,"UTF-8")); PostedMsg postedMsg = new PostedMsg(mqttMessage,topic); messageQueue.offer(postedMsg); } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { logger.info("deliveryComplete:" + iMqttDeliveryToken.getMessageId()); } }); mqttClient.connect(connOpts); logger.info(">>>>>>>>鏈接MQTT服務器成功!!!,鏈接信息:"+clientUrl); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { while (true) { try { PostedMsg msg = (PostedMsg) messageQueue.take(); if (msg != null) { MqttMessage mqttMessage = (MqttMessage) msg.getMsg(); String strRevMsg = null; try { strRevMsg = new String(mqttMessage.getPayload(), 0, mqttMessage.getPayload().length,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } mqttMessageProcessService.processMqttMsg(msg.getTopic(), strRevMsg); } } catch (Exception e) { e.printStackTrace(); } } } }); //緩存MqttClient實例在Map中 GlobalHashMap.mqttClientMap.put("mqttClient", mqttClient); } catch (MqttException e) { e.printStackTrace(); } } private void subscribeInformation(MqttClient mqttClient,String allTopics,int allQos) { try { mqttClient.subscribe(allTopics, allQos); } catch (MqttException e) { e.printStackTrace(); } } /** * PUSH消息MQTT */ public void sendMqttMessage(String content, int qos, String topic) { try { MqttMessage message = new MqttMessage(content.getBytes("UTF-8")); message.setQos(qos); message.setRetained(false); mqttClient.publish(topic, message); } catch (Exception e) { e.printStackTrace(); } }
接下來就是怎麼處理推送到極光服務器的問題了緩存
這裏我貼出一篇寫了如何使用極光推送的文章,能夠參考看看:https://blog.csdn.net/qq_35860097/article/details/75117323服務器
而後就是我寫的極光推送的工具類,須要引入的maven依賴能夠查看官方文檔。文檔地址:https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/maven
代碼以下:ide
/** * 向全部平臺全部用戶推送消息 */ public static PushPayload buildPushObject_android_and_ios(String notification_title, String msg_title, String msg_content) { logger.info(">>>>>>>>向全部平臺全部用戶推送消息中>>>>>>>>"); return PushPayload.newBuilder() .setPlatform(Platform.android_ios()) .setAudience(Audience.all()) .setNotification( Notification.newBuilder() .setAlert(notification_title) .addPlatformNotification( AndroidNotification.newBuilder() .setAlert(msg_content) .setTitle(notification_title) // 此字段爲透傳字段,不會顯示在通知欄。用戶能夠經過此字段來作一些定製需求,如特定的key傳要指定跳轉的頁面(value) .build()) .addPlatformNotification( IosNotification.newBuilder() // 傳一個IosAlert對象,指定apns title、title、subtitle等 .setAlert(notification_title) // 直接傳alert // 此項是指定此推送的badge自動加1 .incrBadge(1) // 此字段的值default表示系統默認聲音;傳sound.caf表示此推送以項目裏面打包的sound.caf聲音來提醒, // 若是系統沒有此音頻則以系統默認聲音提醒;此字段若是傳空字符串,iOS9及以上的系統是無聲音提醒,如下的系統是默認聲音 .setSound("default") // 此項說明此推送是一個background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification // .setContentAvailable(true) .build()) .build()) // Platform指定了哪些平臺就會像指定平臺中符合推送條件的設備進行推送。 jpush的自定義消息, // sdk默認不作任何處理,不會有通知提示。建議看文檔http://docs.jpush.io/guideline/faq/的 // [通知與自定義消息有什麼區別?]瞭解通知和自定義消息的區別 .setMessage(Message.newBuilder().setMsgContent(msg_content).setTitle(msg_title).build()) .setOptions(Options.newBuilder() // 此字段的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義消息無心義 .setApnsProduction(ApnsProduction) // 此字段是給開發者本身給推送編號,方便推送者分辨推送記錄 .setSendno(1) // 此字段的值是用來指定本推送的離線保存時長,若是不傳此字段則默認保存一天,最多指定保留十天,單位爲秒 .setTimeToLive(86400).build()) .build(); }
到此,極光推送的小Demo基本上就算完成了,最近也是比較忙,等想到寫什麼的時候再更新下一篇博客吧。。。工具