添加Websocket依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
根据@ServerEndpoint注解注册Websocket
java
@Configuration
public class AgentWsConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
创建Websocket注解实现的类@ServerEndpoint注解标记类
java
@ServerEndpoint("/websocket/{sessionId}")
@Component
@Slf4j
public class AgentWsServerPoint {
/**
* websocket连接集合,根据Redis广播来的sessionId,来管理Session(取用和删除)
*/
private static final Map<String, Session> SESSION_MAP = new ConcurrentHashMap<>();
/**
* 建立连接
* @param sessionId
* @param session
*/
@OnOpen
public void onOpen(@PathParam("sessionId") String sessionId, Session session) {
SESSION_MAP.put(sessionId, session);
log.info("WebSocket已打开,会话ID是:{}", sessionId);
log.info(sessionId + "建立了连接");
}
/**
* 接收消息并发送消息
* @param sessionId
* @param message
* @param session
* @return
*/
@OnMessage
public String onMessage(@PathParam(value = "sessionId") String sessionId,String message, Session session) throws Exception {
log.info(sessionId + ":" + message);//客户端推送过来的消息
Session session = SESSION_MAP.get(sessionId);
try {
session.getBasicRemote().sendText("Hello World!"); // 给特定用户发送消息
log.info("消息发送成功");
} catch (IOException e) {
e.printStackTrace();
log.error("消息发送失败");
throw e;
}
return null;
}
/**
* 关闭连接
* @param sessionId
* @param session
*/
@OnClose
public void onClose(@PathParam(value = "sessionId") String sessionId,Session session) throws IOException {
if(SESSION_MAP.containsKey(sessionId)){
Session session1 = SESSION_MAP.get(sessionId);
session1.close();
SESSION_MAP.remove(sessionId);
}
log.info("websocket is close ,session id is {}",sessionId);
}
}