Преглед на файлове

修改微信客服聊天

zhoufan преди 2 години
родител
ревизия
6db2f549c4

+ 21 - 8
webapidemo-api/src/main/java/com/example/controller/system/UserController.java

@@ -354,9 +354,13 @@ public class UserController extends BaseController {
354 354
         Long userId = CurrentUser().getUserId();
355 355
         qw.eq(User::getUserId, userId);
356 356
         User user = userService.getEntity(qw);
357
+        System.out.println(JSON.toJSONString(user));
357 358
         if ("0".equals(user.getIsKefu())) {
358
-            user.setOnlineType("0");
359
-            userService.update(user);
359
+//            user.setOnlineType("0");
360
+//            userService.update(user);
361
+            User up=new User();
362
+            up.setOnlineType("0");
363
+            userService.updateBatch(up,qw);
360 364
             updateGroupQueue();
361 365
             userService.getKefuMessage(CurrentUser().getUserId().toString());
362 366
             return Success("签入成功!");
@@ -374,8 +378,11 @@ public class UserController extends BaseController {
374 378
         qw.eq(User::getUserId, userId);
375 379
         User user = userService.getEntity(qw);
376 380
         if ("0".equals(user.getIsKefu())) {
377
-            user.setOnlineType("2");
378
-            userService.update(user);
381
+//            user.setOnlineType("2");
382
+//            userService.update(user);
383
+            User up=new User();
384
+            up.setOnlineType("2");
385
+            userService.updateBatch(up,qw);
379 386
             updateGroupQueue();
380 387
             String queueName = "kefu_" + userId;
381 388
             Set<String> keys = redisHelper.getSetKeys(queueName + "*");
@@ -395,9 +402,12 @@ public class UserController extends BaseController {
395 402
         queryWrapper.eq(User::getUserId, userId);
396 403
         User user = userService.getEntity(queryWrapper);
397 404
         if ("0".equals(user.getIsKefu())) {
398
-            user.setOnlineType("1");
405
+            //user.setOnlineType("1");
406
+            //boolean update = userService.update(user);
407
+            User up=new User();
408
+            up.setOnlineType("1");
409
+            boolean update =userService.updateBatch(up,queryWrapper);
399 410
             String queueName = "kefu_" + userId;
400
-            boolean update = userService.update(user);
401 411
             if (update) {
402 412
                 updateGroupQueue();
403 413
                 //生成模糊匹配的对应的set集合,字符串后面追加的*号做模糊匹配使用
@@ -420,8 +430,11 @@ public class UserController extends BaseController {
420 430
         queryWrapper.eq(User::getUserId, userId);
421 431
         User user = userService.getEntity(queryWrapper);
422 432
         if ("0".equals(user.getIsKefu())) {
423
-            user.setOnlineType("0");
424
-            userService.update(user);
433
+//            user.setOnlineType("0");
434
+//            userService.update(user);
435
+            User up=new User();
436
+            up.setOnlineType("0");
437
+            userService.updateBatch(up,queryWrapper);
425 438
             updateGroupQueue();
426 439
             return Success("置闲成功");
427 440
         }

+ 72 - 1
webapidemo-api/src/main/java/com/example/controller/wechat/WechatController.java

@@ -16,6 +16,7 @@ import com.example.service.system.IUserService;
16 16
 import com.example.service.webScoket.WebSocket;
17 17
 import com.example.util.helper.FileUtil;
18 18
 import com.example.util.helper.RedisHelper;
19
+import com.example.util.helper.StringHelper;
19 20
 import com.thoughtworks.xstream.XStream;
20 21
 import me.chanjar.weixin.common.api.WxConsts;
21 22
 import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
@@ -228,7 +229,7 @@ public class WechatController extends BaseController {
228 229
             LambdaQueryWrapper<CustomerInfo> qw = new LambdaQueryWrapper<>();
229 230
             qw.eq(CustomerInfo::getOpenId, id);
230 231
             CustomerInfo customerInfo = customerInfoService.getEntity(qw);
231
-            if (custName != null && !customerInfo.getCustName().contains(custName)) {
232
+            if (customerInfo==null ||(customerInfo != null&& StringHelper.isNotEmpty(custName) && !customerInfo.getCustName().contains(custName))) {
232 233
                 continue;
233 234
             }
234 235
             Query query = new Query(Criteria.where("openId").is(id));
@@ -256,14 +257,84 @@ public class WechatController extends BaseController {
256 257
      */
257 258
     @GetMapping("/kefu/mongodbMessage/{openId}")
258 259
     public AjaxResult getChatHistory(@PathVariable String openId) {
260
+        Long userId = CurrentUser().getUserId();
259 261
         Query query = new Query(Criteria.where("openId").is(openId));
260 262
         List<MongoDBMessage> mongoDBMessages = mongoTemplate.find(query, MongoDBMessage.class);
263
+
264
+        if(mongoDBMessages.stream().filter(p->p.getReadMessage().equals(1)).count()>0) {
265
+            query.addCriteria(Criteria.where("readMessage").is(1));
266
+            Update update = new Update();
267
+            update.set("readMessage", 0);
268
+            update.set("kefuId", userId);
269
+            this.mongoTemplate.updateMulti(query, update, MongoDBMessage.class);
270
+        }
271
+
272
+        return Success("操作成功!", mongoDBMessages);
273
+    }
274
+
275
+    /**
276
+     * mongodb保存的聊天记录
277
+     * @return
278
+     */
279
+    @GetMapping("/kefu/leaveword/{openId}")
280
+    public AjaxResult getLeaveWord(@PathVariable String openId) {
281
+        Query query = new Query(Criteria.where("openId").is(openId).and("kefuId").is(0));
282
+        Long n = this.mongoTemplate.count(query, MongoDBMessage.class);
283
+        if (n == 0L) {
284
+            return Error("其他客服已经接入");
285
+        }
286
+        Long userId = CurrentUser().getUserId();
287
+        List<MongoDBMessage> mongoDBMessages = mongoTemplate.find(query, MongoDBMessage.class);
261 288
         Update update = new Update();
262 289
         update.set("readMessage", 0);
290
+        update.set("kefuId", userId);
263 291
         this.mongoTemplate.updateMulti(query, update, MongoDBMessage.class);
264 292
         return Success("操作成功!", mongoDBMessages);
265 293
     }
266 294
 
295
+    /**
296
+     * 获取留言列表
297
+     * @return
298
+     */
299
+    @GetMapping("/kefu/leaveword")
300
+    public AjaxResult getLeaveWordList(@RequestParam(value = "custName", required = false) String custName) {
301
+        Long userId = CurrentUser().getUserId();
302
+        //分组
303
+        Aggregation agg = Aggregation.newAggregation(
304
+                //进行条件的筛选
305
+                Aggregation.match(Criteria.where("kefuId").is(0L)),
306
+                //针对某一个字段分组
307
+                Aggregation.group("openId").count().as("count"),
308
+                Aggregation.project("count")
309
+        );
310
+        AggregationResults<Map> aggregationResults = mongoTemplate.aggregate(agg, MongoDBMessage.class, Map.class);
311
+        List<Map> list = aggregationResults.getMappedResults();
312
+        List<SocketVo> socketVoList = new ArrayList<>();
313
+        for (Map map : list) {
314
+            String id = map.get("_id").toString();
315
+
316
+            LambdaQueryWrapper<CustomerInfo> qw = new LambdaQueryWrapper<>();
317
+            qw.eq(CustomerInfo::getOpenId, id);
318
+            CustomerInfo customerInfo = customerInfoService.getEntity(qw);
319
+            if (customerInfo==null ||(customerInfo != null&& StringHelper.isNotEmpty(custName) && !customerInfo.getCustName().contains(custName))) {
320
+                continue;
321
+            }
322
+            Query query = new Query(Criteria.where("openId").is(id));
323
+            query.with(Sort.by(Sort.Order.desc("_id"))).limit(1);
324
+            MongoDBMessage templateOne = mongoTemplate.findOne(query, MongoDBMessage.class);
325
+
326
+            SocketVo socketVo = new SocketVo();
327
+            socketVo.setCustId(customerInfo.getCustId());
328
+            socketVo.setOpenId(customerInfo.getOpenId());
329
+            socketVo.setCustName(customerInfo.getCustName());
330
+            socketVo.setCustChannel(customerInfo.getCustChannel());
331
+            socketVo.setSendTime(templateOne.getSendDate());
332
+            socketVo.setContent(templateOne.getContent());
333
+            socketVo.setUnreadMessageCount(Long.parseLong(map.get("count").toString()) );
334
+            socketVoList.add(socketVo);
335
+        }
336
+        return Success("成功!", socketVoList);
337
+    }
267 338
 
268 339
     /**
269 340
      * 获取文件类型

+ 14 - 13
webapidemo-api/src/main/resources/application-dev.yml

@@ -48,15 +48,6 @@ spring:
48 48
             type: round_robin
49 49
     enabled: true
50 50
 
51
-  data:
52
-    mongodb:
53
-      authentication-database: admin
54
-      host: 192.168.5.44
55
-      port: 27017
56
-      database: jiayi
57
-      username: root
58
-      password: '123456'
59
-
60 51
   redis:
61 52
     # 地址
62 53
     host: 192.168.1.200
@@ -68,6 +59,16 @@ spring:
68 59
     password:
69 60
     # 连接超时时间
70 61
     timeout: 10s
62
+
63
+  data:
64
+    mongodb:
65
+      authentication-database: admin
66
+      host: 192.168.5.44
67
+      port: 27017
68
+      database: jiayi
69
+      username: root
70
+      password: '123456'
71
+
71 72
   rabbitmq:
72 73
     host: 192.168.1.200
73 74
     port: 5672
@@ -89,7 +90,7 @@ spring:
89 90
     #        auto-startup: false
90 91
 
91 92
   wechat:
92
-    AppId: wx4ff77198ae11494b
93
-    AppSecret: 2142698972a706a651f371e412d48a78
94
-    Token: wxtoken
95
-    EncodingAESKey:
93
+    AppId: wx0d67bbb5666ec226
94
+    AppSecret: abe7ea3ac71e42fa27ec564045b1387a
95
+    Token: a3ac71e42f
96
+    EncodingAESKey: SnHmIXFhkuagAXcoAAEsgVnNiqFdn2TXkwT7Tm2MqkC

+ 2 - 2
webapidemo-api/src/main/resources/application.yml

@@ -3,8 +3,8 @@ spring:
3 3
     date-format: yyyy-MM-dd HH:mm:ss
4 4
     time-zone: GMT+8
5 5
   profiles:
6
-    active: production
7
-    #active: dev
6
+    #active: production
7
+    active: dev
8 8
 
9 9
   resources:
10 10
     static-locations: file:/home/website/webapidemo/Api/file/image/  #资源路径

+ 0 - 271
webapidemo-api/src/test/java/TestDate/TestDateInput.java

@@ -1,271 +0,0 @@
1
-package TestDate;
2
-
3
-import com.alibaba.fastjson2.JSON;
4
-import com.alibaba.fastjson2.JSONObject;
5
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
6
-import com.example.WebApiApplication;
7
-import com.example.entity.database.system.Menu;
8
-import com.example.entity.database.system.User;
9
-import com.example.entity.view.system.GroupLogins;
10
-import com.example.service.rabbitmqListener.Consumer;
11
-import com.example.service.rabbitmqListener.PicDownload;
12
-import com.example.service.system.IMenuService;
13
-import com.example.service.system.IUserService;
14
-import com.example.service.webScoket.WebSocket;
15
-import com.example.util.config.RabbitConfig;
16
-import com.example.util.config.WxMpConfig;
17
-import com.example.util.helper.RedisHelper;
18
-import com.rabbitmq.client.Channel;
19
-import com.rabbitmq.client.Connection;
20
-import com.rabbitmq.client.GetResponse;
21
-import me.chanjar.weixin.common.error.WxErrorException;
22
-import me.chanjar.weixin.mp.api.WxMpService;
23
-import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
24
-import org.junit.Test;
25
-import org.junit.runner.RunWith;
26
-import org.springframework.amqp.rabbit.core.RabbitTemplate;
27
-import org.springframework.beans.factory.annotation.Autowired;
28
-import org.springframework.boot.test.context.SpringBootTest;
29
-import org.springframework.data.mongodb.core.MongoTemplate;
30
-import org.springframework.test.context.junit4.SpringRunner;
31
-import org.springframework.web.context.request.RequestContextHolder;
32
-import org.springframework.web.socket.WebSocketSession;
33
-
34
-import java.io.*;
35
-import java.net.URL;
36
-import java.net.URLConnection;
37
-import java.nio.charset.StandardCharsets;
38
-import java.text.SimpleDateFormat;
39
-import java.util.*;
40
-
41
-@SpringBootTest(classes = WebApiApplication.class)
42
-@RunWith(SpringRunner.class)
43
-public class TestDateInput {
44
-    @Autowired
45
-    public IMenuService menuService;
46
-    @Autowired
47
-    public WxMpService wxMpService;
48
-    @Autowired
49
-    public RedisHelper redisHelper;
50
-    @Autowired
51
-    public RabbitTemplate rabbitTemplate;
52
-    @Autowired
53
-    public Consumer consumer;
54
-    @Autowired
55
-    public MongoTemplate mongoTemplate;
56
-    @Autowired
57
-    private WebSocket webSocket;
58
-    @Autowired
59
-    private IUserService userService;
60
-    @Test
61
-    public void test1() {
62
-        Calendar oldCal = Calendar.getInstance();
63
-        oldCal.setTime(new Date());
64
-        oldCal.add(2, -1);
65
-
66
-        Calendar nowCal = Calendar.getInstance();
67
-        nowCal.setTime(new Date());
68
-        System.out.println(nowCal.after(oldCal));
69
-        if (nowCal.after(oldCal)) {
70
-            System.out.println(true);
71
-        } else {
72
-            System.out.println(false);
73
-        }
74
-
75
-
76
-    }
77
-
78
-    @Test
79
-    public void test2() {
80
-        List<Menu> menus = menuService.selectMenuTreeByUserId(2l);
81
-        System.out.println(menus);
82
-    }
83
-
84
-    @Test
85
-    public void test3() {
86
-        String cache = redisHelper.getCache("orR6E6l4wDixgeO8iaDetMoeb3hs");
87
-        System.out.println(cache);
88
-    }
89
-
90
-    @Test
91
-    public void test223() {
92
-        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
93
-        qw.eq(User::getUserId,"1");
94
-        User entity = userService.getEntity(qw);
95
-        System.out.println(entity);
96
-    }
97
-
98
-
99
-    @Test
100
-    public void test222() {
101
-
102
-        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
103
-        //String format = simpleDateFormat.format(createTime);
104
-    }
105
-
106
-    @Test
107
-    public void Test777() throws IOException {
108
-        //创建连接
109
-        Connection connection = RabbitConfig.getConnection();
110
-        //创建消息信道
111
-        Channel channel = connection.createChannel();
112
-        GetResponse groupQueue = channel.basicGet("group_queue", true);
113
-        String groupMessage = new String(groupQueue.getBody());
114
-        GroupLogins groupLogins = JSON.parseObject(groupMessage, GroupLogins.class);
115
-        Long workNumber = groupLogins.getWorkNumber();
116
-
117
-        Map<String, Object> map = new HashMap<>();
118
-        map.put("id", groupLogins.getId());
119
-        map.put("userName", groupLogins.getUserName());
120
-        map.put("workNumber", groupLogins.getWorkNumber());
121
-        map.put("status", groupLogins.getStatus());
122
-        rabbitTemplate.convertAndSend("group_queue", map);
123
-    }
124
-
125
-    @Test
126
-    public void test66() {
127
-        Map<String, Object> map = new HashMap<>();
128
-        map.put("id", "1");
129
-        map.put("type", "1");
130
-        map.put("formUser", "1");
131
-        map.put("appId", "1");
132
-        map.put("openId", "1");
133
-        map.put("sendTime", 1);
134
-        map.put("content", "1");
135
-        rabbitTemplate.convertAndSend("message_queue", map);
136
-    }
137
-
138
-    @Test
139
-    public void Test() {
140
-        WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser("orR6E6l4wDixgeO8iaDetMoeb3hs").content("content").build();
141
-        try {
142
-            wxMpService.getKefuService().sendKefuMessage(message);
143
-        } catch (WxErrorException e) {
144
-            e.printStackTrace();
145
-        }
146
-    }
147
-    @Test
148
-    public void Teswdadt() {
149
-        Set<WebSocketSession> sessions = webSocket.getSessions();
150
-        System.out.println(sessions);
151
-    }
152
-
153
-    @Test
154
-    public void Test2() {
155
-        //String cache = redisHelper.getCache("onLineKefu");
156
-        //JSONObject jsonObject = JSON.parseObject(cache);
157
-        //UserView userView = new UserView();
158
-        List<GroupLogins> groupLoginsList = new ArrayList<>();
159
-        GroupLogins groupLogins = new GroupLogins();
160
-        groupLogins.setWorkNumber(1l);
161
-        groupLogins.setUserName("admin");
162
-        groupLogins.setStatus("0");
163
-        groupLoginsList.add(groupLogins);
164
-        //userView.setGroupLogins(groupLoginsList);
165
-        redisHelper.setCache("onLineKefu", JSON.toJSONString(groupLoginsList));
166
-    }
167
-
168
-    @Test
169
-    public void Test3() {
170
-        String cache = redisHelper.getCache("onLineKefu");
171
-        List<GroupLogins> groupLoginsList = JSON.parseArray(cache, GroupLogins.class);
172
-        System.out.println(groupLoginsList);
173
-        //UserView userView = new UserView();
174
-        GroupLogins groupLogins = new GroupLogins();
175
-        groupLogins.setWorkNumber(2l);
176
-        groupLogins.setUserName("admindd");
177
-        groupLogins.setStatus("0");
178
-        groupLoginsList.add(groupLogins);
179
-        //userView.setGroupLogins(groupLoginsList);
180
-        redisHelper.setCache("onLineKefu", JSON.toJSONString(groupLoginsList));
181
-    }
182
-
183
-    @Test
184
-    public void Tes222t() {
185
-        File file = null;
186
-        try {
187
-            file = wxMpService.getMaterialService().mediaDownload("sFooQ4TojSWPTePnfYo3eQmsJbBU1mdfLAxucQkg5RPaFeQWwcvr19TpCZIHz3lq");
188
-            System.out.println(file);
189
-        } catch (WxErrorException e) {
190
-            e.printStackTrace();
191
-        }
192
-    }
193
-
194
-
195
-    @Test
196
-    public void Tes22222t() {
197
-        File file = null;
198
-        try {
199
-            file = wxMpService.getMaterialService().mediaDownload("sFooQ4TojSWPTePnfYo3eQmsJbBU1mdfLAxucQkg5RPaFeQWwcvr19TpCZIHz3lq");
200
-            System.out.println(file);
201
-        } catch (WxErrorException e) {
202
-            e.printStackTrace();
203
-        }
204
-    }
205
-
206
-    @Test
207
-    public void Tes22222wwt() {
208
-        WxMpConfig wxMpConfig = new WxMpConfig();
209
-        String accessTokenMethod = getAccessTokenMethod(wxMpConfig.wxMpDefaultConfigImpl().getAppId(), wxMpConfig.wxMpDefaultConfigImpl().getSecret());
210
-        System.out.println(accessTokenMethod);
211
-    }
212
-
213
-    @Test
214
-    public void Tes22222222wwt() {
215
-        Object currentUser = RequestContextHolder.getRequestAttributes().getAttribute("CurrentUser", 0);
216
-        System.out.println(currentUser);
217
-    }
218
-
219
-    @Test
220
-    public void Tes22www222wwt() throws IOException {
221
-        WxMpConfig wxMpConfig = new WxMpConfig();
222
-        String accessTokenMethod = getAccessTokenMethod(wxMpConfig.wxMpDefaultConfigImpl().getAppId(), wxMpConfig.wxMpDefaultConfigImpl().getSecret());
223
-        InputStream inputStream = PicDownload.fetchTmpFile("E5Jzo_ybkPFXDHIrCMjubZU8I_47YaUpPoreV7DsBWZHFOmz1sWj9w9X3YO4lB26", "image", accessTokenMethod);
224
-        byte[] flash = new byte[inputStream.available()];
225
-        inputStream.read(flash);
226
-        //二进制转化为图片
227
-        try (FileOutputStream fileOutputStream = new FileOutputStream(new File("C:/Users/2.jpg"));) {
228
-            fileOutputStream.write(flash);
229
-        } catch (IOException e) {
230
-            e.printStackTrace();
231
-        }
232
-    }
233
-
234
-
235
-    /**
236
-     * 获取AccessToken
237
-     *
238
-     * @param appId     填写公众号的appid
239
-     * @param appSecret 填写公众号的开发者密码(AppSecret)
240
-     * @return
241
-     */
242
-    public String getAccessTokenMethod(String appId, String appSecret) {
243
-        try {
244
-            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +
245
-                    appId + "&secret=" + appSecret;
246
-
247
-            StringBuilder json = new StringBuilder();
248
-            URL oracle = new URL(url);
249
-            URLConnection yc = oracle.openConnection();
250
-            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), StandardCharsets.UTF_8));
251
-            String inputLine = null;
252
-            while ((inputLine = in.readLine()) != null) {
253
-                json.append(inputLine);
254
-            }
255
-            in.close();
256
-            JSONObject object = (JSONObject) JSONObject.parse(String.valueOf(json));
257
-            //log.info(title + "==>" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "获取access_token:{}", object.getString("access_token"));
258
-            if (object.getString("access_token") != null) {
259
-
260
-                return object.getString("access_token");
261
-            }
262
-            return null;
263
-
264
-        } catch (Exception e) {
265
-            // log.error("获取accessToken异常" + e.getMessage());
266
-            return null;
267
-        }
268
-    }
269
-
270
-
271
-}

+ 0 - 83
webapidemo-api/src/test/resources/webSecoket.html

@@ -1,83 +0,0 @@
1
-<!DOCTYPE html>
2
-<html>
3
-
4
-<head>
5
-    <meta charset="utf-8">
6
-    <title>Java后端WebSocket的Tomcat实现</title>
7
-    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
8
-</head>
9
-
10
-<body>
11
-<div id="message"></div>
12
-<hr />
13
-<div id="main"></div>
14
-<div id="client"></div>
15
-<input id="text" type="text" />
16
-<button onclick="send()">发送消息</button>
17
-<hr />
18
-<button onclick="closeWebSocket()">关闭WebSocket连接</button>
19
-</body>
20
-<script type="text/javascript">
21
-
22
-    var cid = Math.floor(Math.random() * 100); // 随机生成客户端id
23
-    document.getElementById('client').innerHTML += "客户端 id = " + cid + '<br/>';
24
-
25
-    var websocket = null;
26
-
27
-    //判断当前浏览器是否支持WebSocket
28
-    if ('WebSocket' in window) {
29
-        // 改成你的地址
30
-        websocket = new WebSocket("ws://127.0.0.1:8000/websocket/" + cid);
31
-    } else {
32
-        alert('当前浏览器 Not support websocket')
33
-    }
34
-
35
-    //连接发生错误的回调方法
36
-    websocket.onerror = function () {
37
-        setMessageInnerHTML("websocket.onerror: WebSocket连接发生错误");
38
-    };
39
-
40
-    //连接成功建立的回调方法
41
-    websocket.onopen = function () {
42
-        setMessageInnerHTML("websocket.onopen: WebSocket连接成功");
43
-    }
44
-
45
-    //接收到消息的回调方法
46
-    websocket.onmessage = function (event) {
47
-        setMessageInnerHTML("websocket.onmessage: " + event.data);
48
-    }
49
-
50
-    //连接关闭的回调方法
51
-    websocket.onclose = function () {
52
-        setMessageInnerHTML("websocket.onclose: WebSocket连接关闭");
53
-    }
54
-
55
-    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
56
-    window.onbeforeunload = function () {
57
-        closeWebSocket();
58
-    }
59
-
60
-    //将消息显示在网页上
61
-    function setMessageInnerHTML(innerHTML) {
62
-        document.getElementById('message').innerHTML += innerHTML + '<br/>';
63
-    }
64
-
65
-    //关闭WebSocket连接
66
-    function closeWebSocket() {
67
-        websocket.close();
68
-        alert('websocket.close: 关闭websocket连接')
69
-    }
70
-
71
-    //发送消息
72
-    function send() {
73
-        var message = document.getElementById('text').value;
74
-        try {
75
-            websocket.send('{"msg":"' + message + '"}');
76
-            setMessageInnerHTML("websocket.send: " + message);
77
-        } catch (err) {
78
-            console.error("websocket.send: " + message + " 失败");
79
-        }
80
-    }
81
-</script>
82
-
83
-</html>

+ 4 - 2
webapidemo-service/src/main/java/com/example/service/rabbitmqListener/Consumer.java

@@ -181,7 +181,7 @@ public class Consumer {
181 181
         LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
182 182
         queryWrapper.eq(CustomerInfo::getOpenId, openId);
183 183
 
184
-        if (customerInfoService.getList(queryWrapper) == null) {
184
+        if (customerInfoService.getCount(queryWrapper) == 0) {
185 185
             CustomerInfo customerInfo = new CustomerInfo();
186 186
             customerInfo.setOpenId(openId);
187 187
             customerInfoService.insert(customerInfo);
@@ -331,9 +331,10 @@ public class Consumer {
331 331
             mongoDBMessage.setFromUser(queueMessage.getFormUser());
332 332
             saveMongoDB(queueMessage, mongoDBMessage, queueMessage.getKefuId());
333 333
             String mediaId = queueMessage.getMediaId();
334
+            String content = queueMessage.getContent();
334 335
             String msgType = queueMessage.getMsgType();
335 336
             if ("text".equals(msgType)) {
336
-                WxMpKefuMessage wechatMessage = WxMpKefuMessage.TEXT().toUser(queueMessage.getOpenId()).content(queueMessage.getContent().toString()).build();
337
+                WxMpKefuMessage wechatMessage = WxMpKefuMessage.TEXT().toUser(queueMessage.getOpenId()).content(content).build();
337 338
                 wxMpService.getKefuService().sendKefuMessage(wechatMessage);
338 339
             } else if ("video".equals(msgType)) {
339 340
                 WxMpKefuMessage wechatMessage = WxMpKefuMessage.VIDEO().toUser(queueMessage.getOpenId()).mediaId(mediaId).build();
@@ -345,6 +346,7 @@ public class Consumer {
345 346
                 mongoDBMessage.setPicUrl(queueMessage.getPicUrl());
346 347
             }
347 348
         } catch (Exception e) {
349
+            log.error("微信客服发送消息失败",e);
348 350
             e.printStackTrace();
349 351
         }
350 352
     }

+ 60 - 1
webapidemo-service/src/main/java/com/example/service/webScoket/impl/WebSocketImpl.java

@@ -2,9 +2,17 @@ package com.example.service.webScoket.impl;
2 2
 
3 3
 import com.alibaba.fastjson2.JSON;
4 4
 import com.alibaba.fastjson2.JSONObject;
5
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
6
+import com.example.entity.database.system.User;
7
+import com.example.entity.view.system.GroupLogins;
5 8
 import com.example.entity.view.system.QueueMessage;
9
+import com.example.service.system.IUserService;
6 10
 import com.example.service.webScoket.WebSocket;
11
+import com.example.util.config.RabbitConfig;
7 12
 import com.example.util.helper.RedisHelper;
13
+import com.example.util.helper.SnowFlakeUtil;
14
+import com.rabbitmq.client.Channel;
15
+import com.rabbitmq.client.Connection;
8 16
 import lombok.extern.slf4j.Slf4j;
9 17
 import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
10 18
 import org.apache.tomcat.util.threads.ThreadPoolExecutor;
@@ -38,6 +46,8 @@ public class WebSocketImpl implements WebSocket {
38 46
     private RedisHelper redisHelper;
39 47
     @Autowired
40 48
     private MongoTemplate mongoTemplate;
49
+    @Autowired
50
+    private IUserService userService;
41 51
     /**
42 52
      * 在线连接数(线程安全)
43 53
      */
@@ -61,7 +71,56 @@ public class WebSocketImpl implements WebSocket {
61 71
         int count = connectionCount.decrementAndGet();
62 72
         Map<String, Object> attributes = session.getAttributes();
63 73
         String userId = (String) attributes.get("userId");
64
-        redisHelper.deleteCache(userId);
74
+        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
75
+        qw.eq(User::getUserId, userId);
76
+        User user = userService.getEntity(qw);
77
+        if ("0".equals(user.getIsKefu())) {
78
+//            user.setOnlineType("2");
79
+//            userService.update(user);
80
+            User up=new User();
81
+            up.setOnlineType("2");
82
+            userService.updateBatch(up,qw);
83
+            String queueName = "kefu_" + userId;
84
+            Set<String> keys = redisHelper.getSetKeys(queueName + "*");
85
+            redisHelper.deleteCache(keys);
86
+
87
+            LambdaQueryWrapper<User> online = new LambdaQueryWrapper<>();
88
+            online.eq(User::getIsKefu, "0");
89
+            online.eq(User::getOnlineType, "0");
90
+            List<User> userList = userService.getList(online);
91
+            List<GroupLogins> groupLoginsList = new ArrayList<>();
92
+            SnowFlakeUtil snowFlakeUtil = new SnowFlakeUtil(10, 12);
93
+            Long nextId = snowFlakeUtil.getNextId();
94
+            for (User onlineUser : userList) {
95
+                GroupLogins groupLogins = new GroupLogins();
96
+                groupLogins.setId(nextId);
97
+                groupLogins.setWorkNumber(onlineUser.getUserId());
98
+                groupLogins.setUserName(onlineUser.getUserName());
99
+                groupLogins.setStatus(onlineUser.getStatus());
100
+                groupLoginsList.add(groupLogins);
101
+            }
102
+
103
+            redisHelper.deleteCache("onlineKefu");
104
+            redisHelper.setCache("onlineKefu", JSON.toJSONString(groupLoginsList));
105
+            //创建连接
106
+            Connection connection = RabbitConfig.getConnection();
107
+            //创建消息信道
108
+            Channel channel = null;
109
+            try {
110
+                channel = connection.createChannel();
111
+                channel.queuePurge("group_queue");
112
+            } catch (IOException e) {
113
+                e.printStackTrace();
114
+            }
115
+            for (User onlineUser : userList) {
116
+                Map<String, Object> map = new HashMap<>();
117
+                map.put("id", nextId);
118
+                map.put("workNumber", onlineUser.getUserId());
119
+                map.put("userName", onlineUser.getUserName());
120
+                map.put("status", onlineUser.getStatus());
121
+                rabbitTemplate.convertAndSend("group_queue", map);
122
+            }
123
+        }
65 124
         log.info("a new connection closed,current online count:{}", count);
66 125
     }
67 126
 

+ 13 - 0
webapidemo-util/src/main/java/com/example/util/config/RabbitConfig.java

@@ -17,15 +17,28 @@ import org.springframework.context.annotation.Configuration;
17 17
 public class RabbitConfig {
18 18
 
19 19
     @Value("${spring.rabbitmq.host}")
20
+    private void setHost(String param){
21
+        host=param;
22
+    }
20 23
     private static String host;
21 24
     @Value("${spring.rabbitmq.port}")
25
+    private void setPort(int param){
26
+        port=param;
27
+    }
22 28
     private static int port;
23 29
     @Value("${spring.rabbitmq.username}")
30
+    private void setUsername(String param){
31
+        username=param;
32
+    }
24 33
     private static String username;
25 34
     @Value("${spring.rabbitmq.password}")
35
+    private void setPassword(String param){
36
+        password=param;
37
+    }
26 38
     private static String password;
27 39
 
28 40
     public static Connection getConnection() {
41
+        System.out.println(host);
29 42
         Connection connection = null;
30 43
         try {
31 44
             ConnectionFactory factory = new ConnectionFactory();