Переглянути джерело

修改websocket地址从配置文件获取,优化websocket超时退出机制

hurugang 3 роки тому
батько
коміт
b200becea8

+ 15 - 0
src/main/java/cn/hnthyy/thmz/Utils/DateUtil.java

@@ -375,6 +375,21 @@ public class DateUtil {
         return diff / 60 / 1000;
     }
 
+
+    /**
+     * 获取两个时间中间隔分钟
+     *
+     * @param beginTime
+     * @param endTime
+     * @return
+     */
+    public static Long getIntervalMinutes(Date beginTime, Date endTime){
+        //获得这两个时间的毫秒值后进行处理(因为我的需求不需要处理时间大小,所以此处没有处理,可以判断一下哪个大就用哪个作为减数。)
+        long diff = endTime.getTime() - beginTime.getTime();
+        //此处用毫秒值除以分钟再除以毫秒既得两个时间相差的分钟数
+        return diff / 60 / 1000;
+    }
+
     /**
      * 判断当前日期是否是周末
      *

+ 18 - 5
src/main/java/cn/hnthyy/thmz/controller/CommonController.java

@@ -4,13 +4,11 @@ import cn.hnthyy.thmz.comment.UserLoginToken;
 import cn.hnthyy.thmz.enums.*;
 import cn.hnthyy.thmz.service.his.mz.*;
 import cn.hnthyy.thmz.service.his.zd.*;
-import cn.hnthyy.thmz.service.thmz.PaidForZZService;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
 
 import java.util.*;
@@ -36,8 +34,9 @@ public class CommonController {
     private YshZdPartCodeService yshZdPartCodeService;
     @Autowired
     private JcZdClassService jcZdClassService;
-    @Autowired
-    private PaidForZZService paidForZZService;
+    //websocket 地址前半部分
+    @Value("${webSocketHost}")
+    private String webSocketHost;
     /**
      * 查询科室分类
      *
@@ -727,4 +726,18 @@ public class CommonController {
 //            return resultMap;
 //        }
 //    }
+
+
+
+    /**
+     * 获取webSocket地址 评价器调用,不用鉴权
+     */
+    @RequestMapping(value = "/getWebSocketHost", method = {RequestMethod.GET})
+    public Map<String, Object> getWebSocketHost() {
+        Map<String, Object> resultMap = new HashMap<>();
+        resultMap.put("code", 0);
+        resultMap.put("message", "查询webSocket地址成功");
+        resultMap.put("data", webSocketHost);
+        return resultMap;
+    }
 }

+ 2 - 0
src/main/java/cn/hnthyy/thmz/service/his/mz/ChargeFeeVoService.java

@@ -4,6 +4,8 @@ import cn.hnthyy.thmz.entity.his.mz.MzReceiptSerial;
 import cn.hnthyy.thmz.entity.thmz.Mzmxsr;
 import cn.hnthyy.thmz.enums.YesNoEnum;
 import cn.hnthyy.thmz.vo.*;
+
+import javax.servlet.http.HttpServletRequest;
 import java.math.BigDecimal;
 import java.util.Date;
 import java.util.List;

+ 0 - 1
src/main/java/cn/hnthyy/thmz/service/impl/his/mz/ChargeFeeVoServiceImpl.java

@@ -16,7 +16,6 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Isolation;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
-
 import java.math.BigDecimal;
 import java.util.Date;
 import java.util.List;

+ 4 - 12
src/main/java/cn/hnthyy/thmz/service/impl/thmz/EvaluationServiceImpl.java

