效果如下,浏览器输入URL:
等待一段时间,websocket主动推送
后端打印:
程序结构如下:
QuartzConfig.java
@Configuration
public class QuartzConfig {
@Bean
public JobDetail job(){
return JobBuilder.newJob(QuartzJob.class).storeDurably().build();
}
@Bean
public Trigger trigger(){
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/30 * * * * ?");
return TriggerBuilder.newTrigger()
.forJob(job())
.withSchedule(scheduleBuilder)
.build();
}
}
WebSocketConfig.java
@Component
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
MyController.java
@Controller
public class MyController {
@GetMapping("/")
public String test(){
return "index";
}
}
QuartzJob.java
public class QuartzJob extends QuartzJobBean {
@Autowired
GoodsRepository goodsRepository;
@Autowired
WebSocket webSocket;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String str = "";
for(Goods goods : goodsRepository.getGoodsArrayList()){
str += goods.toString();
}
webSocket.onMessage(str);
}
}
Goods.java
@Data
public class Goods {
Integer id;
String name;
Integer count;
}
GoodsRepository.java
@Repository
public class GoodsRepository {
private static ArrayList<Goods> goodsArrayList = new ArrayList<>();
static {
Goods goods1 = new Goods();
goods1.setId(1);
goods1.setName("石油50L");
goods1.setCount(100);
goodsArrayList.add(goods1);
Goods goods2 = new Goods();
goods2.setId(1);
goods2.setName("石油150L");
goods2.setCount(100);
goodsArrayList.add(goods2);
Goods goods3 = new Goods();
goods3.setId(1);
goods3.setName("石油250L");
goods3.setCount(100);
goodsArrayList.add(goods3);
Goods goods4 = new Goods();
goods4.setId(1);
goods4.setName("石油300L");
goods4.setCount(100);
goodsArrayList.add(goods4);
}
public ArrayList<Goods> getGoodsArrayList(){
return goodsArrayList;
}
}
WebSocket.java
@Component
@ServerEndpoint("/websocket")
public class WebSocket {
//与某个客户端连接对话,通过此对客户端发送消息
private Session session;
//存放所有连接的客户端
private static ConcurrentLinkedQueue<WebSocket> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
@OnOpen
public void onOpen(Session session){
//默认客户端,没有重名
this.session = session;
concurrentLinkedQueue.add(this);
System.out.println("【webSocket连接成功】当前连接人数为:" + concurrentLinkedQueue.size());
}
@OnClose
public void onClose() {
Iterator<WebSocket> iterator = concurrentLinkedQueue.iterator();
while (iterator.hasNext()){
WebSocket next = iterator.next();
if(next == this){
concurrentLinkedQueue.remove(next);
}
}
}
@OnError
public void onError(Session session, Throwable throwable){
System.out.println("error:");
throwable.printStackTrace();
}
@OnMessage
public void onMessage(String message){
Iterator<WebSocket> iterator = concurrentLinkedQueue.iterator();
while (iterator.hasNext()){
WebSocket next = iterator.next();
try {
next.session.getBasicRemote().sendText(message);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
DemoApplication.java
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
let ws = null;
window.onload=function(){
WebSocketTest();
}
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("浏览器支持 WebSocket!");
// 打开一个 web socket
ws = new WebSocket("ws://127.0.0.1:8080/websocket");
ws.onmessage = function (evt)
{
let received_msg = evt.data;
alert("接收推送数据:" + received_msg);
};
ws.onclose = function()
{
// 关闭 websocket
alert("连接已关闭...");
};
}
else
{
// 浏览器不支持 WebSocket
alert("浏览器不支持 WebSocket!");
}
}
</script>
</head>
<body>
<h1>推送页面</h1>
</body>
</html>
源码打包下载地址: