完成客户端注册操作

This commit is contained in:
柏码の讲师 2023-12-07 17:31:14 +08:00
parent 136a208603
commit 5a6db11a3a
9 changed files with 167 additions and 1 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.idea
log
.DS_Store
config

View File

@ -32,6 +32,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.37</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,73 @@
package com.example.config;
import com.alibaba.fastjson2.JSONObject;
import com.example.entity.ConnectionConfig;
import com.example.utils.NetUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
@Slf4j
@Configuration
public class ServerConfiguration {
@Resource
NetUtils net;
@Bean
ConnectionConfig connectionConfig() {
log.info("正在加载服务端连接配置...");
ConnectionConfig config = this.readConfigurationFromFile();
if(config == null)
config = this.registerToServer();
return config;
}
private ConnectionConfig registerToServer() {
Scanner scanner = new Scanner(System.in);
String token, address;
do {
log.info("请输入需要注册的服务端访问地址,地址类似于 'http://192.168.0.22:8080' 这种写法:");
address = scanner.nextLine();
log.info("请输入服务端生成的用于注册客户端的Token秘钥:");
token = scanner.nextLine();
} while (!net.registerToServer(address, token));
ConnectionConfig config = new ConnectionConfig(address, token);
this.saveConfigurationToFile(config);
return config;
}
private void saveConfigurationToFile(ConnectionConfig config) {
File dir = new File("config");
if(!dir.exists() && dir.mkdir())
log.info("创建用于保存服务端连接信息的目录已完成");
File file = new File("config/server.json");
try(FileWriter writer = new FileWriter(file)) {
writer.write(JSONObject.from(config).toJSONString());
} catch (IOException e) {
log.error("保存配置文件时出现问题", e);
}
log.info("服务端连接信息已保存成功!");
}
private ConnectionConfig readConfigurationFromFile() {
File configurationFile = new File("config/server.json");
if(configurationFile.exists()) {
try (FileInputStream stream = new FileInputStream(configurationFile)){
String raw = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
return JSONObject.parseObject(raw).to(ConnectionConfig.class);
} catch (IOException e) {
log.error("读取配置文件时出错", e);
}
}
return null;
}
}

View File

@ -0,0 +1,11 @@
package com.example.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class ConnectionConfig {
String address;
String token;
}

View File

@ -0,0 +1,22 @@
package com.example.entity;
import com.alibaba.fastjson2.JSONObject;
public record Response(int id, int code, Object data, String message) {
public boolean success() {
return code == 200;
}
public JSONObject asJson() {
return JSONObject.from(data);
}
public String asString() {
return data.toString();
}
public static Response errorResponse(Exception e) {
return new Response(0, 500, null, e.getMessage());
}
}

View File

@ -0,0 +1,53 @@
package com.example.utils;
import com.alibaba.fastjson2.JSONObject;
import com.example.entity.ConnectionConfig;
import com.example.entity.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
@Slf4j
@Component
public class NetUtils {
private final HttpClient client = HttpClient.newHttpClient();
@Lazy
@Resource
ConnectionConfig config;
public boolean registerToServer(String address, String token) {
log.info("正在像服务端注册,请稍后...");
Response response = this.doGet("/register", address, token);
if(response.success()) {
log.info("客户端注册已完成!");
} else {
log.error("客户端注册失败: {}", response.message());
}
return response.success();
}
private Response doGet(String url) {
return this.doGet(url, config.getAddress(), config.getToken());
}
private Response doGet(String url, String address, String token) {
try {
HttpRequest request = HttpRequest.newBuilder().GET()
.uri(new URI(address + "/monitor" + url))
.header("Authorization", token)
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return JSONObject.parseObject(response.body()).to(Response.class);
} catch (Exception e) {
log.error("在发起服务端请求时出现问题", e);
return Response.errorResponse(e);
}
}
}

View File

@ -70,6 +70,7 @@ public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> impleme
StringBuilder sb = new StringBuilder(24);
for (int i = 0; i < 24; i++)
sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
System.out.println(sb);
return sb.toString();
}
}

View File

@ -14,7 +14,7 @@ spring:
password: admin
virtual-host: /
datasource:
url: jdbc:mysql://localhost:3306/test
url: jdbc:mysql://localhost:3306/monitor
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver