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;
import java.util.concurrent.ConcurrentHashMap;
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.stereotype.Component;
......@@ -12,38 +16,62 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
*
* @author zhanghj
* @version 1.0.0
* @Title AsyncWebScocketMsgSend.java
* @Package com.glsx.usercenter.component
* @Description TODO 异步websocke消息发送
* @author zhanghj
* @date 2019年8月16日 下午4:11:55
* @version 1.0.0
*/
@Slf4j
@Component
public class AsyncWebScocketMsgSend {
/**
/**
* 群发自定义消息
* @throws EncodeException
* */
*
* @throws EncodeException
*/
@Async
public void sendInfo(JSONArray orderList) {
ConcurrentHashMap<Integer, MyWebSocket> webSocketSet = MyWebSocket.webSocketSet;
for (Map.Entry<Integer, MyWebSocket> param : webSocketSet.entrySet()) {
for (int i = 0; i < orderList.size(); i++) {
try {
JSONObject orderObj = orderList.getJSONObject(i);
Integer managerId = orderObj.getInteger("managerId");
if (param.getKey().equals(managerId)) {
MyWebSocket myWebSocket = param.getValue();
myWebSocket.sendMessage(orderObj);
}
} catch (Exception e) {
continue;
}
}
}
}
public void sendInfo(JSONArray orderList) {
ConcurrentHashMap<Integer, Session> webSocketSet = MyWebSocket.webSocketSet;
for (Map.Entry<Integer, Session> param : webSocketSet.entrySet()) {
for (int i = 0; i < orderList.size(); i++) {
try {
JSONObject orderObj = orderList.getJSONObject(i);
Integer managerId = orderObj.getInteger("managerId");
if (param.getKey().equals(managerId)) {
Session session = param.getValue();
new MyWebSocket().sendMessage(orderObj, session);
}
} catch (Exception e) {
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;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
......@@ -24,66 +18,63 @@ import com.glsx.common.constants.ResultObject;
import com.glsx.usercenter.constants.ResultCodeEnum;
/**
*
* @author zhanghj
* @version 1.0.0
* @Title MyWebSocket.java
* @Package com.glsx.usercenter.component
* @Description TODO websocket的配置
* @author zhanghj
* @date 2019年8月16日 下午2:32:55
* @version 1.0.0
*/
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class MyWebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
public static ConcurrentHashMap<Integer, MyWebSocket> webSocketSet = new ConcurrentHashMap<Integer, MyWebSocket>(16);
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
public static ConcurrentHashMap<Integer, Session> webSocketSet = new ConcurrentHashMap<>(16);
private static Logger log = LoggerFactory.getLogger(MyWebSocket.class);
/**
* 连接建立成功调用的方法*/
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(@PathParam(value="userId") Integer userId,Session session) {
log.info("userId="+userId);
this.session = session;
addWebSocketSet(userId, this);
public void onOpen(@PathParam(value = "userId") Integer userId, Session session) {
log.info("websocket userId=" + userId);
addWebSocketSet(userId, session);
}
private void addWebSocketSet(Integer userId, MyWebSocket myWebSocket) {
// TODO Auto-generated method stub
if (webSocketSet.containsKey(userId)) {
webSocketSet.replace(userId, myWebSocket);
} else {
webSocketSet.put(userId, myWebSocket);
addOnlineCount(); //在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount());
}
}
/**
private void addWebSocketSet(Integer userId, Session session) {
// TODO Auto-generated method stub
if (webSocketSet.containsKey(userId)) {
webSocketSet.replace(userId, session);
} else {
webSocketSet.put(userId, session);
addOnlineCount(); //在线数加1
log.info("websocket 有新连接加入!当前在线人数为" + getOnlineCount());
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam(value="userId") Integer userId) {
public void onClose(@PathParam(value = "userId") Integer userId) {
webSocketSet.remove(userId); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
log.info("websocket 有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) throws Exception {
log.info("websocket 接受到的消息:" + message);
/* this.session = session;
message = "来自客户端的消息:" + message;
log.info(message);
......@@ -96,30 +87,48 @@ public class MyWebSocket {
}*/
//群发消息
// sendInfo("群发消息"+message);
sendMessage(message, session);
}
/**
* 发生错误时调用
@OnError
*
* @OnError
**/
public void onError(Session session, Throwable error) {
log.error("onMessage方法异常"+error.toString());
error.printStackTrace();
}
public void onError(Session session, Throwable error) {
log.error("websocket onMessage方法异常" + error.toString());
error.printStackTrace();
}
/**
* 发送消息需注意方法加锁synchronized,避免阻塞报错
* 注意session.getBasicRemote()与session.getAsyncRemote()的区别
* @param message
* @throws IOException
* @throws EncodeException
*
* @param message 需要发送的消息
* @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 {
//this.session.getBasicRemote().sendText(message);
ResultObject result = new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), message);
this.session.getAsyncRemote().sendText(JSON.toJSONString(result));
}
public synchronized void sendMessage(String 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));
}
public static synchronized int getOnlineCount() {
return onlineCount;
......
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;
import java.util.Map;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
......@@ -35,6 +36,9 @@ public class TestController extends BaseController {
@Autowired
private AsyncWebScocketMsgSend asyncWebScocketMsgSend;
@Autowired
public RedisTemplate redisTemplate;
@RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST})
public ResultObject index(Test test) {
try {
......@@ -67,7 +71,7 @@ public class TestController extends BaseController {
try{
val = PropertiesUtil.getProperty(key);
}catch(Exception e){
}
return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), val);
}*/
......@@ -82,11 +86,18 @@ public class TestController extends BaseController {
logger.info("code=====" + code);
return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), code);
}
@RequestMapping(value = "/testWebsocket", method = {RequestMethod.POST, RequestMethod.GET})
public ResultObject testWebsocket(@RequestBody JSONArray orderList) {
logger.info("测试websocke的msg=====" + JSONObject.toJSONString(orderList));
asyncWebScocketMsgSend.sendInfo(orderList);
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!