Skip to content

Commit dad0e3f

Browse files
committed
update:重构IP地址下发逻辑
1 parent 32395b9 commit dad0e3f

File tree

7 files changed

+132
-79
lines changed

7 files changed

+132
-79
lines changed

src/main/java/com/xiaozhi/XiaozhiApplication.java

Lines changed: 0 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -27,38 +27,4 @@ public class XiaozhiApplication {
2727
public static void main(String[] args) {
2828
SpringApplication.run(XiaozhiApplication.class, args);
2929
}
30-
31-
@Bean
32-
public ApplicationListener<WebServerInitializedEvent> webServerInitializedListener() {
33-
return event -> {
34-
int port = event.getWebServer().getPort();
35-
String contextPath = event.getApplicationContext().getEnvironment()
36-
.getProperty("server.servlet.context-path", "");
37-
38-
// 获取最适合的服务器IP地址
39-
String serverIp = CmsUtils.getServerIp();
40-
41-
String wsAddress = "ws://" + serverIp + ":" + port + contextPath + WebSocketConfig.WS_PATH;
42-
String otaAddress = "http://" + serverIp + ":" + port + contextPath + "/api/device/ota";
43-
44-
logger.info("==========================================================");
45-
logger.info("🚀 小智物联网平台服务已成功启动");
46-
logger.info("==========================================================");
47-
logger.info("📡 WebSocket服务地址: {}", wsAddress);
48-
logger.info("📦 OTA升级服务地址: {}", otaAddress);
49-
50-
// 输出环境详情调试信息
51-
logger.info("==========================================================");
52-
logger.info("🔍 环境详情调试信息:");
53-
Map<String, Object> envDetails = CmsUtils.getEnvironmentDetails();
54-
for (Map.Entry<String, Object> entry : envDetails.entrySet()) {
55-
logger.info(" {} = {}", entry.getKey(), entry.getValue());
56-
}
57-
58-
logger.info("==========================================================");
59-
logger.info("祝您使用愉快!");
60-
logger.info("==========================================================");
61-
};
62-
}
63-
6430
}

src/main/java/com/xiaozhi/common/config/WebMvcConfig.java

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.xiaozhi.common.interceptor.AuthenticationInterceptor;
44
import com.xiaozhi.common.interceptor.LogInterceptor;
55

6+
import lombok.extern.slf4j.Slf4j;
67
import org.springframework.context.annotation.Configuration;
78
import org.springframework.web.servlet.config.annotation.CorsRegistry;
89
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
@@ -15,6 +16,7 @@
1516
import java.io.File;
1617

1718
@Configuration
19+
@Slf4j
1820
public class WebMvcConfig extends WebMvcConfigurationSupport {
1921

2022
@Resource
@@ -28,13 +30,13 @@ public void addInterceptors(InterceptorRegistry registry) {
2830
registry.addInterceptor(authenticationInterceptor)
2931
.addPathPatterns("/**")
3032
.excludePathPatterns(
31-
"/api/user/login",
32-
"/api/user/register",
33-
"/api/device/ota",
34-
"/audio/**",
35-
"/uploads/**",
36-
"/avatar/**",
37-
"/ws/**"
33+
"/api/user/login",
34+
"/api/user/register",
35+
"/api/device/ota",
36+
"/audio/**",
37+
"/uploads/**",
38+
"/avatar/**",
39+
"/ws/**"
3840
);
3941
}
4042

@@ -61,7 +63,7 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) {
6163

6264
super.addResourceHandlers(registry);
6365
} catch (Exception e) {
64-
e.printStackTrace();
66+
log.error("添加资源失败", e);
6567
}
6668
}
6769

src/main/java/com/xiaozhi/common/interceptor/AuthenticationInterceptor.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
66
import org.springframework.stereotype.Component;
7+
import org.springframework.web.method.HandlerMethod;
78
import org.springframework.web.servlet.HandlerInterceptor;
89

910
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -19,6 +20,7 @@
1920
import jakarta.servlet.http.HttpSession;
2021

2122
import java.io.IOException;
23+
import java.lang.reflect.Method;
2224
import java.util.Arrays;
2325
import java.util.List;
2426

@@ -49,6 +51,12 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
4951
return true;
5052
}
5153

