使用spring启动httpserver

本文介绍如何使用Java自带的HttpServer实现HTTP回调接口,通过简单的代码示例展示如何接收HTTP请求及响应处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

个人博客原文地址:http://www.ltang.me/2015/12/01/httpserver_spring/

项目中原本使用的是基于socket的server,后来因为一些原因,需要添加一个http的回调地址,供外部调用,但是总不能修改项目结构,而且只是一个接口需求,不想也不需要重新开个项目丢进服务器,所以直接使用了java自带的HttpServer类,启动一个端口作为http请求的回调地址。

  1. HttpServer代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    public void start() {
           try {
               server = HttpServer.create(new InetSocketAddress(port), 0);
        
               server.createContext("/backcall", backCallHandler);
               server.setExecutor(null);
               server.start();
        
               logger.info("本地监听端口启动成功({})", port);
           } catch (IOException e) {
               logger.error("本地监听端口启动失败(" + port + ")", e);
           }
       }
        
       public void stop() {
           if (server != null) {
               server.stop(100);
           }
       }
    
  2. 其中backCallHandler是对http请求的分发类,解析请求参数,再调用其它方法处理请求并返回结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    public class BackCallHandler implements HttpHandler, ApplicationContextAware {
    
    public void handle(HttpExchange httpExchange) throws IOException {
        InputStream in = httpExchange.getRequestBody(); //获得输入流
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, weiZhiUtil.ENCODING));
        String parameterStr = "";
        String temp = null;
        while ((temp = reader.readLine()) != null) {
            parameterStr += temp;
        }
        Map<String, String> parameters = null;
        try {
            parameters = getParametersMap(parameterStr);
        } catch (Exception e) {
        }
        LOGGER.info("回调接口收到请求,参数为:[" + parameterStr + "]");
        ......
        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, resDoc.asXML().getBytes("UTF-8").length);
        OutputStream out = httpExchange.getResponseBody();
        out.write(resDoc.asXML().getBytes("UTF-8");
        out.flush();
        ......
    
  1. 使用spring bean配置并管理httpServer的启动:

    1
    2
    3
    
    <bean class="com.kuaisu.weizhi.service.WeiZhiHttpServer" init-method="start" destroy-method="stop">
        <property name="port" value="${HTTP_LOCAL_PORT}"/>
    </bean>
    

    spring在实例化这个对象时,就会调用start方法初始化,并注入port参数,启动httpServer。

<think>我们正在讨论如何在Spring Boot中启动HTTP Server服务。根据引用[1]和[2]的内容,我们可以知道Spring Boot通过内嵌的Servlet容器(如Tomcat)来提供HTTP服务。启动HTTP Server服务实际上就是启动Spring Boot应用,因为Spring Boot默认集成了内嵌的Servlet容器。 以下是启动HTTP Server服务的步骤: 1. 添加依赖:在项目的pom.xml文件中添加Spring Boot Web起步依赖。 2. 编写启动类:使用@SpringBootApplication注解,并在main方法中运行SpringApplication。 3. 配置端口:在配置文件中设置服务器端口(如application.properties或application.yml)。 4. 运行应用:运行启动类的main方法,内嵌的Servlet容器就会启动并监听配置的端口。 具体步骤如下: ### 步骤1:添加依赖 在Maven项目中,需要添加`spring-boot-starter-web`依赖,它包含了内嵌的Tomcat服务器以及Spring MVC的支持。 ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> ``` ### 步骤2:创建启动类 创建一个带有`@SpringBootApplication`注解的类,并在其中编写main方法。 ```java 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); } } ``` ### 步骤3:配置端口(可选) 默认情况下,服务器会监听8080端口。如果需要修改端口,可以在`application.properties`或`application.yml`中配置。 在`application.properties`中: ```properties server.port=8080 ``` 或者在`application.yml`中: ```yaml server: port: 8080 ``` ### 步骤4:运行应用 运行Application类的main方法,控制台会输出启动信息,包括内嵌Servlet容器的端口。 如果看到类似以下日志,说明HTTP Server已经启动: ``` Tomcat started on port(s): 8080 (http) with context path '' ``` 此时,可以通过浏览器访问`http://localhost:8080`,虽然还没有定义任何端点,但可以确认服务是否启动。 ### 添加一个简单的REST端点 为了测试,我们可以添加一个简单的REST控制器: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/") public String hello() { return "Hello, World!"; } } ``` 重新启动应用后,访问`http://localhost:8080/`,将会看到"Hello, World!"。 ### 关于配置文件的说明(参考引用[2]) - 在Spring Boot中,可以使用`application.properties`或`application.yml`进行配置。 - 如果使用Spring Cloud Config,则可能会使用`bootstrap`配置文件,它会在应用启动初期加载,用于从配置服务器获取配置(如引用[1]中的配置)。但在普通Spring Boot应用中,通常只需要`application`配置文件。 ### 验证 启动应用后,可以通过以下方式验证: 1. 查看控制台输出,确认Tomcat启动的端口。 2. 使用浏览器访问`http://localhost:8080`(如果端口是8080)。 3. 使用curl命令:`curl http://localhost:8080` ### 注意事项 - 如果端口被占用,启动会失败,需要更改端口。 - 如果需要HTTPS支持,可以配置SSL(不在本文讨论范围)。 这样,我们就成功在Spring Boot中启动了HTTP Server服务。 ### 相关问题 1. 如何修改Spring Boot应用的上下文路径(context path)? 2. 如何在Spring Boot中配置HTTPS? 3. 如何将内嵌的Tomcat服务器替换为Jetty或Undertow? 4. 如何设置Spring Boot应用的健康检查端点? 5. 如何自定义Spring Boot应用的错误页面? 以上问题可以帮助用户进一步了解Spring Boot的Web服务配置。</think>### 在 Spring Boot 中启动 HTTP Server 服务的完整指南 Spring Boot 默认内嵌了 Tomcat 服务器,只需简单配置即可启动 HTTP 服务。以下是具体步骤: #### 1. 添加核心依赖 (pom.xml) ```xml <dependencies> <!-- Web 服务基础依赖(包含内嵌 Tomcat) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 开发工具(热部署等) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> ``` #### 2. 配置服务器属性 (application.yml) ```yaml server: port: 8080 # HTTP 服务端口 servlet: context-path: /api # 应用上下文路径 tomcat: max-threads: 200 # 最大线程数 connection-timeout: 5000 # 连接超时(ms) ``` #### 3. 创建启动类 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HttpServerApplication { public static void main(String[] args) { SpringApplication.run(HttpServerApplication.class, args); } } ``` #### 4. 添加测试端点 ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HealthController { @GetMapping("/health") public String healthCheck() { return "HTTP Server is running!"; } } ``` #### 5. 启动服务 运行 `HttpServerApplication` 的 main 方法,控制台将输出: ``` Tomcat initialized with port(s): 8080 (http) Tomcat started on port(s): 8080 (http) with context path '/api' ``` #### 6. 验证服务 ```bash # 使用 curl 测试 curl http://localhost:8080/api/health # 响应结果 HTTP Server is running! ``` --- ### 高级配置选项 #### 自定义服务器配置 ```java import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ServerConfig { @Bean public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatCustomizer() { return factory -> { factory.addConnectorCustomizers(connector -> { connector.setProperty("maxKeepAliveRequests", "100"); connector.setProperty("acceptCount", "50"); }); }; } } ``` #### 使用 bootstrap 配置(Spring Cloud 环境) ```yaml # bootstrap.yml(优先于 application.yml 加载) spring: application: name: http-service cloud: config: uri: http://config-server:8888 # 配置中心地址[^1][^2] ``` --- ### 常见问题解决 1. **端口冲突** 修改 `server.port` 值,或使用随机端口: ```yaml server: port: 0 # 随机可用端口 ``` 2. **HTTPS 支持** 添加 SSL 配置: ```yaml server: ssl: key-store: classpath:keystore.p12 key-store-password: changeit key-store-type: PKCS12 key-alias: tomcat port: 8443 ``` 3. **服务无法启动** 检查端口占用: ```bash netstat -ano | findstr :8080 ``` --- ### 服务验证方法 | 验证方式 | 命令/操作 | 预期结果 | |----------------|-------------------------------|-----------------------| | 端点访问 | `curl http://localhost:8080/api/health` | HTTP 200 + 文本响应 | | 端口监听 | `telnet localhost 8080` | 连接成功 | | 启动日志 | 查看控制台输出 | Tomcat 启动成功消息 | | Actuator 健康检查| `/actuator/health` | {"status":"UP"} | --- ### 相关问题 1. 如何在 Spring Boot 中配置 HTTPS 双向认证?[^1] 2. 如何将内嵌 Tomcat 替换为 Jetty 或 Undertow?[^2] 3. 如何实现 HTTP 到 HTTPS 的自动重定向?[^1] 4. Spring Boot Actuator 提供了哪些服务器监控端点?[^2] 5. 如何在多网卡环境中指定服务绑定地址?[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值