封装统一返回结构

master
Gary 1 month ago
parent a70b362410
commit b649967128

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="远程mysql数据库" uuid="8a8ed4eb-9b24-489c-b26e-b4705aafb513">
<driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize>
<imported>true</imported>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://47.122.61.54:3306/?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

@ -0,0 +1 @@
# 解析excel 然后设置定时任务发送给前端消息内容

@ -0,0 +1,20 @@
package com.gary.exercise.config;
import cn.hutool.core.io.resource.ClassPathResource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
*
*/
@Data
@Component
@ConfigurationProperties(prefix ="excel" )
public class FileConfig {
private final String fileName="exercise.xlsx";
private final String sheetNumber="Sheet1";
private final String filePath=new ClassPathResource(fileName).getFile().getAbsolutePath();
}

@ -1,4 +1,5 @@
package com.gary.exercise.config;
import com.gary.exercise.service.ExerciseService;
import com.gary.exercise.socket.ExerciseWebSocketHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
@ -11,10 +12,17 @@ import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private final ExerciseService exerciseService;
public WebSocketConfig(ExerciseService exerciseService) {
this.exerciseService = exerciseService;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 注册 WebSocket 的处理器
registry.addHandler(new ExerciseWebSocketHandler(), "/exercise") // 定义路径 /exercise
registry.addHandler(new ExerciseWebSocketHandler(exerciseService), "/exercise") // 定义路径 /exercise
.setAllowedOrigins("*"); // 设置允许的跨域请求
}
}

@ -1,5 +1,6 @@
package com.gary.exercise.dto;
import cn.hutool.json.JSONUtil;
import lombok.Data;
/**
@ -8,8 +9,6 @@ import lombok.Data;
@Data
public class ActionDto {
private String human;
private String action;
private String description;
}

@ -0,0 +1,19 @@
package com.gary.exercise.dto;
import lombok.Data;
/**
*
*/
@Data
public class GameEvent {
private String classMessage;//节数信息
LeftTime time;//剩余时间
ActionDto lakerActionDto;//湖人队动作
ActionDto wolvesActionDto;//森林狼队动作
}

@ -0,0 +1,20 @@
package com.gary.exercise.dto;
import lombok.Data;
/**
*
*/
@Data
public class Human {
private String name; //姓名
private int points; // 得分
private int rebounds; // 篮板
private int assists; // 助攻
private int blocks; // 盖帽
private int steals; // 抢断
private int fouls; // 犯规
private int twoPoints; // 2分球数
private int threePoints; // 3分球数
private int freeThrows; // 罚球数
}

@ -0,0 +1,13 @@
package com.gary.exercise.dto;
import lombok.Data;
/**
*
*/
@Data
public class LeftTime {
int minute;
int second;
}

@ -0,0 +1,12 @@
package com.gary.exercise.dto;
import lombok.Data;
@Data
public class ScoreDto {
private int laker_score;//湖人对比分
private int wolf_score;//森林狼队比分
}

@ -1,28 +1,26 @@
package com.gary.exercise.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @author Gary
* @date 2024/12/11 4:13
* @description:
*/
public interface ExerciseService {
/**
* Excel List
*
* @param filepath Excel
* @param line 1
* @return List<String>
*0
*/
List<String> readExcelByLine(String filepath, Integer line);
List<String> readRow( int rowIndex) throws IOException;
/**
*excel
*
*/
Map<String, String> getDetailInformation(String filepath, Integer line);
Map<String, String> processRow(int rowIndex) throws IOException;
}

@ -1,56 +1,28 @@
package com.gary.exercise.service.impl;
import com.gary.exercise.config.FileConfig;
import com.gary.exercise.service.ExerciseService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class ExerciseServiceImpl implements ExerciseService {
@Override
public List<String> readExcelByLine(String filepath, Integer line) {
List<String> result = new ArrayList<>();
try{
FileInputStream fis = new FileInputStream(filepath);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheetAt(0);
Row dataRow = sheet.getRow(line - 1); //获取第i行的数据
if (dataRow == null) {
throw new IllegalArgumentException("指定的行不存在或文件为空");
}
for (int i = 0; i < dataRow.getLastCellNum(); i++) {
Cell cell = dataRow.getCell(i);
String cellValue = getCellValue(cell);
result.add(cellValue);
}
} catch (IOException e) {
throw new RuntimeException("读取 Excel 文件失败: " + e.getMessage(), e);
}
return result;
}
@Override
public Map<String, String> getDetailInformation(String filepath, Integer line) {
Map<String,String> result =new HashMap<>();
List<String> readResult= readExcelByLine(filepath, line);//获取读取到的结果
if(readResult.isEmpty()) {
throw new RuntimeException("读取到的结果为空");
}else if(readResult.size()==1){//说明是第一第二节开始的标志
result.put("now_class",readResult.get(0));
}else if(Objects.equals(readResult.get(0), "时间")) {
return null;
}else{
result.put("time",readResult.get(0));//获取当前时间
result.put("laker_action",readResult.get(1));//获取当前湖人队的动作
result.put("score",readResult.get(2));//获取当前比分
result.put("wolf_action",readResult.get(3));//获取当前森林狼队的动作
}
return result;
private final FileConfig fileConfig;
public ExerciseServiceImpl(FileConfig fileConfig) {
this.fileConfig = fileConfig;
}
/**
*
*/
@ -62,7 +34,7 @@ public class ExerciseServiceImpl implements ExerciseService {
case STRING -> cell.getStringCellValue();
case NUMERIC -> {
if (DateUtil.isCellDateFormatted(cell)) {
yield cell.getDateCellValue().toString();
yield new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
}
yield String.valueOf(cell.getNumericCellValue());
}
@ -72,7 +44,48 @@ public class ExerciseServiceImpl implements ExerciseService {
default -> "UNKNOWN";
};
}
/**
* Excel
* @param rowIndex 0
* @return
* @throws IOException
*/
@Override
public List<String> readRow( int rowIndex) throws IOException {
List<String> rowData = new ArrayList<>();
String filePath = fileConfig.getFilePath();
String sheetName = fileConfig.getSheetNumber();
try (FileInputStream fileInputStream = new FileInputStream(new File(filePath));
Workbook workbook = new XSSFWorkbook(fileInputStream)) {
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
throw new IllegalArgumentException("Sheet " + sheetName + " does not exist.");
}
Row row = sheet.getRow(rowIndex);
if (row == null) {
throw new IllegalArgumentException("Row " + rowIndex + " does not exist.");
}
for (Cell cell : row) {
rowData.add(getCellValue(cell));
}
}
return rowData;
}
@Override
public Map<String, String> processRow(int rowIndex) throws IOException{
List<String> rowData = readRow(rowIndex);
return Map.of();
}
}