@@ -46,10 +46,7 @@ public class EvaluationServiceImpl implements EvaluationService {
      * 客户端与患者的对应关系
      */
     private static ConcurrentHashMap<String, Map<String,Object>> clientAndPatientMap = new ConcurrentHashMap<>();
-    /**
-     * 存储了所有评价器客户端IP与评价器对应的用户信息,因为建立价格连接和推送消息是两步,会断开,所以缓存起来
-     */
-    private static ConcurrentHashMap<String, User> userMap = new ConcurrentHashMap<>();
+
     @Override
     public void login(HttpServletRequest httpServletRequest) {
         String requestIp = HttpUtil.getIPAddress(httpServletRequest);
@@ -67,17 +64,12 @@ public class EvaluationServiceImpl implements EvaluationService {
             e.printStackTrace();
             return;
         }
-        userMap.put(windows.getClientIpAddress(),tokenUser);
-        evaluationWebSocket.login(windows.getClientIpAddress());
+        evaluationWebSocket.login(windows.getClientIpAddress(),tokenUser);
     }
 
     @Override
     public void loginOut(String clientIpAddress) {
-        userMap.remove(clientIpAddress);
-        Map<String, Object> resultMap = new HashMap();
-        resultMap.put("type", "url");
-        resultMap.put("url", "/thmz/client-welcome");
-        evaluationWebSocket.appointSending(clientIpAddress, JSONObject.valueToString(resultMap));
+        evaluationWebSocket.loginOut(clientIpAddress);
     }
 
 
@@ -85,7 +77,7 @@ public class EvaluationServiceImpl implements EvaluationService {
     @Override
     public Map<String, Object> getUserInfo(HttpServletRequest httpServletRequest) {
         String requestIp = HttpUtil.getIPAddress(httpServletRequest);
-        User tokenUser=userMap.get(requestIp);
+        User tokenUser=evaluationWebSocket.getUser(requestIp);
         if(tokenUser==null){
             return null;
         }

+ 59 - 6
src/main/java/cn/hnthyy/thmz/socket/EvaluationWebSocket.java

@@ -1,7 +1,11 @@
 package cn.hnthyy.thmz.socket;
 
+import cn.hnthyy.thmz.Utils.DateUtil;
+import cn.hnthyy.thmz.entity.thmz.User;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.json.JSONObject;
+import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Component;
 
 import javax.websocket.OnClose;
@@ -10,10 +14,7 @@ import javax.websocket.OnOpen;
 import javax.websocket.Session;
 import javax.websocket.server.PathParam;
 import javax.websocket.server.ServerEndpoint;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
 import java.util.concurrent.ConcurrentHashMap;
 
 
@@ -50,11 +51,19 @@ public class EvaluationWebSocket {
      */
     private static ConcurrentHashMap<String, EvaluationWebSocket> webSocketSet = new ConcurrentHashMap<>();
 
+    /**
+     * 用于存所有的连接最后一次发送消息的时间
+     */
+    private static ConcurrentHashMap<String, Date> lastSendMessageDate = new ConcurrentHashMap<>();
+
 //    /**
 //     * 用于存所有待推送的价格信息,因为建立价格连接和推送消息是两步,会断开,所以缓存起来
 //     */
 //    private static ConcurrentHashMap<String, Map<String, Object>> priceMap = new ConcurrentHashMap<>();
-
+    /**
+     * 存储了所有评价器客户端IP与评价器对应的用户信息,因为建立价格连接和推送消息是两步,会断开,所以缓存起来
+     */
+    private static ConcurrentHashMap<String, User> userMap = new ConcurrentHashMap<>();
     /**
      * 保存登录到换页的评价器ip
      */
@@ -107,6 +116,7 @@ public class EvaluationWebSocket {
     public void groupSending(String message) {
         for (String name : webSocketSet.keySet()) {
             try {
+                lastSendMessageDate.put(name,new Date());
                 webSocketSet.get(name).session.getBasicRemote().sendText(message);
             } catch (Exception e) {
                 //e.printStackTrace();
@@ -125,6 +135,7 @@ public class EvaluationWebSocket {
         try {
             Session session = webSocketSet.get(clientIp).session;
             synchronized (session) {
+                lastSendMessageDate.put(clientIp,new Date());
                 session.getBasicRemote().sendText(message);
             }
         } catch (Exception e) {
@@ -146,8 +157,10 @@ public class EvaluationWebSocket {
     /**
      * 评价器客户端登录
      * @param clientIp
+     * @param tokenUser
      */
-    public void login(String clientIp) {
+    public void login(String clientIp,User tokenUser) {
+        userMap.put(clientIp,tokenUser);
         if (isLogin(clientIp)) {
             return;
         }
@@ -158,6 +171,27 @@ public class EvaluationWebSocket {
         appointSending(clientIp, JSONObject.valueToString(resultMap));
     }
 
+    /**
+     * 评价器登出
+     * @param clientIpAddress
+     */
+    public void loginOut(String clientIpAddress) {
+        Map<String, Object> resultMap = new HashMap();
+        resultMap.put("type", "url");
+        resultMap.put("url", "/thmz/client-welcome");
+        appointSending(clientIpAddress, JSONObject.valueToString(resultMap));
+        userMap.remove(clientIpAddress);
+        welcomeSet.remove(clientIpAddress);
+    }
+
+    /**
+     * 获取当前评价器登录的用户信息
+     * @param requestIp
+     * @return
+     */
+    public User getUser(String requestIp){
+        return userMap.get(requestIp);
+    }
 //    /**
 //     * 设置待发送的价格信息
 //     *
@@ -167,4 +201,23 @@ public class EvaluationWebSocket {
 //    public void setPriceInfo(String clientIp, Map<String, Object> params) {
 //        priceMap.put(clientIp, params);
 //    }
+
+
+    /**
+     * 每十分钟检查一次客户端是否没有消息推送,如果没有消息推送就关闭客户端
+     */
+    @Scheduled(cron="0 0/10 * * * ?")
+    private void closeClientSession() {
+        Date now = new Date();
+        for (String clientIp:lastSendMessageDate.keySet()) {
+            if(StringUtils.isBlank(clientIp)){
+                continue;
+            }
+            Date lastDate = lastSendMessageDate.get(clientIp);
+            Long intervalMinutes =DateUtil.getIntervalMinutes(lastDate,now);
+            if(intervalMinutes>=10L){
+                loginOut(clientIp);
+            }
+        }
+    }
 }

+ 4 - 1
src/main/resources/application-dev.yml

@@ -137,4 +137,7 @@ notifyServiceUrl: "http://172.16.30.26:8706/triage/notify"
 #语音生成接口地址
 audioServiceUrl: "http://webhis.thyy.cn:8706/voice/textToSpeech"
 #化验结果接口
-soap_url: "http://172.16.32.178:622/pushservice.asmx?wsdl"
+soap_url: "http://172.16.32.178:622/pushservice.asmx?wsdl"
+
+#websocket 地址前半部分
+webSocketHost: "ws://172.16.32.161:81/thmz/"

+ 4 - 1
src/main/resources/application-prod.yml

@@ -135,4 +135,7 @@ notifyServiceUrl: "http://webhis.thyy.cn:8706/triage/notify"
 audioServiceUrl: "http://webhis.thyy.cn:8706/voice/textToSpeech"
 
 #化验结果接口
-soap_url: "http://172.16.32.178:622/pushservice.asmx?wsdl"
+soap_url: "http://172.16.32.178:622/pushservice.asmx?wsdl"
+
+#websocket 地址前半部分
+webSocketHost: "ws://webhis.thyy.cn:81/thmz/"

+ 76 - 62
src/main/resources/static/js/common/evaluation-websocket.js

@@ -1,9 +1,9 @@
 var websocket = null;
 var ipAddress = "";
-//测试环境
-//var serverAddress="ws://172.16.32.161:81/thmz/evaluationWebSocket/";
-//生产环境
-var serverAddress="ws://webhis.thyy.cn:81/thmz/evaluationWebSocket/";
+// //测试环境
+// //var serverAddress="ws://172.16.32.161:81/thmz/evaluationWebSocket/";
+// //生产环境
+// var serverAddress="ws://webhis.thyy.cn:81/thmz/evaluationWebSocket/";
 /**
  * 创建webSocket
  * @param type
@@ -13,66 +13,80 @@ function openEvaluationWebSocket(type) {
         getUserIP(function(ip) {
             ipAddress = ip
             if('WebSocket' in window){
-                websocket = new WebSocket(serverAddress+ipAddress+"/"+type);
-            }else{
-                alert('当前浏览器不支持WebSocket,请更换浏览器');
-            }
-            websocket.onerror = function(){
-                console.log("连接出错");
-            }
-            websocket.onopen = function(){
-                console.log("连接成功");
-            }
-            websocket.onmessage  = function(event){
-                var data = JSON.parse(event.data);
-                if(data.type=="url"){
-                    window.open(data.url, '_self');
-                    return;
-                }
-                //推送价格
-                if(data.type=="priceData"){
 
-                }
-                if(data.type=="content"){
-                    if(data.id=="client_evaluate"){
-                        $("#client_evaluate").show();
-                        $("#client_index").hide();
-                        $("#client_price").hide();
-                        var mp3 = $("#mp3");
-                        mp3.attr("src",data.messageAudio);
-                        mp3.get(0).play();
-                        return;
-                    }else if(data.id=="client_price"){
-                        $("#client_price").show();
-                        $("#client_evaluate").hide();
-                        $("#client_index").hide();
-                        $("#pName").text(data.name);
-                        $("#pGender").text(data.call);
-                        $("#needPay").text(data.needPay);
-                        $("#pay").text(data.pay);
-                        $("#changeAmount").text(data.changeAmount);
-                        //播放语音
-                        var mp3 = $("#mp3");
-                        mp3.attr("src",data.messageAudio);
-                        mp3.get(0).play();
-                        return;
-                    }
-                }
-                console.log("收到消息" + event.data);
-            }
-            websocket.onclose = function(){
-                console.log("退出连接");
-            }
-            window.onbeforeunload = function(){
-                clos();
-            }
+                $.ajax({
+                    type: "GET",
+                    url: '/thmz/getWebSocketHost',
+                    contentType: "application/json;charset=UTF-8",
+                    dataType: "json",
+                    headers: {'Accept': 'application/json'},
+                    success: function (res) {
+                        if (res.code == 0) {
+                            var serverAddress=res.data;
+                            serverAddress=serverAddress+"evaluationWebSocket/"+ipAddress+"/"+type;
+                            websocket = new WebSocket(serverAddress);
+                            websocket.onerror = function(){
+                                console.log("连接出错");
+                            }
+                            websocket.onopen = function(){
+                                console.log("连接成功");
+                            }
+                            websocket.onmessage  = function(event){
+                                var data = JSON.parse(event.data);
+                                if(data.type=="url"){
+                                    window.open(data.url, '_self');
+                                    return;
+                                }
+                                //推送价格
+                                if(data.type=="priceData"){
 
-            function clos(){
-                websocket.close(3000,"强制关闭");
-            }
-            function send(){
-                var msg = document.getElementById('text').value;
-                websocket.send(msg);
+                                }
+                                if(data.type=="content"){
+                                    if(data.id=="client_evaluate"){
+                                        $("#client_evaluate").show();
+                                        $("#client_index").hide();
+                                        $("#client_price").hide();
+                                        var mp3 = $("#mp3");
+                                        mp3.attr("src",data.messageAudio);
+                                        mp3.get(0).play();
+                                        return;
+                                    }else if(data.id=="client_price"){
+                                        $("#client_price").show();
+                                        $("#client_evaluate").hide();
+                                        $("#client_index").hide();
+                                        $("#pName").text(data.name);
+                                        $("#pGender").text(data.call);
+                                        $("#needPay").text(data.needPay);
+                                        $("#pay").text(data.pay);
+                                        $("#changeAmount").text(data.changeAmount);
+                                        //播放语音
+                                        var mp3 = $("#mp3");
+                                        mp3.attr("src",data.messageAudio);
+                                        mp3.get(0).play();
+                                        return;
+                                    }
+                                }
+                                console.log("收到消息" + event.data);
+                            }
+                            websocket.onclose = function(){
+                                console.log("退出连接");
+                            }
+                            window.onbeforeunload = function(){
+                                clos();
+                            }
+
+                            function clos(){
+                                websocket.close(3000,"强制关闭");
+                            }
+                            function send(){
+                                var msg = document.getElementById('text').value;
+                                websocket.send(msg);
+                            }
+                        }
+                    }
+                });
+            }else{
+                alert('当前浏览器不支持WebSocket,请更换浏览器');
             }
         })
     }