修改报警提示信息的数据结构,在报警信息中增加对应的报警提示信息id;删除jackjson的LocalDateTime序列化反序列化配置;修改默认使用fastjson2作为序列化工具,增加fastjson2的全局LocalDateTime序列化反序列化配置

This commit is contained in:
joylink_zhangsai 2023-06-28 16:29:34 +08:00
parent 90340d5897
commit 27af2ab543
22 changed files with 267 additions and 212 deletions

View File

@ -1,5 +1,9 @@
package club.joylink.xiannccda.alert.core;
import club.joylink.xiannccda.alert.xian3.Xian3TrainDelayAlert;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.JSONWriter.Feature;
import com.alibaba.fastjson2.annotation.JSONType;
import java.time.LocalDateTime;
/**

View File

@ -0,0 +1,12 @@
package club.joylink.xiannccda.alert.core;
public enum AlertTipLocationType {
/**
* 全线
*/
QX,
/**
* 鱼化寨联锁区
*/
YHZ_LSQ,
}

View File

@ -0,0 +1,15 @@
package club.joylink.xiannccda.alert.core;
/**
* 报警提示信息的时间范围枚举
*/
public enum AlertTipTimeType {
/**
* 7到9点
*/
CLOCK_7_9,
/**
* 7到9点及19到21点
*/
CLOCK_7_9_AND_19_21,
}

View File

@ -0,0 +1,12 @@
package club.joylink.xiannccda.alert.core;
public enum AlertType {
/**
* 西安三蓝显
*/
XIAN3_BLUE_DISPLAY,
/**
* 西安三列车延误
*/
XIAN3_TRAIN_DELAY,
}

View File

