(自用)WebSocket创建流程

在Spring Boot项目中新建WebSocket服务,可以按照以下详细步骤进行操作:

1.创建Spring Boot项目

可以通过Spring Initializr(<>)快速创建一个新的Spring Boot项目,添加`Spring Web`和`Spring Boot DevTools`依赖,也可以添加`Lombok`依赖来简化代码。

2.添加WebSocket依赖

在`pom.xml`文件中添加Spring Boot WebSocket相关依赖:

```xml

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-websocket</artifactId>

</dependency>

```

3.配置WebSocket

创建一个配置类来启用WebSocket支持,并定义处理器和拦截器:

```java

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.socket.config.annotation.EnableWebSocket;

import org.springframework.web.socket.config.annotation.WebSocketConfigurer;

import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration

@EnableWebSocket

public class WebSocketConfig implements WebSocketConfigurer {

@Override

public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

registry.addHandler(myHandler(), "/ws").setAllowedOrigins("*");

}

@Bean

public MyWebSocketHandler myHandler() {

return new MyWebSocketHandler();

}

@Bean

public ServletServerContainerFactoryBean createWebSocketContainer() {

ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();

container.setMaxTextMessageBufferSize(8192);

container.setMaxBinaryMessageBufferSize(8192);

return container;

}

}

```

在上述代码中:

• `registerWebSocketHandlers`方法用于注册WebSocket处理器`MyWebSocketHandler`,并指定WebSocket连接的路径为`/ws`,同时允许所有来源的连接(`setAllowedOrigins("*")`)。

• `myHandler`方法返回一个`MyWebSocketHandler`实例,该实例是自定义的WebSocket处理器,用于处理WebSocket连接中的各种事件。

• `createWebSocketContainer`方法用于配置WebSocket容器的一些参数,如最大文本消息缓冲区大小和最大二进制消息缓冲区大小。

4.创建WebSocket处理器

创建`MyWebSocketHandler`类,继承`TextWebSocketHandler`或`WebSocketHandler`,并重写相应方法来处理WebSocket事件:

```java

import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;

import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MyWebSocketHandler extends TextWebSocketHandler {

@Override

public void afterConnectionEstablished(WebSocketSession session) throws Exception {

super.afterConnectionEstablished(session);

System.out.println("连接建立:" + session.getId());

}

@Override

protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

super.handleTextMessage(session, message);

System.out.println("收到消息:" + message.getPayload());

session.sendMessage(new TextMessage("服务器已收到消息:" + message.getPayload()));

}

@Override

public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

super.afterConnectionClosed(session, status);

System.out.println("连接关闭:" + session.getId());

}

}

```

在上述代码中:

• `afterConnectionEstablished`方法在WebSocket连接建立后被调用,可以在这里进行一些初始化操作,如打印连接ID。

• `handleTextMessage`方法用于处理客户端发送的文本消息,可以在这里对消息进行处理,并向客户端发送响应。

• `afterConnectionClosed`方法在WebSocket连接关闭后被调用,可以在这里进行一些清理操作,如打印连接关闭信息。

5.创建控制器(可选)

如果需要通过HTTP接口触发WebSocket消息发送,可以创建一个控制器:

```java

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.messaging.simp.SimpMessagingTemplate;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class WebSocketController {

@Autowired

private SimpMessagingTemplate template;

@GetMapping("/send")

public String send(@RequestParam String message) {

template.convertAndSend("/topic/messages", message);

return "消息已发送";

}

}

```

在上述代码中:

• `SimpMessagingTemplate`用于向指定的WebSocket订阅路径发送消息。

• `send`方法通过`@GetMapping`注解定义了一个HTTP GET接口`/send`,当访问该接口时,会将请求参数`message`作为消息发送到WebSocket订阅路径`/topic/messages`。

6.前端页面测试

创建一个简单的HTML页面来测试WebSocket连接和消息发送:

```html

<!DOCTYPE html>

<html>

<head>

<title>WebSocket Test</title>

<script>

var ws = new WebSocket("ws://localhost:8080/ws");

ws.onopen = function () {

console.log("连接已建立");

};

ws.onmessage = function (event) {

console.log("收到消息:" + event.data);

};

ws.onclose = function () {

console.log("连接已关闭");

};

function sendMessage() {

var message = document.getElementById("message").value;

ws.send(message);

}

</script>

</head>

<body>

<h1>WebSocket Test</h1>

<input type="text" id="message" placeholder="输入消息">

<button οnclick="sendMessage()">发送消息</button>

</body>

</html>

定时器

(定时器)主要使用 @Scheduled 注解

启用定时任务支持 在Spring Boot的主类或配置类上添加 @EnableScheduling 注解,以启用定时任务支持:java复制import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

@EnableScheduling

public class ScheduledTaskApplication {

public static void run(String[] args) {

SpringApplication.run(ScheduledTaskApplication.class, args);

}

}

  1. 定义定时任务 创建一个类,使用 @Scheduled 注解标记需要定时执行的方法。可以指定任务的执行周期(如固定延迟、固定频率或Cron表达式):java复制import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

public class MyScheduledTasks {

// 每5秒执行一次

@Scheduled(fixedRate = 5000)

public void fixedRateTask() {

System.out.println("Fixed Rate Task executed at: " + new java.util.Date());

}

相关推荐
Chan169 小时前
【 Java八股文面试 | JavaSE篇 】
java·jvm·spring boot·面试·java-ee·八股
FG.10 小时前
LangChain4j
java·spring boot·langchain4j
smileNicky13 小时前
SpringBoot系列之集成Pulsar教程
java·spring boot·后端
麦麦大数据13 小时前
J009 美食推荐可视化大数据系统vue+springboot
vue.js·spring boot·mysql·推荐算法·美食·可视化分析·沙箱支付
rfidunion14 小时前
springboot+VUE+部署(1。新建项目)
java·vue.js·spring boot
小翰子_14 小时前
Spring Boot整合Sharding-JDBC实现日志表按月按周分表实战
java·spring boot·后端
千寻技术帮14 小时前
10347_基于Springboot的新疆旅游管理系统
spring boot·mysql·旅游·在线旅游
程序员iteng15 小时前
AI一键图表生成、样式修改的绘图开源工具【easy-draw】
spring boot·开源·node.js
我爱娃哈哈17 小时前
SpringBoot + Seata + Nacos:分布式事务落地实战,订单-库存一致性全解析
spring boot·分布式·后端
麦兜*17 小时前
【springboot】图文详解Spring Boot自动配置原理:为什么@SpringBootApplication是核心?
android·java·spring boot·spring·spring cloud·tomcat