①Spring Task-------实现系统定时任务
概念:
应用场景:
使用步骤:
实现订单超时和前一天派送中的订单的自动任务处理:
@Component
@Slf4j
public class Mytask {@Autowiredprivate OrderServiceimpl orderServiceimpl;/*** 处理订单超时的任务*/@Scheduled(cron = "0 * * * * ?")//每分钟触发一次public void processTimeoutOrder(){log.info("定时处理超时订单,{}", LocalDateTime.now());//先去数据库中查是否有超时的订单List<Orders> ordersList = orderServiceimpl.query().eq("status", 1).lt("order_time", LocalDateTime.now().plusMinutes(-15)).list();//如果有if(ordersList != null && ordersList.size() > 0){for (Orders orders : ordersList) {//设置订单的取消orders.setStatus(6);orders.setCancelReason("订单超时取消");orders.setCancelTime(LocalDateTime.now());//更新数据库orderServiceimpl.updateById(orders);}}}/*** 处理一直处于派送中状态的订单*/@Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行一次public void processDeliveryOrder(){log.info("处理一直处于派送中状态的订单,{}", LocalDateTime.now());//先去数据库中查是否有前一天还在派送的订单List<Orders> ordersList = orderServiceimpl.query().eq("status", 4).lt("order_time", LocalDateTime.now().plusMinutes(-60)).list();//如果有if(ordersList != null && ordersList.size() > 0){for (Orders orders : ordersList) {//设置订单的取消orders.setStatus(5);//更新数据库orderServiceimpl.updateById(orders);}}}
}
②WebSocket-------实现前后端无请求的数据交互
概念:
应用场景:
使用步骤:
<!-- websocket--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
实现前后端之间长连接的消息互传:
WebSocketServer类:
/*** WebSocket服务*/
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {//存放会话对象private static Map<String, Session> sessionMap = new HashMap();/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam("sid") String sid) {System.out.println("客户端:" + sid + "建立连接");sessionMap.put(sid, session);}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, @PathParam("sid") String sid) {System.out.println("收到来自客户端:" + sid + "的信息:" + message);}/*** 连接关闭调用的方法** @param sid*/@OnClosepublic void onClose(@PathParam("sid") String sid) {System.out.println("连接断开:" + sid);sessionMap.remove(sid);}/*** 群发** @param message*///后端自己调用该方法进行消息的发送public void sendToAllClient(String message) {Collection<Session> sessions = sessionMap.values();for (Session session : sessions) {try {//服务器向客户端发送消息session.getBasicRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}}}
WebSocketConfiguration类:用于配置注册
/*** WebSocket配置类,用于注册WebSocket的Bean*/
@Configuration
public class WebSocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}
前端的实例代码:
<!DOCTYPE HTML>
<html>
<head><meta charset="UTF-8"><title>WebSocket Demo</title>
</head>
<body><input id="text" type="text" /><button onclick="send()">发送消息</button><button onclick="closeWebSocket()">关闭连接</button><div id="message"></div>
</body>
<script type="text/javascript">var websocket = null;var clientId = Math.random().toString(36).substr(2);//判断当前浏览器是否支持WebSocketif('WebSocket' in window){//连接WebSocket节点websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);}else{alert('Not support websocket')}//连接发生错误的回调方法websocket.onerror = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法websocket.onopen = function(){setMessageInnerHTML("连接成功");}//接收到消息的回调方法websocket.onmessage = function(event){setMessageInnerHTML(event.data);}//连接关闭的回调方法websocket.onclose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){document.getElementById('message').innerHTML += innerHTML + '<br/>';}//发送消息function send(){var message = document.getElementById('text').value;websocket.send(message);}//关闭连接function closeWebSocket() {websocket.close();}
</script>
</html>
③Apache POI
第一步:引入依赖
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId></dependency>
第二步:创建并且写入数据
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Springtest {public static void write() throws Exception {//在内存中创建一个Excel文件XSSFWorkbook excel = new XSSFWorkbook();//在Excel中创建一个sheet页XSSFSheet sheet = excel.createSheet("info");//在sheet页中创建行对象XSSFRow row = sheet.createRow(1);//在行上创建单元格,并且写入内容row.createCell(1).setCellValue("姓名");row.createCell(2).setCellValue("城市");List<String> name = new ArrayList<>();name.add("张三");name.add("李四");name.add("王五");List<String> city = new ArrayList<>();city.add("长沙");city.add("武汉");city.add("广州");for(int i=2;i<5;i++){row = sheet.createRow(i);row.createCell(1).setCellValue(name.get(i - 2));row.createCell(2).setCellValue(city.get(i - 2));}//输出流将内存中的Excel文件写入磁盘FileOutputStream fileOutputStream = new FileOutputStream(new File("F:\\info.xlsx"));excel.write(fileOutputStream);//关闭资源fileOutputStream.close();excel.close();}@Testpublic void test() throws Exception {write();}
}
第三步:读取Excel文件并且读入
public static void read() throws Exception {//读取磁盘上已经存在的Excel文件FileInputStream fileInputStream = new FileInputStream(new File("F:\\info.xlsx"));XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);//获取Excel中的sheet页XSSFSheet sheet = excel.getSheet("info");//获取Sheet中的数据的最后一行的行号int lastRowNum = sheet.getLastRowNum();for(int i=1;i<=lastRowNum;i++){XSSFRow row = sheet.getRow(i);String stringCellValue1 = row.getCell(1).getStringCellValue();String stringCellValue2 = row.getCell(2).getStringCellValue();System.out.print("stringCellValue1 = " + stringCellValue1+" ");System.out.println("stringCellValue2 = " + stringCellValue2);}//关闭资源fileInputStream.close();excel.close();}@Testpublic void test01() throws Exception {read();}
OK!到此苍穹外面项目终于结束!!,学到了很多,继续加油!!