Commit 36fd2ac7 by yangll

开发审核工单弹框功能

git-svn-id: svn://192.168.3.233/frms/code/car-service/trunk/car-service@33375 aeb6102e-e053-11e5-9fec-f9ebc45caf4b
1 parent d17ecc3c
...@@ -4,7 +4,11 @@ import java.util.Map; ...@@ -4,7 +4,11 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.EncodeException; import javax.websocket.EncodeException;
import javax.websocket.Session;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.connection.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -12,38 +16,62 @@ import com.alibaba.fastjson.JSONArray; ...@@ -12,38 +16,62 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
/** /**
* * @author zhanghj
* @version 1.0.0
* @Title AsyncWebScocketMsgSend.java * @Title AsyncWebScocketMsgSend.java
* @Package com.glsx.usercenter.component * @Package com.glsx.usercenter.component
* @Description TODO 异步websocke消息发送 * @Description TODO 异步websocke消息发送
* @author zhanghj
* @date 2019年8月16日 下午4:11:55 * @date 2019年8月16日 下午4:11:55
* @version 1.0.0
*/ */
@Slf4j
@Component @Component
public class AsyncWebScocketMsgSend { public class AsyncWebScocketMsgSend {
/** /**
* 群发自定义消息 * 群发自定义消息
*
* @throws EncodeException * @throws EncodeException
* */ */
@Async @Async
public void sendInfo(JSONArray orderList) { public void sendInfo(JSONArray orderList) {
ConcurrentHashMap<Integer, MyWebSocket> webSocketSet = MyWebSocket.webSocketSet; ConcurrentHashMap<Integer, Session> webSocketSet = MyWebSocket.webSocketSet;
for (Map.Entry<Integer, MyWebSocket> param : webSocketSet.entrySet()) { for (Map.Entry<Integer, Session> param : webSocketSet.entrySet()) {
for (int i = 0; i < orderList.size(); i++) { for (int i = 0; i < orderList.size(); i++) {
try { try {
JSONObject orderObj = orderList.getJSONObject(i); JSONObject orderObj = orderList.getJSONObject(i);
Integer managerId = orderObj.getInteger("managerId"); Integer managerId = orderObj.getInteger("managerId");
if (param.getKey().equals(managerId)) { if (param.getKey().equals(managerId)) {
MyWebSocket myWebSocket = param.getValue(); Session session = param.getValue();
myWebSocket.sendMessage(orderObj); new MyWebSocket().sendMessage(orderObj, session);
} }
} catch (Exception e) { } catch (Exception e) {
continue; log.error("发送websocket消息异常" + e.getMessage(), e);
} }
} }
} }
} }
/**
* 发送消息
*
* @param message 发送的消息
*/
@Async
public void sendMessage(Message message) {
log.info("开始调用sendMessage:" + message.toString());
ConcurrentHashMap<Integer, Session> webSocketSet = MyWebSocket.webSocketSet;
log.info("webSocketSet:" + JSONUtil.toJsonStr(webSocketSet));
for (Map.Entry<Integer, Session> param : webSocketSet.entrySet()) {
try {
log.info("开始调用websocket:" + message);
// // 获取用户Id 通过用户id判断是否是管理员角色 管理员角色才会推送数据到浏览器
Integer userId = param.getKey();
log.info("sendMessage userId===" + userId);
Session session = param.getValue();
new MyWebSocket().sendMessage(message.toString(), session);
} catch (Exception e) {
log.error("发送websocket消息异常" + e.getMessage(), e);
}
}
}
} }
package com.glsx.usercenter.component; package com.glsx.usercenter.component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.EncodeException;
import javax.websocket.OnClose; import javax.websocket.OnClose;
import javax.websocket.OnMessage; import javax.websocket.OnMessage;
import javax.websocket.OnOpen; import javax.websocket.OnOpen;
...@@ -24,13 +18,12 @@ import com.glsx.common.constants.ResultObject; ...@@ -24,13 +18,12 @@ import com.glsx.common.constants.ResultObject;
import com.glsx.usercenter.constants.ResultCodeEnum; import com.glsx.usercenter.constants.ResultCodeEnum;
/** /**
* * @author zhanghj
* @version 1.0.0
* @Title MyWebSocket.java * @Title MyWebSocket.java
* @Package com.glsx.usercenter.component * @Package com.glsx.usercenter.component
* @Description TODO websocket的配置 * @Description TODO websocket的配置
* @author zhanghj
* @date 2019年8月16日 下午2:32:55 * @date 2019年8月16日 下午2:32:55
* @version 1.0.0
*/ */
@ServerEndpoint(value = "/websocket/{userId}") @ServerEndpoint(value = "/websocket/{userId}")
@Component @Component
...@@ -40,31 +33,27 @@ public class MyWebSocket { ...@@ -40,31 +33,27 @@ public class MyWebSocket {
private static int onlineCount = 0; private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
public static ConcurrentHashMap<Integer, MyWebSocket> webSocketSet = new ConcurrentHashMap<Integer, MyWebSocket>(16); public static ConcurrentHashMap<Integer, Session> webSocketSet = new ConcurrentHashMap<>(16);
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private static Logger log = LoggerFactory.getLogger(MyWebSocket.class); private static Logger log = LoggerFactory.getLogger(MyWebSocket.class);
/** /**
* 连接建立成功调用的方法*/ * 连接建立成功调用的方法
*/
@OnOpen @OnOpen
public void onOpen(@PathParam(value="userId") Integer userId,Session session) { public void onOpen(@PathParam(value = "userId") Integer userId, Session session) {
log.info("userId="+userId); log.info("websocket userId=" + userId);
this.session = session; addWebSocketSet(userId, session);
addWebSocketSet(userId, this);
} }
private void addWebSocketSet(Integer userId, MyWebSocket myWebSocket) { private void addWebSocketSet(Integer userId, Session session) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
if (webSocketSet.containsKey(userId)) { if (webSocketSet.containsKey(userId)) {
webSocketSet.replace(userId, myWebSocket); webSocketSet.replace(userId, session);
} else { } else {
webSocketSet.put(userId, myWebSocket); webSocketSet.put(userId, session);
addOnlineCount(); //在线数加1 addOnlineCount(); //在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount()); log.info("websocket 有新连接加入!当前在线人数为" + getOnlineCount());
} }
} }
...@@ -72,18 +61,20 @@ public class MyWebSocket { ...@@ -72,18 +61,20 @@ public class MyWebSocket {
* 连接关闭调用的方法 * 连接关闭调用的方法
*/ */
@OnClose @OnClose
public void onClose(@PathParam(value="userId") Integer userId) { public void onClose(@PathParam(value = "userId") Integer userId) {
webSocketSet.remove(userId); //从set中删除 webSocketSet.remove(userId); //从set中删除
subOnlineCount(); //在线数减1 subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); log.info("websocket 有一连接关闭!当前在线人数为" + getOnlineCount());
} }
/** /**
* 收到客户端消息后调用的方法 * 收到客户端消息后调用的方法
* *
* @param message 客户端发送过来的消息*/ * @param message 客户端发送过来的消息
*/
@OnMessage @OnMessage
public void onMessage(String message, Session session) throws Exception { public void onMessage(String message, Session session) throws Exception {
log.info("websocket 接受到的消息:" + message);
/* this.session = session; /* this.session = session;
message = "来自客户端的消息:" + message; message = "来自客户端的消息:" + message;
log.info(message); log.info(message);
...@@ -96,14 +87,16 @@ public class MyWebSocket { ...@@ -96,14 +87,16 @@ public class MyWebSocket {
}*/ }*/
//群发消息 //群发消息
// sendInfo("群发消息"+message); // sendInfo("群发消息"+message);
sendMessage(message, session);
} }
/** /**
* 发生错误时调用 * 发生错误时调用
@OnError *
* @OnError
**/ **/
public void onError(Session session, Throwable error) { public void onError(Session session, Throwable error) {
log.error("onMessage方法异常"+error.toString()); log.error("websocket onMessage方法异常" + error.toString());
error.printStackTrace(); error.printStackTrace();
} }
...@@ -111,14 +104,30 @@ public class MyWebSocket { ...@@ -111,14 +104,30 @@ public class MyWebSocket {
/** /**
* 发送消息需注意方法加锁synchronized,避免阻塞报错 * 发送消息需注意方法加锁synchronized,避免阻塞报错
* 注意session.getBasicRemote()与session.getAsyncRemote()的区别 * 注意session.getBasicRemote()与session.getAsyncRemote()的区别
* @param message *
* @throws IOException * @param message 需要发送的消息
* @throws EncodeException * @param session session连接对象
* @throws Exception 异常类
*/
public synchronized void sendMessage(JSONObject message, Session session) throws Exception {
log.info("websocket 开始发送消息:" + message);
// this.session.getBasicRemote().sendText(message);
ResultObject result = new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), message);
session.getAsyncRemote().sendText(JSON.toJSONString(result));
}
/**
* 发送消息重写方法
*
* @param message 发送的消息
* @param session websocket的连接
* @throws Exception
*/ */
public synchronized void sendMessage(JSONObject message) throws IOException, EncodeException { public synchronized void sendMessage(String message, Session session) throws Exception {
//this.session.getBasicRemote().sendText(message); log.info("websocket 开始发送消息:" + message);
// this.session.getBasicRemote().sendText(message);
ResultObject result = new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), message); ResultObject result = new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), message);
this.session.getAsyncRemote().sendText(JSON.toJSONString(result)); session.getAsyncRemote().sendText(JSON.toJSONString(result));
} }
public static synchronized int getOnlineCount() { public static synchronized int getOnlineCount() {
......
package com.glsx.usercenter.component;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* redis 订阅组件
*
* @author Yanglinlong
* @date 2023/1/5 10:19
*/
@Slf4j
@Component
public class RedisReceiveListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] bytes) {
log.info("redis订阅接受的消息:" + message.toString());
AsyncWebScocketMsgSend asyncWebScocketMsgSend = new AsyncWebScocketMsgSend();
asyncWebScocketMsgSend.sendMessage(message);
}
}
package com.glsx.usercenter.config;
import com.glsx.usercenter.component.RedisReceiveListener;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
/**
* @author Yanglinlong
* @date 2023/1/5 10:32
*/
@Configuration
public class ReceiveListenerConfig extends CachingConfigurerSupport {
/**
* 消息监听容器
*
* @param factory
* @return
*/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory factory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);
//订阅一个通道 该处的通道名是发布消息时的名称
container.addMessageListener(catAdapter(), new PatternTopic("websocket-topic"));
return container;
}
/**
* 消息监听适配器,绑定消息处理器
*
* @return
*/
@Bean
MessageListenerAdapter catAdapter() {
return new MessageListenerAdapter(new RedisReceiveListener());
}
}
...@@ -5,6 +5,7 @@ import java.util.List; ...@@ -5,6 +5,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
...@@ -35,6 +36,9 @@ public class TestController extends BaseController { ...@@ -35,6 +36,9 @@ public class TestController extends BaseController {
@Autowired @Autowired
private AsyncWebScocketMsgSend asyncWebScocketMsgSend; private AsyncWebScocketMsgSend asyncWebScocketMsgSend;
@Autowired
public RedisTemplate redisTemplate;
@RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST}) @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST})
public ResultObject index(Test test) { public ResultObject index(Test test) {
try { try {
...@@ -89,4 +93,11 @@ public class TestController extends BaseController { ...@@ -89,4 +93,11 @@ public class TestController extends BaseController {
asyncWebScocketMsgSend.sendInfo(orderList); asyncWebScocketMsgSend.sendInfo(orderList);
return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg()); return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg());
} }
@RequestMapping(value = "/testRedisReceive", method = {RequestMethod.POST, RequestMethod.GET})
public ResultObject testRedisReceive(@RequestParam String message) {
logger.info("测试redis订阅的msg=====" + message);
redisTemplate.convertAndSend("websocket-topic", message);
return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg());
}
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!