SpringBoot通知機制的實現(xiàn)方式
1. 快速創(chuàng)建maven管理的SpringBoot項目
1、訪問 http://start.spring.io/
2、 選擇構建工具Maven Project、
Spring Boot版本1.3.6以及一些工程基本信息點擊“Switch to the full version.”java版本選擇1.7;
3、點擊Generate Project下載項目壓縮包
4、解壓后
使用eclipse,Import -> Existing Maven Projects -> Next ->選擇解壓后的文件夾-> Finsh,OK done!
使用IDEA的話,按如下步驟導入項目: File -> New -> Project fron Existing Sourses -> 選擇解壓后的直接包含pom.xml文件的demo文件夾,OK -> 選第二項Import project from external model, 選maven,Next -> Next -> 勾選左下角Open Project Structure after import, Next -> Next -> Finish -> 選Yes -> OK -> 大功告成!
(記錄自己踩過的坑:一定要選直接包含pom.xml的demo文件夾,一開始選擇直接解壓后的demo文件夾,結果找不到可以導入的maven項目。 )

5、 運行剛導入的項目
訪問localhost:8080/hello, 看到頁面顯示Hello World。
6、 在這個demo的基礎上進行開發(fā)
2. 通知機制的流程
1、客戶端向server訂閱通知
訂閱信息包括通知類型(notificationTypes)、過濾條件(filteringCriteria)、訂閱者地址(subscriberUri)和 managerId。
請求數(shù)據(jù)以json格式發(fā)送,因此在服務端用@RequestBody Map request 來處理請求中的json數(shù)據(jù),創(chuàng)建JSONObject 對象,從而根據(jù)參數(shù)名獲取請求中傳入的參數(shù)值。
服務端代碼如下:
@RequestMapping("/notifications")
public void subscribeNotification(@RequestBody Map request, HttpServletResponse response)
throws ServletException, IOException, JSONException {
System.out.println("Enter localhost:8083/notifications. " );
JSONObject jsonObject = new JSONObject(request);
String subscriptionId = (String) jsonObject.get("subscriptionId"); // 通過JSONObject 對象獲取請求中傳入的參數(shù)值
String notificationType = (String) jsonObject.get("notificationType");
String filteringCriteria = (String) jsonObject.get("filteringCriteria");
String managerId = (String) jsonObject.get("managerId");
System.out.println("subscriptionId=" + subscriptionId + ", notificationType=" + notificationType + ", filteringCriteria=" + filteringCriteria + ", managerId=" + managerId );
// some code... 省略了存數(shù)據(jù)庫的操作
response.setHeader("Location", "http://localhost:8083/notifications/0101"); // 通過response.setHeader()方法設置響應頭
PrintWriter out = response.getWriter();
String result = "Success to Subscribe a notification! ";
out.write(result);
}
服務端端口設為8083,默認是8080,可以通過在resources 下的application.properties文件里加一條語句server.port=8083 修改為其他端口號。
Postman的接口測試結果如下:

