Java案例如何实现服务启动?

wen python案例 2

本文目录导读:

Java案例如何实现服务启动?

  1. 基于 Spring Boot 的 Web 服务启动
  2. 使用 Apache Commons Daemon 实现系统服务
  3. 使用 Java 内置的 ServerSocket 实现简单 TCP 服务
  4. 使用 ScheduledExecutorService 实现定时任务服务
  5. 使用 Spring Boot + @Scheduled 启动定时服务
  6. 启动流程图(以 Spring Boot 为例)
  7. 总结对比

基于 Spring Boot 的 Web 服务启动

这是目前最常用的一种,适合构建 RESTful API 或微服务。

1 主启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2 启动后执行的业务(可选)

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class StartupRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("服务启动完成,执行初始化任务...");
        // 加载缓存、启动定时任务等
    }
}

优点:内嵌Tomcat/Jetty,自动配置,开发者只需要关注业务代码。


使用 Apache Commons Daemon 实现系统服务

适用于需要注册为 Windows 服务或 Linux Systemd 服务的场景。

1 主服务类

public class MyService {
    public static void main(String[] args) {
        // 启动服务逻辑
        System.out.println("服务已启动");
        // ... 业务代码
    }
}

2 使用 commons-daemon 包装

import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
public class MyDaemon implements Daemon {
    private Thread serverThread;
    @Override
    public void init(DaemonContext context) throws Exception {
        System.out.println("初始化服务");
    }
    @Override
    public void start() throws Exception {
        serverThread = new Thread(() -> {
            // 服务主循环
            while (!Thread.currentThread().isInterrupted()) {
                // 处理请求
            }
        });
        serverThread.start();
    }
    @Override
    public void stop() throws Exception {
        serverThread.interrupt();
    }
    @Override
    public void destroy() { }
}

然后使用 procrun(Windows)或 jsvc(Linux)将类安装为系统服务。


使用 Java 内置的 ServerSocket 实现简单 TCP 服务

适合自定义协议或轻量级内部服务。

import java.io.*;
import java.net.*;
public class SimpleTcpService {
    public static void main(String[] args) throws IOException {
        int port = 8080;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务启动,监听端口: " + port);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                new Thread(() -> {
                    try (BufferedReader in = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream()));
                         PrintWriter out = new PrintWriter(
                                 clientSocket.getOutputStream(), true)) {
                        String input;
                        while ((input = in.readLine()) != null) {
                            out.println("Echo: " + input);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        }
    }
}

使用 ScheduledExecutorService 实现定时任务服务

适用于周期性执行任务的场景(如数据同步、监控检查)。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledService {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            System.out.println("执行定时任务: " + System.currentTimeMillis());
            // 实际业务逻辑
        }, 0, 5, TimeUnit.SECONDS);
        // 防止主线程退出
        Runtime.getRuntime().addShutdownHook(new Thread(scheduler::shutdown));
        System.out.println("定时任务服务启动,每5秒执行一次");
    }
}

使用 Spring Boot + @Scheduled 启动定时服务

这是最简洁的定时任务实现方式(通常结合 Web 服务一起使用)。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@SpringBootApplication
@EnableScheduling
public class ScheduledApp {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledApp.class, args);
    }
}
@Component
class MyScheduledTask {
    @Scheduled(fixedRate = 5000)
    public void task() {
        System.out.println("定时任务执行: " + System.currentTimeMillis());
    }
}

启动流程图(以 Spring Boot 为例)

graph TD
    A[main 方法入口] --> B[SpringApplication.run]
    B --> C[初始化 Spring 容器]
    C --> D[自动配置内嵌 Web 服务器]
    D --> E[扫描 Bean & 依赖注入]
    E --> F[执行 ApplicationRunner / CommandLineRunner]
    F --> G[注册 ShutdownHook]
    G --> H[服务就绪,等待请求]

总结对比

方案 适用场景 复杂度 典型框架/工具
Spring Boot Web RESTful API、微服务 Spring Boot
Commons Daemon 系统服务注册 procrun/jsvc
ServerSocket 自定义 TCP 协议 原生 Java
ScheduledExecutor 定时任务 原生 Java
Spring @Scheduled 定时任务 + Web Spring Boot

推荐:如果你在构建企业级服务,Spring Boot + @Scheduled(如需定时任务)是最常用、最稳定的选择,如果只是简单的后台脚本或定时任务,使用原生 ScheduledExecutorService 即可。

抱歉,评论功能暂时关闭!