@ -1,34 +1,40 @@
package club.joylink.xiannccda.alert.xian3;
import club.joylink.xiannccda.alert.core.AlertManager;
import club.joylink.xiannccda.alert.core.AlertTipLocationType;
import club.joylink.xiannccda.alert.core.AlertTipTimeType;
import club.joylink.xiannccda.entity.AlertTip;
import club.joylink.xiannccda.event.Listener;
import club.joylink.xiannccda.repository.IAlertTipRepository;
import club.joylink.xiannccda.ws.WsMessageServerManager;
import club.joylink.xiannccda.ws.XianNccAlertMessageServer;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.reader.ObjectReader;
import com.alibaba.fastjson2.util.JodaSupport;
import com.alibaba.fastjson2.writer.ObjectWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.PostConstruct;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandler;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
@Component
public class Xian3AlertJob {
private WsMessageServerManager wsMessageServerManager;
private final IAlertTipRepository alertTipRepository;
@Autowired
public Xian3AlertJob(WsMessageServerManager wsMessageServerManager) {
public Xian3AlertJob(WsMessageServerManager wsMessageServerManager,
IAlertTipRepository alertTipRepository) {
this.wsMessageServerManager = wsMessageServerManager;
this.alertTipRepository = alertTipRepository;
}
@PostConstruct
@ -41,11 +47,25 @@ public class Xian3AlertJob {
alertManager.addTask(new TrainDelayAlertMonitoringTask());
//报警监听
alertManager.on(new Listener<Xian3TrainDelayAlert>() {
private XianNccAlertMessageServer msgServer = xianNccAlertMessageServer;
@Override
public void accept(Xian3TrainDelayAlert event) {
msgServer.addMsg(event);
LambdaQueryWrapper<AlertTip> queryWrapper = Wrappers.lambdaQuery(AlertTip.class);
queryWrapper.eq(AlertTip::getAlertType, event.getAlertType().name())
.eq(AlertTip::getLocationType, AlertTipLocationType.QX.name());
LocalTime start = LocalTime.of(7, 0, 0);
LocalTime end = LocalTime.of(9, 0, 0);
LocalTime now = LocalTime.now();
if (!now.isBefore(start) && !now.isAfter(end)) {
queryWrapper.eq(AlertTip::getTimeType, AlertTipTimeType.CLOCK_7_9.name());
} else {
queryWrapper.isNull(AlertTip::getTimeType);
}
AlertTip alertTip = alertTipRepository.getOne(queryWrapper);
if (alertTip != null) {
event.setAlertTipId(alertTip.getId());
}
xianNccAlertMessageServer.addMsg(event);
}
});

View File

@ -5,16 +5,10 @@ import java.time.LocalDateTime;
import lombok.Data;
/**
* 西安3全线蓝显
* 西安3蓝显
*/
@Data
public class Xian3EntireLineBlueDisplayAlert implements AlertInfo {
/**
* 用于查询该报警的提示信息的code
*/
public static final String TIP_CODE = "xian3_entire_blue_display";
public class Xian3BlueDisplayAlert implements AlertInfo {
private String id;
@Override

View File

@ -1,20 +1,25 @@
package club.joylink.xiannccda.alert.xian3;
import club.joylink.xiannccda.alert.core.AlertInfo;
import club.joylink.xiannccda.alert.core.AlertType;
import java.time.LocalDateTime;
import lombok.Builder;
import lombok.Data;
import lombok.NonNull;
/**
* 西安三号线报警
*/
@Builder
@Data
public class Xian3TrainDelayAlert implements AlertInfo {
@NonNull
private String id;
private String level;
private LocalDateTime alertTime;
private String info;
private Integer alertTipId;
@Override
public String getId() {
@ -35,4 +40,8 @@ public class Xian3TrainDelayAlert implements AlertInfo {
public String getInfo() {
return info;
}
public AlertType getAlertType() {
return AlertType.XIAN3_TRAIN_DELAY;
}
}

View File

@ -0,0 +1,46 @@
package club.joylink.xiannccda.configuration;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.reader.ObjectReader;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import com.alibaba.fastjson2.util.JodaSupport;
import com.alibaba.fastjson2.writer.ObjectWriter;
import jakarta.annotation.PostConstruct;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JsonConfig {
public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
return new HttpMessageConverters(converter);
}
@PostConstruct
public void setLocalDateTimeDeserialization() {
JSON.register(LocalDateTime.class, new ObjectWriter<LocalDateTime>() {
@Override
public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType,
long features) {
jsonWriter.writeString(DATE_TIME_FORMATTER.format((LocalDateTime) object));
}
});
JSON.register(LocalDateTime.class, new ObjectReader<LocalDateTime>() {
@Override
public LocalDateTime readObject(JSONReader jsonReader, Type fieldType, Object fieldName,
long features) {
String str = jsonReader.readString();
return LocalDateTime.parse(str, DATE_TIME_FORMATTER);
}
});
}
}

View File

@ -1,51 +0,0 @@
package club.joylink.xiannccda.configuration;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LocalDateTimeSerializerConfig {
/**
* Date格式化字符串
*/
private static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* DateTime格式化字符串
*/
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* Time格式化字符串
*/
private static final String TIME_FORMAT = "HH:mm:ss";
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
builder.serializerByType(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)));
builder.deserializerByType(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)));
builder.serializerByType(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
builder.deserializerByType(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
builder.serializerByType(LocalTime.class,
new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
builder.deserializerByType(LocalTime.class,
new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
};
}
}

View File

@ -1,21 +1,22 @@
package club.joylink.xiannccda.controller;
import club.joylink.xiannccda.dto.AlertTipDTO;
import club.joylink.xiannccda.dto.AlertTipQueryDTO;
import club.joylink.xiannccda.dto.alertTip.AlertTipQueryDTO;
import club.joylink.xiannccda.dto.alertTip.AlertTipSaveDTO;
import club.joylink.xiannccda.entity.AlertTip;
import club.joylink.xiannccda.exception.BusinessExceptionAssertEnum;
import club.joylink.xiannccda.repository.IAlertTipRepository;
import club.joylink.xiannccda.service.AlertTipService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -32,20 +33,26 @@ import org.springframework.web.bind.annotation.RestController;
public class AlertTipController {
private final IAlertTipRepository alertTipRepository;
private final AlertTipService alertTipService;
public AlertTipController(IAlertTipRepository alertTipRepository) {
public AlertTipController(IAlertTipRepository alertTipRepository,
AlertTipService alertTipService) {
this.alertTipRepository = alertTipRepository;
this.alertTipService = alertTipService;
}
@SecurityRequirement(name = "jwt")
@Operation(summary = "插入报警提示信息")
@PostMapping()
public void insert(AlertTip alertInfo) {
QueryWrapper<AlertTip> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(AlertTip::getCode, alertInfo.getCode());
long count = alertTipRepository.count(queryWrapper);
BusinessExceptionAssertEnum.UNIQUE_FIELD_REPEAT.assertTrue(count == 0, "code重复");
alertTipRepository.save(alertInfo);
public void save(@RequestBody @Validated AlertTipSaveDTO saveDTO) {
alertTipService.save(saveDTO);
}
@SecurityRequirement(name = "jwt")
@Operation(summary = "插入或更新报警提示信息")
@PostMapping("/saveOrUpdate")
public void saveOrUpdate(@RequestBody @Validated AlertTipSaveDTO saveDTO) {
alertTipService.saveOrUpdate(saveDTO);
}
@SecurityRequirement(name = "jwt")
@ -62,14 +69,14 @@ public class AlertTipController {
@GetMapping("/code/{code}")
public AlertTip getByCode(@PathVariable String code) {
QueryWrapper<AlertTip> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(AlertTip::getCode, code);
queryWrapper.lambda().eq(AlertTip::getAlertType, code);
return alertTipRepository.getOne(queryWrapper);
}
@SecurityRequirement(name = "jwt")
@Operation(summary = "根据id更新数据")
@PutMapping("/id")
public void updateById(AlertTip alertTip) {
public void updateById(@RequestBody AlertTip alertTip) {
alertTipRepository.updateById(alertTip);
}

View File

@ -1,11 +0,0 @@
package club.joylink.xiannccda.dto;
import java.util.Map;
import lombok.Data;
@Data
public class AlertTipDTO {
private String code;
private Map<String, Object> info;
}

View File

@ -1,4 +1,4 @@
package club.joylink.xiannccda.dto;
package club.joylink.xiannccda.dto.alertTip;
import club.joylink.xiannccda.entity.AlertTip;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;

View File

@ -0,0 +1,20 @@
package club.joylink.xiannccda.dto.alertTip;
import club.joylink.xiannccda.alert.core.AlertTipLocationType;
import club.joylink.xiannccda.alert.core.AlertTipTimeType;
import club.joylink.xiannccda.alert.core.AlertType;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class AlertTipSaveDTO {
@NotNull(message = "报警类型不能为空")
private AlertType alertType;
private AlertTipTimeType timeType;
private AlertTipLocationType locationType;
private String infoJson;
}

View File

@ -14,7 +14,7 @@ import lombok.experimental.Accessors;
* </p>
*
* @author walker-sheng
* @since 2023-06-21
* @since 2023-06-28
*/
@Getter
@Setter
@ -26,15 +26,25 @@ public class AlertTip {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@Schema(description = "数据在业务中的唯一标识")
private String code;
@Schema(description = "故障类型")
private String alertType;
@Schema(description = "时间定义类型")
private String timeType;
@Schema(description = "地点定义类型")
private String locationType;
@Schema(description = "提示信息的json")
private String infoJson;
public static final String ID = "id";
public static final String CODE = "code";
public static final String ALERT_TYPE = "alert_type";
public static final String TIME_TYPE = "time_type";
public static final String LOCATION_TYPE = "location_type";
public static final String INFO_JSON = "info_json";
}

View File

@ -10,7 +10,7 @@ import org.apache.ibatis.annotations.Mapper;
* </p>
*
* @author walker-sheng
* @since 2023-06-21
* @since 2023-06-28
*/
@Mapper
public interface AlertTipMapper extends BaseMapper<AlertTip> {

View File

@ -5,13 +5,15 @@
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="club.joylink.xiannccda.entity.AlertTip">
<id column="id" property="id" />
<result column="code" property="code" />
<result column="alert_type" property="alertType" />
<result column="time_type" property="timeType" />
<result column="location_type" property="locationType" />
<result column="info_json" property="infoJson" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id, code, info_json
id, alert_type, time_type, location_type, info_json
</sql>
</mapper>

View File

@ -1,6 +1,6 @@
package club.joylink.xiannccda.repository;
import club.joylink.xiannccda.dto.AlertTipQueryDTO;
import club.joylink.xiannccda.dto.alertTip.AlertTipQueryDTO;
import club.joylink.xiannccda.entity.AlertTip;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;

View File

@ -1,20 +1,13 @@
package club.joylink.xiannccda.repository.impl;
import club.joylink.xiannccda.dto.AlertTipDTO;
import club.joylink.xiannccda.dto.AlertTipQueryDTO;
import club.joylink.xiannccda.dto.alertTip.AlertTipQueryDTO;
import club.joylink.xiannccda.entity.AlertTip;
import club.joylink.xiannccda.mapper.AlertTipMapper;
import club.joylink.xiannccda.repository.IAlertTipRepository;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.awt.desktop.QuitEvent;
import java.lang.ProcessHandle.Info;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@ -31,9 +24,8 @@ public class AlertTipRepository extends ServiceImpl<AlertTipMapper, AlertTip> im
@Override
public Page<AlertTip> page(AlertTipQueryDTO queryDTO) {
LambdaQueryWrapper<AlertTip> queryWrapper = Wrappers.lambdaQuery(AlertTip.class);
queryWrapper.select(AlertTip::getCode);
if (StringUtils.hasText(queryDTO.getCode())) {
queryWrapper.eq(AlertTip::getCode, queryDTO.getCode());
queryWrapper.eq(AlertTip::getAlertType, queryDTO.getCode());
}
return page(queryDTO, queryWrapper);
}

View File

@ -0,0 +1,53 @@
package club.joylink.xiannccda.service;
import club.joylink.xiannccda.dto.alertTip.AlertTipSaveDTO;
import club.joylink.xiannccda.entity.AlertTip;
import club.joylink.xiannccda.exception.BusinessExceptionAssertEnum;
import club.joylink.xiannccda.repository.IAlertTipRepository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
@Service
public class AlertTipService {
private final IAlertTipRepository alertTipRepository;
public AlertTipService(IAlertTipRepository alertTipRepository) {
this.alertTipRepository = alertTipRepository;
}
public void save(AlertTipSaveDTO saveDTO) {
AlertTip saveEntity = convertToEntity(saveDTO);
LambdaQueryWrapper<AlertTip> queryWrapper = Wrappers.lambdaQuery(AlertTip.class);
queryWrapper.eq(AlertTip::getAlertType, saveEntity.getAlertType())
.eq(AlertTip::getTimeType, saveEntity.getTimeType())
.eq(AlertTip::getLocationType, saveEntity.getLocationType());
long count = alertTipRepository.count(queryWrapper);
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertTrue(count == 0,
"相同报警类型、时间范围、地点范围的提示信息已存在");
alertTipRepository.save(saveEntity);
}
public void saveOrUpdate(AlertTipSaveDTO saveDTO) {
AlertTip saveEntity = convertToEntity(saveDTO);
LambdaUpdateWrapper<AlertTip> updateWrapper = Wrappers.lambdaUpdate(AlertTip.class);
updateWrapper.eq(AlertTip::getAlertType, saveEntity.getAlertType())
.eq(AlertTip::getTimeType, saveEntity.getTimeType())
.eq(AlertTip::getLocationType, saveEntity.getLocationType());
alertTipRepository.saveOrUpdate(saveEntity, updateWrapper);
}
private AlertTip convertToEntity(AlertTipSaveDTO saveDTO) {
AlertTip entity = new AlertTip();
entity.setAlertType(saveDTO.getAlertType().name());
if (saveDTO.getTimeType() != null) {
entity.setTimeType(saveDTO.getTimeType().name());
}
if (saveDTO.getLocationType() != null) {
entity.setLocationType(saveDTO.getLocationType().name());
}
entity.setInfoJson(saveDTO.getInfoJson());
return entity;
}
}

View File

@ -1,79 +0,0 @@
package club.joylink.xiannccda.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
public class JsonUtils {
public static ObjectMapper objectMapper;
public static ObjectMapper objectNullableMapper;
static {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
builder
.simpleDateFormat("yyyy-MM-dd HH:mm:ss") // 格式化日期
.timeZone("GMT+8") // 设置时区
.failOnUnknownProperties(false) // 未知属性不抛出异常
.serializationInclusion(JsonInclude.Include.NON_NULL) // 忽略null属性
;
objectMapper = builder.build();
Jackson2ObjectMapperBuilder nullableBuilder = Jackson2ObjectMapperBuilder.json();
nullableBuilder
.simpleDateFormat("yyyy-MM-dd HH:mm:ss") // 格式化日期
.timeZone("GMT+8") // 设置时区
.failOnUnknownProperties(false) // 未知属性不抛出异常
;
objectNullableMapper = nullableBuilder.build();
}
public static String writeValueNullableFieldAsString(Object value) {
try {
return objectNullableMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new RuntimeException("Json write value as String exception", e);
}
}
public static String writeValueAsString(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new RuntimeException("Json write value as String exception", e);
}
}
public static <T> T read(String text, Class<T> valueType) {
try {
return objectMapper.readValue(text, valueType);
} catch (IOException e) {
throw new RuntimeException("Json read String to Object exception", e);
}
}
public static <T> T read(String text, JavaType valueType) {
try {
return objectMapper.readValue(text, valueType);
} catch (IOException e) {
throw new RuntimeException("Json read String to Object exception", e);
}
}
public static <T> T readCollection(String text, Class<?> collectionClass, Class<?>... elementClasses) {
try {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
return objectMapper.readValue(text, javaType);
} catch (IOException e) {
throw new RuntimeException("Json read String to Object Collection exception", e);
}
}
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
}

View File

@ -1,7 +1,8 @@
package club.joylink.xiannccda.ws;
import club.joylink.xiannccda.alert.core.AlertInfo;
import club.joylink.xiannccda.util.JsonUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter.Feature;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@ -25,7 +26,7 @@ public class XianNccAlertMessageServer implements IMessageServer {
@Override
public Object onSubscription(String destination, Map<String, String> paramMap) {
return JsonUtils.writeValueAsString(allMsg.values());
return allMsg.values();
}
@Override

View File

@ -1,8 +1,13 @@
package club.joylink.xiannccda;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import com.alibaba.fastjson2.support.spring6.messaging.converter.MappingFastJsonMessageConverter;
import com.alibaba.fastjson2.support.spring6.websocket.sockjs.FastjsonSockJsMessageCodec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import lombok.NonNull;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.converter.GenericMessageConverter;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
@ -12,6 +17,7 @@ import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
@ -27,7 +33,7 @@ public class WebSocketTest {
@Test
public void testWebSocketSubscription() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(new StandardWebSocketClient());
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
stompClient.setMessageConverter(new MappingFastJsonMessageConverter());
String webSocketUrl = "ws://localhost:9081/ws-default";
CountDownLatch latch = new CountDownLatch(1);
@ -36,11 +42,6 @@ public class WebSocketTest {
headers.set("Authorization", "Bearer YourAccessTokenHere");
StompSessionHandlerAdapter sessionHandler = new StompSessionHandlerAdapter() {
@Override
public Type getPayloadType(StompHeaders headers) {
return String.class;
}
@Override
public void handleException(StompSession session, StompCommand command, StompHeaders headers,
byte[] payload, Throwable exception) {
@ -58,16 +59,14 @@ public class WebSocketTest {
@Override
public void handleFrame(StompHeaders headers, Object payload) {
String msg = new String((byte[]) payload, StandardCharsets.UTF_8);
System.out.println(msg);
String message = new String((byte[]) payload, StandardCharsets.UTF_8);
System.out.println("Received message: " + message);
}
});
}
};
StompHeaders connectHeaders = new StompHeaders();
connectHeaders.add("tokenGroup", "192:168:99:3::DEMO");
stompClient.connectAsync(webSocketUrl, headers, sessionHandler);
stompClient.connectAsync(webSocketUrl, sessionHandler);
assertTrue(latch.await(20, TimeUnit.SECONDS));
}