1.开启websocket
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Resource
private ElectricRecordHandler electricRecordHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(electricRecordHandler, "/wsElectricRecord")
.setAllowedOrigins("*");
}
}
2.websocket 方法实现
@Component
@Slf4j
public class ElectricRecordHandler extends TextWebSocketHandler {
private static final ConcurrentHashMap<String, WebSocketSession> SESSION_HOLDER = new ConcurrentHashMap<>();
@Resource
private BrpPowerStationService brpPowerStationService;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
TextMessage textMessage = new TextMessage("消息出去了");
session.sendMessage(textMessage);
}
@Override
public void afterConnectionEstablished(@NonNull WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
SESSION_HOLDER.put(session.getId(), session);
if(log.isDebugEnabled()){
log.debug("webSocket already connected:");
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
SESSION_HOLDER.remove(session.getId());
if(log.isDebugEnabled()){
log.debug("webSocket disConnect:");
}
}
public void sendMessage(Object message, String type) {
if(log.isDebugEnabled()){
log.debug("记录进来了:{}",message);
}
if (!CollectionUtils.isEmpty(SESSION_HOLDER)) {
SESSION_HOLDER.values().stream().forEach(session -> {
try {
SocketResult result = new SocketResult();
result.setType(type);
if (Constants.ELECTRIC_RECORD.equals(type)) {
InTheElectricRecord inTheElectricRecord = JsonUtils.convertValue(message, InTheElectricRecord.class);
if(log.isDebugEnabled()){
log.debug("websocket 记录:{}",inTheElectricRecord);
}
ElectricRecord electricRecord = brpPowerStationService.crudAndFunction(brpPowerStationMapper -> {
return brpPowerStationMapper.getPowerStation(inTheElectricRecord.getStationNo());
});
if(UserHolderUtils.isOperator()){
String userId = UserHolderUtils.getUserId();
List<String> listNumber = brpPowerStationService.crudAndFunction(
mapper -> {
return mapper.findNumbersByUserId(userId);
}
);
if(CollectionUtils.isEmpty(listNumber)
|| !listNumber.contains(electricRecord.getNumber())){
electricRecord = null;
}
}
if (electricRecord != null) {
electricRecord.setStopTime(inTheElectricRecord.getStopTime());
electricRecord.setVin(inTheElectricRecord.getVin());
}
result.setContent(electricRecord);
}
TextMessage textMessage = new TextMessage(JsonUtils.objToJsonStr(result));
session.sendMessage(textMessage);
if(log.isDebugEnabled()){
log.debug("推送成功:{}",result.getContent());
}
} catch (IOException e) {
log.error("发送消息失败", e);
}
});
} else {
log.info("session_holder 为空:{}",message);
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
super.handleTransportError(session,throwable);
log.error("webSocket handleTransportError userId :{}",session.getId());
}
}