[*] 日常优化

This commit is contained in:
acgist
2023-07-21 08:15:34 +08:00
parent eb84cc3d8d
commit 21dfb0df9e
12 changed files with 276 additions and 266 deletions

View File

@@ -17,8 +17,6 @@ import com.acgist.taoyao.boot.model.MessageCodeException;
import com.acgist.taoyao.signal.client.ClientAdapter;
import com.acgist.taoyao.signal.utils.CipherUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
@@ -27,8 +25,6 @@ import lombok.extern.slf4j.Slf4j;
* @author acgist
*/
@Slf4j
@Getter
@Setter
public class SocketClient extends ClientAdapter<AsynchronousSocketChannel> {
/**

View File

@@ -133,7 +133,7 @@ public final class SocketSignalMessageHandler implements CompletionHandler<Integ
final String message = this.decrypt(bytes);
log.debug("Socket信令消息{} - {}", this.channel, message);
// 处理
this.execute(message.strip());
this.execute(message);
}
}
}

View File

@@ -5,8 +5,6 @@ import com.acgist.taoyao.boot.model.Message;
import com.acgist.taoyao.signal.client.ClientAdapter;
import jakarta.websocket.Session;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
@@ -15,32 +13,30 @@ import lombok.extern.slf4j.Slf4j;
* @author acgist
*/
@Slf4j
@Getter
@Setter
public class WebSocketClient extends ClientAdapter<Session> {
public WebSocketClient(long timeout, Session instance) {
super(timeout, instance);
}
@Override
public void push(Message message) {
synchronized (this.instance) {
try {
if(this.instance.isOpen()) {
this.instance.getBasicRemote().sendText(message.toString(), true);
} else {
log.error("WebSocket终端已经关闭{}", this.instance);
}
} catch (Exception e) {
log.error("WebSocket终端发送消息异常{}", message, e);
}
}
}
@Override
protected String getClientIP(Session instance) {
return (String) instance.getUserProperties().get(Constant.IP);
}
public WebSocketClient(long timeout, Session instance) {
super(timeout, instance);
}
@Override
public void push(Message message) {
synchronized (this.instance) {
try {
if(this.instance.isOpen()) {
this.instance.getBasicRemote().sendText(message.toString(), true);
} else {
log.error("WebSocket终端已经关闭{}", this.instance);
}
} catch (Exception e) {
log.error("WebSocket终端发送消息异常{}", message, e);
}
}
}
@Override
protected String getClientIP(Session instance) {
return (String) instance.getUserProperties().get(Constant.IP);
}
}

View File

@@ -23,59 +23,59 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@ServerEndpoint(value = "/websocket.signal", configurator = WebSocketSignalConfigurator.class)
public class WebSocketSignal {
private static ClientManager clientManager;
private static ProtocolManager protocolManager;
private static TaoyaoProperties taoyaoProperties;
private static PlatformErrorProtocol platformErrorProtocol;
@OnOpen
public void open(Session session) {
log.debug("WebSocket信令终端连接成功{}", session);
WebSocketSignal.clientManager.open(new WebSocketClient(WebSocketSignal.taoyaoProperties.getTimeout(), session));
}
@OnMessage
public void message(Session session, String message) {
log.debug("WebSocket信令消息{}-{}", session, message);
try {
WebSocketSignal.protocolManager.execute(message.strip(), session);
} catch (Exception e) {
log.error("处理WebSocket信令消息异常{}-{}", WebSocketSignal.clientManager.clients(session), message, e);
WebSocketSignal.clientManager.push(session, WebSocketSignal.platformErrorProtocol.build(e));
}
}
@OnClose
public void close(Session session) {
log.debug("WebSocket信令终端关闭{}", session);
WebSocketSignal.clientManager.close(session);
}
@OnError
public void error(Session session, Throwable e) {
log.error("WebSocket信令终端异常{}", session, e);
this.close(session);
}
@Autowired
public void setClientManager(ClientManager clientManager) {
WebSocketSignal.clientManager = clientManager;
}
private static ClientManager clientManager;
private static ProtocolManager protocolManager;
private static TaoyaoProperties taoyaoProperties;
private static PlatformErrorProtocol platformErrorProtocol;
@OnOpen
public void open(Session session) {
log.debug("WebSocket信令终端连接成功{}", session);
WebSocketSignal.clientManager.open(new WebSocketClient(WebSocketSignal.taoyaoProperties.getTimeout(), session));
}
@OnMessage
public void message(Session session, String message) {
log.debug("WebSocket信令消息{} - {}", session, message);
try {
WebSocketSignal.protocolManager.execute(message, session);
} catch (Exception e) {
log.error("处理WebSocket信令消息异常{} - {}", WebSocketSignal.clientManager.clients(session), message, e);
WebSocketSignal.clientManager.push(session, WebSocketSignal.platformErrorProtocol.build(e));
}
}
@OnClose
public void close(Session session) {
log.debug("WebSocket信令终端关闭{}", session);
WebSocketSignal.clientManager.close(session);
}
@OnError
public void error(Session session, Throwable e) {
log.error("WebSocket信令终端异常{}", session, e);
WebSocketSignal.clientManager.close(session);
}
@Autowired
public void setClientManager(ClientManager clientManager) {
WebSocketSignal.clientManager = clientManager;
}
@Autowired
public void setProtocolManager(ProtocolManager protocolManager) {
WebSocketSignal.protocolManager = protocolManager;
}
@Autowired
public void setTaoyaoProperties(TaoyaoProperties taoyaoProperties) {
WebSocketSignal.taoyaoProperties = taoyaoProperties;
}
@Autowired
public void setPlatformErrorProtocol(PlatformErrorProtocol platformErrorProtocol) {
WebSocketSignal.platformErrorProtocol = platformErrorProtocol;
}
@Autowired
public void setProtocolManager(ProtocolManager protocolManager) {
WebSocketSignal.protocolManager = protocolManager;
}
@Autowired
public void setTaoyaoProperties(TaoyaoProperties taoyaoProperties) {
WebSocketSignal.taoyaoProperties = taoyaoProperties;
}
@Autowired
public void setPlatformErrorProtocol(PlatformErrorProtocol platformErrorProtocol) {
WebSocketSignal.platformErrorProtocol = platformErrorProtocol;
}
}

View File

@@ -25,7 +25,7 @@ public class WebSocketSignalConfigurator extends ServerEndpointConfig.Configurat
field.setAccessible(true);
config.getUserProperties().put(Constant.IP, ((RequestFacade) field.get(request)).getRemoteAddr());
} catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
throw MessageCodeException.of(e, "无效终端IP" + request);
throw MessageCodeException.of(e, "无效终端IP" + request);
}
super.modifyHandshake(config, request, response);
}