@ -1,34 +1,90 @@
package com.gary.exercise.socket;
import com.gary.exercise.service.ExerciseService;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class ExerciseWebSocketHandler implements WebSocketHandler {
// 用于存储所有的 WebSocket 会话
private static final Logger log = LoggerFactory.getLogger(ExerciseWebSocketHandler.class);
private final ExerciseService exerciseService;
//存储webSocket的消息对话ID
private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
public ExerciseWebSocketHandler(ExerciseService exerciseService) {
this.exerciseService = exerciseService;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 当连接建立时触发
String sessionId = session.getId();
sessions.put(sessionId, session);
System.out.println("WebSocket连接已建立: " + sessionId);
// 发送欢迎消息
session.sendMessage(new TextMessage("欢迎连接到 WebSocket 服务,您的会话 ID 是: " + sessionId));
}
@Override
public void handleMessage(@NotNull WebSocketSession session, @NotNull WebSocketMessage<?> message) throws Exception {
// 处理接收到的消息
if (message instanceof TextMessage) {
// 接收客户端的消息
String clientMessage = ((TextMessage) message).getPayload();
System.out.println("收到消息: " + clientMessage);
// 回复客户端
session.sendMessage(new TextMessage("服务器收到消息: " + clientMessage));
// 启动一个线程来每秒发送一行数据
new Thread(() -> {
try {
int rowIndex = 0; // 从第 0 行开始
while (true) {
List<String> rowData = exerciseService.readRow(rowIndex); // 读取 Excel 数据
String rowString = String.join(", ", rowData); // 格式化为字符串
session.sendMessage(new TextMessage(rowString)); // 发送给客户端
rowIndex++; // 移动到下一行
Thread.sleep(1000); // 每秒发送一次
// 停止条件:到达 Excel 文件的末尾
if (rowData.isEmpty()) {
session.sendMessage(new TextMessage("已到达文件末尾"));
break;
}
}
} catch (Exception e) {
log.error("发生错误: {}", e.getMessage());
try {
session.sendMessage(new TextMessage("发生错误: " + e.getMessage()));
} catch (IOException ioException) {
log.error("发生错误: {}", e.getMessage());
}
}
}).start();
} else {
System.out.println("不支持的消息类型: " + message.getClass().getName());
}

@ -0,0 +1,15 @@
server:
port: 9090
# 数据库
spring:
datasource:
url: jdbc:mysql://47.122.61.54:3306/nba_visualization?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: GHLgjw168168+
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
max-lifetime: 27000000 # 7.5 小时(毫秒)

Binary file not shown.

@ -1,27 +1,28 @@
package com.gary.exercise;
import cn.hutool.core.io.resource.ClassPathResource;
import com.gary.exercise.service.ExerciseService;
import com.gary.exercise.service.impl.ExerciseServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@SpringBootTest
class ExerciseApplicationTests {
@Test
void contextLoads() {
}
public static void main(String[] args) {
ExerciseService service = new ExerciseServiceImpl();
String filepath = "D:\\data\\coding files\\java\\exercise\\src\\main\\resources\\exercise.xlsx"; // 替换为实际路径
int line = 3; // 读取第2行数据
Map<String,String>result=service.getDetailInformation(filepath,line);
/* List<String> result = service.readExcelByLine(filepath, line);*/
System.out.println("读取结果:"+result);
private final ExerciseService exerciseService;
private final int hang =1;
ExerciseApplicationTests(ExerciseService exerciseService) {
this.exerciseService = exerciseService;
}
public static void main(String[] args) throws IOException {
}
}

@ -0,0 +1,15 @@
server:
port: 9090
# 数据库
spring:
datasource:
url: jdbc:mysql://47.122.61.54:3306/nba_visualization?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: GHLgjw168168+
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
max-lifetime: 27000000 # 7.5 小时(毫秒)

Binary file not shown.
Loading…
Cancel
Save