在Spring Boot项目中使用Java WebSocket
-
添加依赖:在项目的构建文件(如pom.xml
)中添加Java WebSocket的依赖项。可以使用Java EE的WebSocket API或者其他第三方库,例如 Tyrus 或 Jetty WebSocket。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
-
创建WebSocket端点:创建一个类作为WebSocket端点,用于处理WebSocket连接和消息。这个类需要使用 @ServerEndpoint
注解进行标记,并定义相应的处理方法。
@Component
@ServerEndpoint("/ws/{token}")
public class WebSocketServer {
private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class);
/**
* 每个客户端一个token
*/
private String token = "";
private static final HashMap<String, Session> map = new HashMap<>();
/**
* 连接成功
*/
@OnOpen
public void onOpen(Session session, @PathParam("token") String token) {
map.put(token, session);
this.token = token;
LOG.info("有新连接:token:{},session id:{},当前连接数:{}", token, session.getId(), map.size());
}
/**
* 连接关闭
*/
@OnClose
public void onClose(Session session) {
map.remove(this.token);
LOG.info("连接关闭,token:{},session id:{}!当前连接数:{}", this.token, session.getId(), map.size());
}
/**
* 收到消息
*/
@OnMessage
public void onMessage(String message, Session session) {
LOG.info("收到消息:{},内容:{}", token, message);
}
/**
* 连接错误
*/
@OnError
public void onError(Session session, Throwable error) {
LOG.error("发生错误", error);
}
/**
* 群发消息
*/
public void sendInfo(String message) {
for (String token : map.keySet()) {
Session session = map.get(token);
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
LOG.error("推送消息失败:{},内容:{}", token, message);
}
LOG.info("推送消息:{},内容:{}", token, message);
}
}
}
在上面的示例中,使用 @ServerEndpoint("/websocket")
注解标记了WebSocket端点的URL路径。
-
配置WebSocket支持:在Spring Boot应用程序的配置类中,启用WebSocket支持。可以使用@EnableWebSocket
注解或者配置WebSocketConfigurer
来完成。
@Configuration
public class WebSocketConfig {
// ServerEndpointExporter作为一个Bean注册到Spring容器中,它会自动扫描并注册带有@ServerEndpoint注解的WebSocket端点类。
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
这个配置类可以用于将WebSocket端点类自动注册到Spring容器中,而无需手动配置和注册每个WebSocket端点。
-
运行应用程序:启动你的Spring Boot应用程序,WebSocket端点将会被注册,并可用于处理WebSocket连接和消息。
-
调用服务方
public void vote(Long id) {
docMapperCust.increaseVoteCount(id);
String key = RequestContext.getRemoteAddr();
//id+远程ip作为key和value,24小时的有效期
if (redisUtil.validateRepeat("DOC_VOTE" + id + "_" + key, 3600 * 24)) {
docMapperCust.increaseViewCount(id);
} else {
throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
}
//推送消息
Doc docDb = docMapper.selectByPrimaryKey(id);
String logId = MDC.get("LOG_ID");
wsService.sendInfo("【" + docDb.getName() + "】被点赞", logId);
}
@Service
public class WsService {
@Resource
public WebSocketServer webSocketServer;
// 异步调用
@Async
public void sendInfo(String message, String logId) {
MDC.put("LOG_ID", logId);
webSocketServer.sendInfo(message);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)