前提须知:websocket基本使用
业务场景,每秒推送统计数据给前端页面,分别显示前天,昨天,今天的前十名客户数据
@ServerEndpoint("/smsMCustomerStaTop10Ws")
定义推送数据给到具体的连接标识import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xyc.monitor.service.SmsMonitorService;
import com.xyc.monitor.service.impl.SmsMonitorServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Top10客户发送量推送
*/
@Component
@ServerEndpoint(value = "/smsMCustomerStaTop10Ws")
public class SmsMCustomerStaTop10Ws {
private static final Logger LOGGER = LoggerFactory.getLogger(SmsMCustomerStaTop10Ws.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的当前对象。
private static Set<SmsMCustomerStaTop10Ws> webSocketSet = new CopyOnWriteArraySet<SmsMCustomerStaTop10Ws>();
private static Map<Session,Integer> map = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//客户端传过来的参数 ,ip:port
private String parameter;
private static SmsMonitorService smsMonitorService;
@Autowired
public void setSmsMonitorService(SmsMonitorService smsMonitorService) {
SmsMCustomerStaTop10Ws.smsMonitorService = smsMonitorService;
}
/**
* 连接建立成功调用的方法
* @param session
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
LOGGER.info("SmsMCustomerStaTop10Ws ===> 有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
map.remove(this.session);
//UDPMsgQueueStatusClient.removeUdpClient(parameter);
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
LOGGER.info("SmsMCustomerStaTop10Ws ===> 有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*
* */
@OnMessage
public void onMessage(String message, Session session) {
//关闭前一个udp
//UDPMsgQueueStatusClient.removeUdpClient(parameter);
//this.parameter = message;
JSONArray objects = JSON.parseArray(message);
//JSONObject jso = JSON.parseObject(message);
Integer status= objects.getJSONObject(0).getInteger("status");
//SmsMonitorServiceImpl.statusSCSSo = status;
map.put(session,status);
LOGGER.info("SmsMCustomerStaTop10Ws ===> 来自客户端的消息:" + message);
}
/**
* 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error) {
LOGGER.info("SmsMCustomerStaTop10Ws 发生错误");
LOGGER.error("onError ===> ", error);
}
/**
* 推送触发
*/
private static void pushTrigger() {
if(SmsMCustomerStaTop10Ws.onlineCount >= 1) {
if(!SmsMonitorServiceImpl.isPushSCS)
SmsMonitorServiceImpl.isPushSCS = true;
smsMonitorService.pushSmsMCustomerStaTop10();
}
if(SmsMCustomerStaTop10Ws.onlineCount == 0) {
SmsMonitorServiceImpl.isPushSCS = false;
}
}
/**
* 发送文本类型消息 192.168.3.146:10086
* @throws IOException
*/
public static void sendInfo(Integer status,Object obj) throws IOException {
for (SmsMCustomerStaTop10Ws item : webSocketSet) {
try {
Session session = item.session;
Integer integer = map.get(session);
if(integer == status){
item.session.getBasicRemote().sendText(JSON.toJSONString(obj));
}else{
continue;
}
} catch (Exception e) {
LOGGER.info("SmsMCustomerStaTop10Ws ===> 发送文本消息错误", e);
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
SmsMCustomerStaTop10Ws.onlineCount++;
pushTrigger();
}
public static synchronized void subOnlineCount() {
SmsMCustomerStaTop10Ws.onlineCount--;
pushTrigger();
}
}
onOpen()
方法最终触发的业务方法smsMonitorService.pushSmsMCustomerStaTop10();
/**
* 记录线程数,保证只创建一个线程
*/
private volatile static int threadCountSCS = 0;
/**
* 数据推送开关,是否推送数据到前端,默认关闭
*/
public static boolean isPushSCS = false;
/**
* 今日1,昨天2,前天3 数据 默认今日
*/
private static ImmutableSet<Integer> statusSCS = ImmutableSet.of(1, 2, 3);
@Override
public void pushSmsMCustomerStaTop10() {
if (threadCountSCS >= 1)
return;
new Thread() {
public void run() {
threadCountSCS++;
Thread.currentThread().setName("pushSmsMCustomerStaTop10-" + threadCountSCS);
System.out.println("top10客户发送量推送服务线程启动");
while (isPushSCS) {
for (Integer statusSC : statusSCS) {
try {
List<SmsMCustomerStaVo> smsMCustomerStaTop10 = smsMonitorMapper.findSmsMCustomerStaTop10(statusSC);
List<SmsMCustomerStaView> smsMCustomerStaViewList = new ArrayList<>();
int i = 1;
for (SmsMCustomerStaVo sm : smsMCustomerStaTop10) {
SmsMCustomerStaView smsMCustomerStaView = new SmsMCustomerStaView();
smsMCustomerStaView.setId(i);
smsMCustomerStaView.setShortName(SmsSymbol.customerMap.get(sm.getCustomerNo()).getShortName());
smsMCustomerStaView.setCustomerName(SmsSymbol.customerMap.get(sm.getCustomerNo()).getName());
smsMCustomerStaView.setSubmitCount(sm.getAllCount());
Integer issueCount = sm.getSendSuccessCount() + sm.getSendFailCount() + sm.getSubmitSuccessCount(); //下发总量 = 总量除开提交失败
smsMCustomerStaView.setIssueCount(issueCount);
//成功率(前30分钟成功率)
Double sendSuccessCountRate = 0D;
if(sm != null && sm.getAllCountThirty() != null && sm.getAllCountThirty() != 0){
sendSuccessCountRate = sm.getSendSuccessCountThirty() / sm.getAllCountThirty().doubleValue();
}
//未知率
Double unknownRateRate = 0D;
if(sm != null && sm.getAllCount() != null && sm.getAllCount() != 0){
//sendSuccessCountRate = sm.getSendSuccessCount() / issueCount.doubleValue(); //发送成功率
unknownRateRate = sm.getSubmitSuccessCount() / sm.getAllCount().doubleValue(); //未知率 = 提交成功 / 提交总量
}
smsMCustomerStaView.setSuccessRate(sendSuccessCountRate == 0 ?"0%":new DecimalFormat("#0.00").format(sendSuccessCountRate * 100) + "%");
smsMCustomerStaView.setUnknownRate(unknownRateRate == 0 ?"0%":new DecimalFormat("#0.00").format(unknownRateRate * 100) + "%");
i++;
smsMCustomerStaViewList.add(smsMCustomerStaView);
}
//List collect = smsMCustomerStaViewList.stream().sorted(Comparator.comparing(SmsMCustomerStaView::getSubmitCount).reversed()).collect(Collectors.toList());
SmsMCustomerStaTop10Ws.sendInfo(statusSC,smsMCustomerStaViewList);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("top10客户发送量推送服务报错",e );
}
}
try {
Thread.sleep(1000);
}catch (Exception e){
System.out.println(e);
}
}
System.out.println("top10客户发送量推送服务线程停止");
threadCountSCS--;
}
}.start();
}
smsMonitorMapper.findSmsMCustomerStaTop10(statusSC);
(传参区分查 前日/昨日/今日
数据)<select id="findSmsMCustomerStaTop10" resultMap="SmsMCustomerStaResultMap">
select t.* from (
SELECT SUM(ALL_COUNT) ALL_COUNT,SUM(SUBMIT_SUCCESS_COUNT) SUBMIT_SUCCESS_COUNT,SUM(SUBMIT_FAIL_COUNT) SUBMIT_FAIL_COUNT,
SUM(SEND_SUCCESS_COUNT) SEND_SUCCESS_COUNT,SUM(SEND_FAIL_COUNT) SEND_FAIL_COUNT,SUM(ALL_COUNT_THIRTY) ALL_COUNT_THIRTY,
SUM(SEND_SUCCESS_COUNT_THIRTY) SEND_SUCCESS_COUNT_THIRTY,CUSTOMER_NO
FROM SMS_M_CUSTOMER_STA
<if test="statusSCS == 1">
WHERE STA_DATE_TIME >= trunc(sysdate)
if>
<if test="statusSCS == 2">
WHERE STA_DATE_TIME >= trunc(sysdate-1) AND STA_DATE_TIME trunc(sysdate)
if>
<if test="statusSCS == 3">
WHERE STA_DATE_TIME >= trunc(sysdate-2) AND STA_DATE_TIME trunc(sysdate-1)
if>
GROUP BY CUSTOMER_NO ORDER BY ALL_COUNT DESC)t where rownum <= 20
select>