springboot Socket 断网重启 demo
时间: 2023-09-17 09:15:07 浏览: 106
springboot demo
5星 · 资源好评率100%
这里是一个简单的 Spring Boot Socket 断网重启的示例:
首先,定义一个 Socket 服务类:
```java
@Component
public class SocketServer {
private ServerSocket serverSocket;
private ExecutorService executorService;
private volatile boolean isRunning = true;
public void start(int port) {
executorService = Executors.newFixedThreadPool(10);
try {
serverSocket = new ServerSocket(port);
while (isRunning) {
Socket socket = serverSocket.accept();
executorService.submit(new SocketHandler(socket));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
executorService.shutdown();
}
}
public void stop() {
isRunning = false;
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
然后,定义一个 Socket 处理类:
```java
public class SocketHandler implements Runnable {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = reader.readLine()) != null) {
// 处理消息
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
最后,在 Spring Boot 启动类中创建 SocketServer 实例并启动服务:
```java
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
SocketServer socketServer = new SocketServer();
socketServer.start(8888);
}
}
```
如果需要实现断网重启功能,可以使用 Spring Boot 的 @Scheduled 注解和一个定时任务来检测服务是否可用:
```java
@Component
public class SocketCheckTask {
@Autowired
private SocketServer socketServer;
@Scheduled(fixedDelay = 5000)
public void check() {
try {
Socket socket = new Socket("localhost", 8888);
socket.close();
} catch (IOException e) {
// 发生异常,说明服务不可用,重启服务
socketServer.stop();
socketServer.start(8888);
}
}
}
```
上述代码中,定时任务每隔 5 秒钟检测一次 Socket 服务是否可用,如果发生异常,则说明服务不可用,需要先停止服务,然后再重新启动服务。
阅读全文