View File

@@ -21,34 +21,34 @@ import com.acgist.taoyao.signal.protocol.system.SystemShutdownProtocol;
@ConditionalOnProperty(prefix = "taoyao.script", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ScriptAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SystemRebootProtocol systemRebootProtocol(ScriptProperties scriptProperties) {
return new SystemRebootProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public SystemShutdownProtocol systemShutdownProtocol(ScriptProperties scriptProperties) {
return new SystemShutdownProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public PlatformRebootProtocol platformRebootProtocol(ScriptProperties scriptProperties) {
return new PlatformRebootProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public PlatformShutdownProtocol platformShutdownProtocol(ScriptProperties scriptProperties) {
return new PlatformShutdownProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public PlatformScriptProtocol platformScriptProtocol() {
return new PlatformScriptProtocol();
}
@Bean
@ConditionalOnMissingBean
public SystemRebootProtocol systemRebootProtocol(ScriptProperties scriptProperties) {
return new SystemRebootProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public SystemShutdownProtocol systemShutdownProtocol(ScriptProperties scriptProperties) {
return new SystemShutdownProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public PlatformRebootProtocol platformRebootProtocol(ScriptProperties scriptProperties) {
return new PlatformRebootProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public PlatformShutdownProtocol platformShutdownProtocol(ScriptProperties scriptProperties) {
return new PlatformShutdownProtocol(scriptProperties);
}
@Bean
@ConditionalOnMissingBean
public PlatformScriptProtocol platformScriptProtocol() {
return new PlatformScriptProtocol();
}
}

View File

@@ -30,53 +30,53 @@ import lombok.extern.slf4j.Slf4j;
@ConditionalOnProperty(prefix = "taoyao.socket", name = "enabled", havingValue = "true", matchIfMissing = true)
public class SocketSignalAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SocketSignal socketSignal(
ClientManager clientManager,
ProtocolManager protocolManager,
SocketProperties socketProperties,
PlatformErrorProtocol platformErrorProtocol
) {
this.buildSecret(socketProperties);
return new SocketSignal(clientManager, protocolManager, socketProperties, platformErrorProtocol);
}
@Bean
@ConditionalOnBean(SocketSignal.class)
public CommandLineRunner socketSignalCommandLineRunner(SocketSignal socketSignal) {
return new OrderedCommandLineRunner() {
@Override
public void run(String ... args) throws Exception {
socketSignal.init();
}
};
}
/**
* @param socketProperties 加密配置
*/
private void buildSecret(SocketProperties socketProperties) {
log.info("Socket信令加密策略{}", socketProperties.getEncrypt());
if(socketProperties.getEncrypt() == null) {
return;
}
if(StringUtils.isNotEmpty(socketProperties.getEncryptSecret())) {
log.info("Socket信令加密密码固定{}", socketProperties.getEncryptSecret());
return;
}
final byte[] bytes = switch (socketProperties.getEncrypt()) {
case AES -> new byte[16];
case DES -> new byte[8];
default -> null;
@Bean
@ConditionalOnMissingBean
public SocketSignal socketSignal(
ClientManager clientManager,
ProtocolManager protocolManager,
SocketProperties socketProperties,
PlatformErrorProtocol platformErrorProtocol
) {
this.buildSecret(socketProperties);
return new SocketSignal(clientManager, protocolManager, socketProperties, platformErrorProtocol);
}
@Bean
@ConditionalOnBean(SocketSignal.class)
public CommandLineRunner socketSignalCommandLineRunner(SocketSignal socketSignal) {
return new OrderedCommandLineRunner() {
@Override
public void run(String ... args) throws Exception {
socketSignal.init();
}
};
if(bytes == null) {
final Random random = new Random();
random.nextBytes(bytes);
socketProperties.setEncryptSecret(Base64.getMimeEncoder().encodeToString(bytes));
log.info("Socket信令加密密码随机{}", socketProperties.getEncryptSecret());
} else {
log.warn("Socket信令加密密码算法不支持的算法{}", socketProperties.getEncrypt());
}
}
}
/**
* @param socketProperties 加密配置
*/
private void buildSecret(SocketProperties socketProperties) {
log.info("Socket信令加密策略{}", socketProperties.getEncrypt());
if(socketProperties.getEncrypt() == null) {
return;
}
if(StringUtils.isNotEmpty(socketProperties.getEncryptSecret())) {
log.info("Socket信令加密密码固定{}", socketProperties.getEncryptSecret());
return;
}
final byte[] bytes = switch (socketProperties.getEncrypt()) {
case AES -> new byte[16];
case DES -> new byte[8];
default -> null;
};
if(bytes == null) {
final Random random = new Random();
random.nextBytes(bytes);
socketProperties.setEncryptSecret(Base64.getMimeEncoder().encodeToString(bytes));
log.info("Socket信令加密密码随机{}", socketProperties.getEncryptSecret());
} else {
log.warn("Socket信令加密密码算法不支持的算法{}", socketProperties.getEncrypt());
}
}

View File

@@ -17,16 +17,16 @@ import com.acgist.taoyao.signal.client.websocket.WebSocketSignal;
@AutoConfiguration
public class WebSocketSignalAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public WebSocketSignal webSocketSignal() {
return new WebSocketSignal();
}
@Bean
@ConditionalOnMissingBean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
@ConditionalOnMissingBean
public WebSocketSignal webSocketSignal() {
return new WebSocketSignal();
}
@Bean
@ConditionalOnMissingBean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

View File

@@ -30,44 +30,44 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class ClientController {
private final ClientManager clientManager;
private final ClientWakeupProtocol clientWakeupProtocol;
private final ClientRebootProtocol clientRebootProtocol;
private final ClientShutdownProtocol clientShutdownProtocol;
private final ClientManager clientManager;
private final ClientWakeupProtocol clientWakeupProtocol;
private final ClientRebootProtocol clientRebootProtocol;
private final ClientShutdownProtocol clientShutdownProtocol;
@Operation(summary = "终端列表", description = "终端列表")
@GetMapping("/list")
@ApiResponse(content = @Content(schema = @Schema(implementation = ClientStatus.class)))
public Message list() {
return Message.success(this.clientManager.status());
}
@Operation(summary = "终端状态", description = "终端状态")
@GetMapping("/status/{clientId}")
@ApiResponse(content = @Content(schema = @Schema(implementation = ClientStatus.class)))
public Message status(@PathVariable String clientId) {
return Message.success(this.clientManager.status(clientId));
}
@Operation(summary = "唤醒终端", description = "唤醒终端")
@GetMapping("/wakeup/{clientId}")
public Message wakeup(@PathVariable String clientId) {
this.clientWakeupProtocol.execute(clientId);
return Message.success();
}
@Operation(summary = "重启终端", description = "重启终端")
@GetMapping("/reboot/{clientId}")
public Message reboot(@PathVariable String clientId) {
this.clientRebootProtocol.execute(clientId);
return Message.success();
}
@GetMapping("/list")
@ApiResponse(content = @Content(schema = @Schema(implementation = ClientStatus.class)))
public Message list() {
return Message.success(this.clientManager.status());
}
@Operation(summary = "终端状态", description = "终端状态")
@GetMapping("/status/{clientId}")
@ApiResponse(content = @Content(schema = @Schema(implementation = ClientStatus.class)))
public Message status(@PathVariable String clientId) {
return Message.success(this.clientManager.status(clientId));
}
@Operation(summary = "唤醒终端", description = "唤醒终端")
@GetMapping("/wakeup/{clientId}")
public Message wakeup(@PathVariable String clientId) {
this.clientWakeupProtocol.execute(clientId);
return Message.success();
}
@Operation(summary = "重启终端", description = "重启终端")
@GetMapping("/reboot/{clientId}")
public Message reboot(@PathVariable String clientId) {
this.clientRebootProtocol.execute(clientId);
return Message.success();
}
@Operation(summary = "关闭终端", description = "关闭终端")
@GetMapping("/shutdown/{clientId}")
public Message shutdown(@PathVariable String clientId) {
this.clientShutdownProtocol.execute(clientId);
return Message.success();
}
@Operation(summary = "关闭终端", description = "关闭终端")
@GetMapping("/shutdown/{clientId}")
public Message shutdown(@PathVariable String clientId) {
this.clientShutdownProtocol.execute(clientId);
return Message.success();
}
}

View File

@@ -41,13 +41,13 @@ public class ProtocolController {
```
{
"code" : "状态编码",
"message": "状态描述",
"header": {
"v": "消息版本",
"id": "消息标识",
"v" : "消息版本",
"id" : "消息标识",
"signal": "信令标识"
},
"code": "状态编码",
"message": "状态描述",
"body": {
...
}
@@ -64,49 +64,60 @@ public class ProtocolController {
...:其他自定义的透传内容
```
> 没有指定消息类型时表示和信令消息类型相同
> 消息类型可以省略表示和前面一致
""");
this.applicationContext.getBeansOfType(Protocol.class).entrySet().stream()
.sorted((a, z) -> a.getValue().signal().compareTo(z.getValue().signal()))
.forEach(e -> {
final String key = e.getKey();
final String key = e.getKey();
final Protocol protocol = e.getValue();
final String name = protocol.name();
final String signal = protocol.signal();
final String name = protocol.name();
final String signal = protocol.signal();
final Class<?> clazz;
final Description description;
if(AopUtils.isAopProxy(e) || AopUtils.isCglibProxy(protocol) || AopUtils.isJdkDynamicProxy(protocol)) {
if(
AopUtils.isAopProxy(e) ||
AopUtils.isCglibProxy(protocol) ||
AopUtils.isJdkDynamicProxy(protocol)
) {
// 代理获取
clazz = AopUtils.getTargetClass(protocol);
description = AnnotationUtils.findAnnotation(clazz, Description.class);
} else {
// 直接获取
clazz = protocol.getClass();
description = AnnotationUtils.findAnnotation(clazz, Description.class);
}
final Description description = AnnotationUtils.findAnnotation(clazz, Description.class);
if(description == null) {
log.info("信令没有注解:{} - {}", key, name);
return;
}
// 信令名称
builder.append("### ").append(name)
.append("").append(signal).append("")
.append(newLine).append(newLine);
builder
.append("### ").append(name)
.append("").append(signal).append("")
.append(newLine).append(newLine);
// 描述信息
final String memo = description.memo().strip();
if(StringUtils.isNotEmpty(memo)) {
builder.append(memo).append(newLine).append(newLine);
builder
.append(memo)
.append(newLine).append(newLine);
}
// 消息主体
builder
.append("```").append(newLine)
.append("# 消息主体").append(newLine);
.append("```")
.append(newLine)
.append("# 消息主体")
.append(newLine);
Stream.of(description.body()).forEach(line -> builder.append(line.strip()).append(newLine));
// 数据流向
builder.append("# 数据流向").append(newLine);
builder
.append("# 数据流向")
.append(newLine);
Stream.of(description.flow()).forEach(line -> builder.append(line.strip()).append(newLine));
builder.append("```").append(newLine).append(newLine);
builder
.append("```")
.append(newLine).append(newLine);
});
return builder.toString();
}

View File

@@ -32,36 +32,36 @@ import lombok.RequiredArgsConstructor;
@RequestMapping("/room")
@RequiredArgsConstructor
public class RoomController {
private final RoomManager roomManager;
private final RoomManager roomManager;
@Operation(summary = "房间信息", description = "房间信息")
@GetMapping("/log")
public Message log() {
this.roomManager.log();
return Message.success();
}
public Message log() {
this.roomManager.log();
return Message.success();
}
@Operation(summary = "房间列表", description = "房间列表")
@GetMapping("/list")
@ApiResponse(content = @Content(schema = @Schema(implementation = RoomStatus.class)))
public Message list() {
return Message.success(this.roomManager.status());
}
@GetMapping("/list")
@ApiResponse(content = @Content(schema = @Schema(implementation = RoomStatus.class)))
public Message list() {
return Message.success(this.roomManager.status());
}
@Operation(summary = "房间状态", description = "房间状态")
@GetMapping("/status/{roomId}")
@ApiResponse(content = @Content(schema = @Schema(implementation = RoomStatus.class)))
public Message status(@PathVariable String roomId) {
return Message.success(this.roomManager.status(roomId));
}
@Operation(summary = "房间终端列表", description = "房间终端列表")
@GetMapping("/list/client/{roomId}")
@ApiResponse(content = @Content(schema = @Schema(implementation = ClientStatus.class)))
public Message listClient(@PathVariable String roomId) {
final Room room = this.roomManager.room(roomId);
return Message.success(room == null ? List.of() : room.clientStatus());
}
@Operation(summary = "房间状态", description = "房间状态")
@GetMapping("/status/{roomId}")
@ApiResponse(content = @Content(schema = @Schema(implementation = RoomStatus.class)))
public Message status(@PathVariable String roomId) {
return Message.success(this.roomManager.status(roomId));
}
@Operation(summary = "房间终端列表", description = "房间终端列表")
@GetMapping("/list/client/{roomId}")
@ApiResponse(content = @Content(schema = @Schema(implementation = ClientStatus.class)))
public Message listClient(@PathVariable String roomId) {
final Room room = this.roomManager.room(roomId);
return Message.success(room == null ? List.of() : room.clientStatus());
}
}

View File

@@ -20,17 +20,17 @@ public class ApplicationEventAdapter extends ApplicationEvent {
private static final long serialVersionUID = 1L;
/**
* 消息
* 信令消息
*/
private final Message message;
/**
* 主体
* 信令主体
*/
private final Map<String, Object> body;
protected ApplicationEventAdapter(Object source, Message message, Map<String, Object> body) {
super(source);
this.body = body;
this.body = body;
this.message = message;
}
@@ -55,6 +55,13 @@ public class ApplicationEventAdapter extends ApplicationEvent {
return MapUtils.getLong(this.body, key);
}
/**
* @see MapUtils#getDouble(Map, String)
*/
public Double getDouble(String key) {
return MapUtils.getDouble(this.body, key);
}
/**
* @see MapUtils#getInteger(Map, String)
*/