需求
实现方式
SSE案例(Springboot项目)
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
@RestController
@RequestMapping("/sse")
public class SseController {
@RequestMapping(value = "/get_data", produces = "text/event-stream;charset=UTF-8")
public String push() throws InterruptedException {
Thread.sleep(1000);
return "data:测试数据:" + Math.random() + "\n\n";
}
}
- resource目录下创建public目录,然后创建index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script type="text/javascript">
let source = new EventSource("http://localhost:8080/sse/get_data");
source.addEventListener('message',function (t){
var data = t.data;
document.getElementById("result").innerText = data;
})
source.addEventListener('open', function(e) {
console.log("连接打开.");
}, false);
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("连接关闭");
} else {
console.log(e.readyState);
}
}, false);
script>
head>
<body>
模拟数据:
<div>测试div>
<div id="result">div>
body>
html>
- 创建Application启动类,启动项目
- 浏览器访问: localhost:8080/index.html
WebSocket案例(Springboot项目)
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
dependencies>
- 创建config包,创建WebSocketConfig.java
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 创建server包,创建MysqlSocketServer.java MysqlUtil.java User.java
@ServerEndpoint("/wsMysql")
@Component
public class MysqlSocketServer {
private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
@OnOpen
public void onOpen(Session session) throws IOException {
System.out.println(String.format("Socket Connection onOpen ....%s",Thread.currentThread().getId()));
executor.scheduleAtFixedRate(() -> {
try {
MysqlUtil.pushLog(session);
} catch (IOException e) {
e.printStackTrace();
}
}, 2, 1, TimeUnit.SECONDS);
}
@OnClose
public void onClose(Session session) {
System.out.println(String.format("Socket Connection onClose ..... %s",Thread.currentThread().getId()));
}
@OnError
public void onError(Throwable e) {
System.out.println("Socket Connection onError .....");
e.printStackTrace();
}
}
@Configuration
@EnableScheduling
public class MysqlUtil {
public static List<User> users = new ArrayList<>();
public static void pushLog(Session session) throws IOException {
List<User> users = findAll();
session.getBasicRemote().sendText(JSON.toJSONString(users));
}
private static List<User> findAll() {
return users;
}
static {
int num = (int) (1 + Math.random() * (3 - 1 + 1));
users.add(new User("1", "tom", 12));
users.add(new User("2", "jim", 22));
users.add(new User("3", "jack", 32));
ArrayList<User> rs = new ArrayList<>();
for (int i = 0; i < num; i++) {
rs.add(users.get(i));
}
}
@Scheduled(fixedRate = 2000)
public void configureTasks() throws IOException {
int num = (int) Math.random();
users.add(new User(String.valueOf(num), "name" + num, num * 2));
}
}
public class User {
private String id;
private String name;
private Integer age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
}
- resources目录下创建static目录,创建index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>mysql中获取数据,实时展示title>
head>
<body>
<div id="logContainer" >
div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js">script>
<script>
$(document).ready(function () {
if (typeof (WebSocket) == "undefined") {
console.log("您使用的浏览器不支持WebSocket");
} else {
let socket = new WebSocket("ws://127.0.0.1:7500/wsMysql");
socket.onopen = () => {
console.log("已连接到wsServer");
};
socket.onclose = () => {
console.log("已断开与wsServer的连接");
};
socket.onerror = (e) => {
console.log("发生错误", e);
}
socket.onmessage = function (event) {
console.log("接收到的数据:" + event.data);
document.getElementById("logContainer").innerText = event.data
};
}
});
script>
body>
html>
server:
port: 7500
- 启动服务,访问 localhost:7500/index.html