1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、新建webSocket配置
@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter类的作用是,会扫描所有的服务器端点,
* 把带有@ServerEndpoint 注解的所有类都添加进来
*
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3、创建一个处理消息类
@Component
@ServerEndpoint("/webSocket/{uId}")
@Slf4j
public class WebSocketServerUtil {
public static ReviewService xxService;
@Autowired
public void setXxService(ReviewService xxService){
WebSocketServerUtil.xxService = xxService;
}
private Session session;
private static CopyOnWriteArraySet<WebSocketServerUtil > webSocketSet = new CopyOnWriteArraySet<>();
private static ConcurrentHashMap<Long,WebSocketServerUtil > webSocketMap = new ConcurrentHashMap<>();
private Long uId = null;
@OnOpen
public void onOpen(Session session, @PathParam("uId") Long uId){
this.session = session;
this.uId = uId;
if(webSocketMap .containsKey(uId)){
webSocketMap .remove(uId);
webSocketMap .put(uId,this);
}else{
webSocketMap .put(uId,this);
webSocketSet.add(this);
}
log.info("【websocket消息】有新的连接,总数:{}",webSocketMap.size());
}
@OnClose
public void onClose(){
if(webSocketMap.containsKey(uId)){
webSocketMap.remove(uId);
//从set中删除
webSocketSet.remove(this);
}
log.info("【websocket消息】连接断开,总数:{}",webSocketSet.size());
}
@OnMessage
public void onMessage(String message) {
log.info("【websocket消息】收到客户端发来的消息:{}", message);
Map msgMap = new HashMap();
Result reviewList = xxService.getReviewList();
if (reviewList == null) {
msgMap.put("step", 0);
msgMap.put("msg", "没有");
} else {
msgMap.put("step", 1);
msgMap.put("msg", reviewList.getData());
}
try {
WebSocketServerUtil.sendInfo(JSONUtil.toJsonStr(msgMap), uId);
//log.info(msgMap.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void sendMessage(String message){
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发送自定义消息
* */
public static void sendInfo(String message,Long uId) throws Exception {
log.info("发送消息到:"+uId+",报文:"+message);
if(webSocketMap.containsKey(uId)){
webSocketMap.get(uId).sendMessage(message);
}else{
log.error("用户"+uId+",不在线!");
throw new Exception("连接已关闭,请刷新页面后重试");
}
}
}