Spring Boot笔记-利用Quartz进行定时任务,利用websocket推送到浏览器(界面为thymeleaf)
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot笔记-利用Quartz进行定时任务,利用websocket推送到浏览器(界面为thymeleaf)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
效果如下,瀏覽器輸入URL:
等待一段時間,websocket主動推送
后端打印:
程序結(jié)構(gòu)如下:
QuartzConfig.java
@Configuration public class QuartzConfig {@Beanpublic JobDetail job(){return JobBuilder.newJob(QuartzJob.class).storeDurably().build();}@Beanpublic Trigger trigger(){CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/30 * * * * ?");return TriggerBuilder.newTrigger().forJob(job()).withSchedule(scheduleBuilder).build();} }WebSocketConfig.java
@Component public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();} }MyController.java
@Controller public class MyController {@GetMapping("/")public String test(){return "index";} }QuartzJob.java
public class QuartzJob extends QuartzJobBean {@AutowiredGoodsRepository goodsRepository;@AutowiredWebSocket webSocket;@Overrideprotected 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 {//與某個客戶端連接對話,通過此對客戶端發(fā)送消息private Session session;//存放所有連接的客戶端private static ConcurrentLinkedQueue<WebSocket> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();@OnOpenpublic void onOpen(Session session){//默認客戶端,沒有重名this.session = session;concurrentLinkedQueue.add(this);System.out.println("【webSocket連接成功】當前連接人數(shù)為:" + concurrentLinkedQueue.size());}@OnClosepublic void onClose() {Iterator<WebSocket> iterator = concurrentLinkedQueue.iterator();while (iterator.hasNext()){WebSocket next = iterator.next();if(next == this){concurrentLinkedQueue.remove(next);}}}@OnErrorpublic void onError(Session session, Throwable throwable){System.out.println("error:");throwable.printStackTrace();}@OnMessagepublic 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 socketws = new WebSocket("ws://127.0.0.1:8080/websocket");ws.onmessage = function (evt){let received_msg = evt.data;alert("接收推送數(shù)據(jù):" + received_msg);};ws.onclose = function(){// 關閉 websocketalert("連接已關閉...");};}else{// 瀏覽器不支持 WebSocketalert("瀏覽器不支持 WebSocket!");}}</script></head> <body><h1>推送頁面</h1></body> </html>?
源碼打包下載地址:
https://github.com/fengfanchen/Java/tree/master/QuartzDemo
總結(jié)
以上是生活随笔為你收集整理的Spring Boot笔记-利用Quartz进行定时任务,利用websocket推送到浏览器(界面为thymeleaf)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++笔记-C++11中default及
- 下一篇: 信息安全工程师笔记-网络安全漏洞防护技术