2、服務端將通知發(fā)送給客戶端
請求信息包括訂閱Id(subscriptionId)、通知類型(NotificationType)、發(fā)送者Id(producerId)、消息(message)。首先根據(jù)subscriptionId 從數(shù)據(jù)庫查找到該訂閱的通知類型、過濾條件和訂閱者地址,然后判斷該通知是否符合訂閱條件,符合則將該通知發(fā)送給訂閱者。
服務端代碼如下:
@RequestMapping("/sendNotification")
public void sendNotification(@RequestBody Map request, HttpServletResponse response)
throws ServletException, IOException, JSONException {
System.out.println("request:" + request);
JSONObject jsonObject = new JSONObject(request);
System.out.println("jsonObject:" + jsonObject);
String subscriptionId = (String) jsonObject.get("subscriptionId");
String notificationType = (String) jsonObject.get("notificationType");
String producerId = (String) jsonObject.get("producerId");
String alarmType = (String) jsonObject.getJSONObject("message").get("alarmType");
System.out.println("subscriptionId=" + subscriptionId + ", notificationType=" + notificationType + ", producerId=" + producerId + ", alarmType=" + alarmType );
// some code... 查詢數(shù)據(jù)庫(省略)
// 模擬數(shù)據(jù)庫查詢結果
String getNotificationType = "";
String getAlarmType = "";
String getsubscriberUri = "";
if(subscriptionId.equals("http://localhost:8081/notifications/0101")){
getNotificationType = "alarm";
getAlarmType = "01";
getsubscriberUri = "http://localhost:8081/notifications/001";
}
if(subscriptionId.equals("http://localhost:8081/notifications/0102")){
getNotificationType = "alarm";
getAlarmType = "02";
getsubscriberUri = "http://localhost:8082/notifications/001";
}
// 判斷該通知是否符合訂閱條件
String subscribeURL = "";
if(notificationType.equals(getNotificationType) && alarmType.equals(getAlarmType)){
subscribeURL = getsubscriberUri;
} else return;
// 建立連接,將通知發(fā)送給訂閱者
HttpURLConnection subscribeConnection = null;
StringBuffer responseBuffer = new StringBuffer();
try{
URL getsubscribeURL = new URL(subscribeURL);
subscribeConnection = (HttpURLConnection) getsubscribeURL.openConnection(); // 建立連接
subscribeConnection.setDoOutput(true);
subscribeConnection.setDoInput(true);
subscribeConnection.setRequestMethod("POST");
subscribeConnection.setRequestProperty("Accept-Charset", "utf-8");
subscribeConnection.setRequestProperty("Content-Type", "application/json");
subscribeConnection.setRequestProperty("Charset", "UTF-8");
byte[] data = (jsonObject.toString()).getBytes();
subscribeConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
// 開始連接請求
subscribeConnection.connect();
OutputStream out = subscribeConnection.getOutputStream();
// 寫入請求的字符串
out.write((jsonObject.toString()).getBytes()); // 發(fā)送json數(shù)據(jù)
out.flush();
out.close();
}catch (IOException e) {
}
if (subscribeConnection.getResponseCode() == 200) { // 若響應碼為200,則通知訂閱成功
System.out.println("Success to send the notification." );
String readLine;
BufferedReader responseReader = new BufferedReader(new InputStreamReader(
subscribeConnection.getInputStream(), "utf-8"));
while ((readLine = responseReader.readLine()) != null) {
responseBuffer.append(readLine);
}
System.out.println("Http Response:" + responseBuffer);
subscribeConnection.disconnect();
PrintWriter out = response.getWriter();
out.write(responseBuffer.toString());
}else return;
}
訂閱者(8081端口)接收通知,代碼如下:
@RequestMapping("/notifications/001")
public void receiveNotification(@RequestBody Map request, HttpServletResponse response)
throws ServletException, IOException{
System.out.println("Receive a new notification." );
System.out.println("request:" + request);
PrintWriter out = response.getWriter();
String result = "Success to Subscribe a notification! ";
out.write(result);
}
3. 運行過程及結果
首先,用Postman 向服務端(8083端口)發(fā)送通知:

服務端結果如下:

訂閱者(8081端口)結果如下:

附上demo源碼地址: https://github.com/bupt-lxl/SpringBoot-Notification
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Hibernate中l(wèi)oad方法與get方法的區(qū)別
Hibernate中有兩個極為相似的方法get()與load(),他們都可以通過指定的實體類與ID從數(shù)據(jù)庫中讀取數(shù)據(jù),并返回對應的實例,但Hibernate不會搞兩個完全一樣的方法的2016-01-01
在Spring Boot中加載初始化數(shù)據(jù)的實現(xiàn)
這篇文章主要介紹了在Spring Boot中加載初始化數(shù)據(jù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
spring?boot?實現(xiàn)一個?禁止重復請求的方法
這篇文章主要介紹了spring?boot?實現(xiàn)一個?禁止重復請求,當重復請求該方法時,會返回"Duplicate?request",避免重復執(zhí)行相同的操作,需要的朋友可以參考下2024-03-03
java調(diào)用openoffice將office系列文檔轉(zhuǎn)換為PDF的示例方法
本篇文章主要介紹了java使用openoffice將office系列文檔轉(zhuǎn)換為PDF的示例方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-11-11
Springboot如何同時裝配兩個相同類型數(shù)據(jù)庫
這篇文章主要介紹了Springboot如何同時裝配兩個相同類型數(shù)據(jù)庫,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
SpringBoot如何訪問html和js等靜態(tài)資源配置
這篇文章主要介紹了SpringBoot如何訪問html和js等靜態(tài)資源配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Spring Boot基于Active MQ實現(xiàn)整合JMS
這篇文章主要介紹了Spring Boot基于Active MQ實現(xiàn)整合JMS,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07