54+
// 检查是否有@@UnLogin注解
55+
if (hasUnLoginAnnotation(handler)) {
56+
logger.debug("接口 {} 标记为不需要登录验证", path);
57+
return true;
58+
}
59+
5260
// 获取会话
5361
HttpSession session = request.getSession(false);
5462
if (session != null) {
@@ -134,4 +142,31 @@ private void handleUnauthorized(HttpServletRequest request, HttpServletResponse
134142
private boolean isPublicPath(String path) {
135143
return PUBLIC_PATHS.stream().anyMatch(path::startsWith);
136144
}
145+
146+
/**
147+
* 检查处理器是否有@UnLogin注解
148+
*/
149+
private boolean hasUnLoginAnnotation(Object handler) {
150+
if (!(handler instanceof HandlerMethod)) {
151+
return false;
152+
}
153+
154+
HandlerMethod handlerMethod = (HandlerMethod) handler;
155+
Method method = handlerMethod.getMethod();
156+
Class<?> controllerClass = handlerMethod.getBeanType();
157+
158+
// 检查方法上是否有@UnLogin注解
159+
UnLogin methodAnnotation = method.getAnnotation(UnLogin.class);
160+
if (methodAnnotation != null && methodAnnotation.value()) {
161+
return true;
162+
}
163+
164+
// 检查类上是否有@UnLogin注解
165+
UnLogin classAnnotation = controllerClass.getAnnotation(UnLogin.class);
166+
if (classAnnotation != null && classAnnotation.value()) {
167+
return true;
168+
}
169+
170+
return false;
171+
}
137172
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.xiaozhi.common.interceptor;
2+
3+
import java.lang.annotation.ElementType;
4+
import java.lang.annotation.Retention;
5+
import java.lang.annotation.RetentionPolicy;
6+
import java.lang.annotation.Target;
7+
8+
/**
9+
* 标记不需要登录验证的接口
10+
* 在控制器方法上使用此注解,可以跳过登录验证
11+
* @author wwtang5
12+
*/
13+
@Target({ElementType.METHOD, ElementType.TYPE})
14+
@Retention(RetentionPolicy.RUNTIME)
15+
public @interface UnLogin {
16+
/**
17+
* 是否跳过登录验证,默认为true
18+
*/
19+
boolean value() default true;
20+
}

src/main/java/com/xiaozhi/communication/server/websocket/WebSocketConfig.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,16 @@
33
import jakarta.annotation.Resource;
44
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
6+
import org.springframework.beans.factory.annotation.Value;
67
import org.springframework.context.annotation.Bean;
78
import org.springframework.context.annotation.Configuration;
89
import org.springframework.web.socket.config.annotation.EnableWebSocket;
910
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
1011
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
1112
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
1213

14+
import com.xiaozhi.utils.CmsUtils;
15+
1316
@Configuration
1417
@EnableWebSocket
1518
public class WebSocketConfig implements WebSocketConfigurer {
@@ -22,11 +25,16 @@ public class WebSocketConfig implements WebSocketConfigurer {
2225
@Resource
2326
private WebSocketHandler webSocketHandler;
2427

28+
@Resource
29+
private CmsUtils cmsUtils;
30+
2531
@Override
2632
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
2733
registry.addHandler(webSocketHandler, WS_PATH)
2834
.setAllowedOrigins("*");
29-
logger.info("WebSocket 处理器注册到路径: {}", WS_PATH);
35+
36+
logger.info("📡 WebSocket服务地址: {}", cmsUtils.getWebsocketAddress());
37+
logger.info("==========================================================");
3038
}
3139

3240
@Bean

src/main/java/com/xiaozhi/controller/DeviceController.java

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
import jakarta.annotation.Resource;
1616
import jakarta.servlet.http.HttpServletRequest;
1717

18-
import org.apache.ibatis.javassist.NotFoundException;
1918
import org.springframework.core.env.Environment;
2019
import org.springframework.http.HttpHeaders;
2120
import org.springframework.http.HttpStatus;
@@ -46,6 +45,9 @@ public class DeviceController extends BaseController {
4645
@Resource
4746
private Environment environment;
4847

48+
@Resource
49+
private CmsUtils cmsUtils;
50+
4951
/**
5052
* 设备查询
5153
*
@@ -219,7 +221,7 @@ public ResponseEntity<byte[]> ota(@RequestHeader("Device-Id") String deviceIdAut
219221
device.setLastLogin(new Date().toString());
220222

221223
// 设置设备IP地址
222-
device.setIp(CmsUtils.getClientIp(request));
224+
device.setIp(cmsUtils.getClientIp(request));
223225

224226
// 查询设备是否已绑定
225227
List<SysDevice> queryDevice = deviceService.query(device, new PageFilter());
@@ -232,14 +234,9 @@ public ResponseEntity<byte[]> ota(@RequestHeader("Device-Id") String deviceIdAut
232234
serverTimeData.put("timestamp", timestamp);
233235
serverTimeData.put("timezone_offset", 480); // 东八区
234236

235-
// 获取服务器IP和端口
236-
String serverIp = CmsUtils.getServerIp();
237-
String portStr = environment.getProperty("server.port");
238-
int port = Integer.parseInt(portStr);
239237
// 设置固件信息
240-
firmwareData.put("url", "http://" + serverIp + ":" + port + request.getContextPath() + "/api/device/ota");
238+
firmwareData.put("url", cmsUtils.getOtaAddress());
241239
firmwareData.put("version", "1.0.0");
242-
243240
// 检查设备是否已绑定
244241
if (ObjectUtils.isEmpty(queryDevice)) {
245242
// 设备未绑定,生成验证码
@@ -264,7 +261,7 @@ public ResponseEntity<byte[]> ota(@RequestHeader("Device-Id") String deviceIdAut
264261
// 设置WebSocket连接信息.
265262
String websocketToken = "";//deviceService.generateToken(deviceId);
266263
Map<String, Object> websocketData = new HashMap<>();
267-
websocketData.put("url", "ws://" + serverIp + ":" + port + "/ws/xiaozhi/v1/");
264+
websocketData.put("url", cmsUtils.getWebsocketAddress());
268265
websocketData.put("token", websocketToken);
269266
responseData.put("websocket", websocketData);
270267

0 commit comments

Comments
 (0)