跳到主要内容

Java 快速开始

本文档介绍如何从零开始创建一个 Java Spring Boot 应用,并将其部署到 CloudBase HTTP 云函数中。

前置条件

在开始之前,请确保您已经:

  • 安装了 Java JDK (推荐 JDK 8 或更高版本)
  • 安装了 Maven
  • 拥有腾讯云账号并开通了 CloudBase 服务
  • 了解基本的 Spring Boot 开发知识

第一步:创建项目目录

创建名为 helloworld-java 的新目录,并进入该目录:

mkdir helloworld-java
cd helloworld-java

第二步:初始化项目配置

创建 pom.xml 文件,用于描述项目信息和依赖关系:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>helloworld-java</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>

<name>helloworld-java</name>
<description>Simple hello world sample in Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>

<properties>
<java.version>8</java.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

第三步:创建标准 Spring Boot 目录结构

mkdir -p src/main/java/com/example/demo
mkdir -p src/main/resources

第四步:编写应用代码

创建 src/main/java/com/example/demo/DemoApplication.java 文件,这是应用的入口文件:

⚠️ 重要提示:CloudBase HTTP 云函数的默认端口必须是 9000

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@SpringBootApplication
@RestController
public class DemoApplication {

private final RestTemplate restTemplate = new RestTemplate();

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@GetMapping("/")
public String hello() {
return "Hello World!";
}

@GetMapping("/myip")
public ResponseEntity<?> getIpInfo() {
try {
// 设置 CORS 头,允许跨域请求
HttpHeaders headers = new HttpHeaders();
headers.set("Access-Control-Allow-Origin", "*");
headers.setContentType(MediaType.APPLICATION_JSON);

// 使用 RestTemplate 获取远程数据(这里使用 ipinfo.io 作为示例)
String response = restTemplate.getForObject("https://ipinfo.io", String.class);

return new ResponseEntity<>(response, headers, HttpStatus.OK);
} catch (Exception error) {
System.err.println("获取 IP 信息失败: " + error.getMessage());

Map<String, String> errorResponse = new HashMap<>();
errorResponse.put("error", "Failed to fetch remote data");
errorResponse.put("message", error.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
}
}

@GetMapping("/health")
public ResponseEntity<Map<String, Object>> health() {
// 健康检查接口
Map<String, Object> health = new HashMap<>();
health.put("status", "healthy");
health.put("timestamp", new Date().toInstant().toString());
health.put("version", "1.0.0");

return ResponseEntity.ok()
.header("Content-Type", "application/json")
.body(health);
}

@RequestMapping(value = "/{path:[^\\.]*}")
public ResponseEntity<Map<String, String>> notFound() {
// 错误处理:对于未知路径返回 404 错误
Map<String, String> error = new HashMap<>();
error.put("error", "Not Found");

return ResponseEntity.status(HttpStatus.NOT_FOUND)
.header("Content-Type", "application/json")
.body(error);
}
}

创建配置文件 src/main/resources/application.yml

# 服务器配置
# CloudBase HTTP 云函数的默认端口必须是 9000
server:
port: 9000
address: 0.0.0.0

# 应用配置
spring:
application:
name: helloworld-java

此代码创建了一个基本的 Web 服务器,提供以下功能:

  • 根路径 (/):返回 "Hello World!" 消息
  • IP 查询 (/myip):获取并返回客户端 IP 信息
  • 健康检查 (/health):返回服务状态信息
  • 错误处理:对于未知路径返回 404 错误

第五步:构建应用

使用 Maven 构建应用:

mvn clean package

构建成功后,会在 target/ 目录下生成 helloworld-java-1.0.0.jar 文件。

第六步: 创建启动脚本

💡 注意

  • 在 windows 下创建 scf_bootstrap 文件时,优先使用 nano scf_bootstrap 或者 vim scf_bootstrap 创建
  • 在 windows 下使用 vscode 创建 scf_bootstrap 文件时,部署到 HTTP 云函数可能会报错: scf_bootstrap 文件不存在
  • 这个错误是因为脚本文件包含了 Windows 格式的回车符(^M),导致 Linux 无法正确识别解释器路径。这是 WSL 中常见的问题

创建 scf_bootstrap 文件(无扩展名),这是 CloudBase 云函数的启动脚本:

#!/bin/bash
java -jar target/helloworld-java-1.0.0.jar

⚠️ 注意

  • 文件名必须是 scf_bootstrap,没有扩展名
  • 确保文件具有执行权限

为启动脚本添加执行权限:

chmod +x scf_bootstrap

第七步:本地测试(可选)

在部署之前,您可以在本地测试应用:

java -jar target/helloworld-java-1.0.0.jar

测试成功后,您可以通过以下方式验证:

  • 访问 http://localhost:9000/ 查看 Hello World 消息
  • 访问 http://localhost:9000/myip 查看 IP 信息
  • 访问 http://localhost:9000/health 查看健康状态

Ctrl + C 停止本地服务器。

第八步:部署到 CloudBase HTTP 云函数

准备部署文件

确保您的项目目录包含以下标准的 Spring Boot 项目结构:

helloworld-java/
├── scf_bootstrap
├── pom.xml
├── src/
│ └── main/
│ ├── java/
│ │ └── com/example/demo/DemoApplication.java
│ └── resources/
│ └── application.yml
└── target/
└── helloworld-java-1.0.0.jar

通过控制台部署

  1. 登录 云开发平台/云函数
  2. 点击「新建云函数」
  3. 选择「HTTP 云函数」
  4. 填写函数名称(如:helloworld-java
  5. 选择运行时:Java 8
  6. 选择「本地上传」方式
  7. 将项目文件打包为 zip 文件并上传(请选择文件进行打包,不要打包根目录文件夹)
  8. 点击「确定」完成部署

通过 CLI 部署

详情请参考 CLI 部署 HTTP 函数

打包项目

如果需要手动打包,可以使用以下命令:

# 创建 zip 包(包含 Maven 项目结构和构建产物)
zip -r helloworld-java.zip pom.xml target/helloworld-java-1.0.0.jar scf_bootstrap

第九步:访问您的应用

部署成功后,您可以参考通过 HTTP 访问云函数设置自定义域名访问HTTP 云函数

您可以通过以下方式测试:

  • 访问根路径查看 Hello World 消息
  • 访问 /myip 路径查看 IP 信息
  • 访问 /health 路径查看服务状态

常见问题

Q: 为什么必须使用 9000 端口?

A: CloudBase HTTP 云函数要求应用监听 9000 端口,这是平台的标准配置。在 Spring Boot 中可通过 application.ymlserver.port=9000 配置。

Q: 如何查看函数日志?

A: 在 CloudBase 控制台的云函数页面,点击函数名称进入详情页,可以查看运行日志。

Q: 支持哪些 Java 版本?

A: CloudBase 支持 Java 8、Java 11 等版本,建议使用 Java 8 以获得最佳兼容性。

Q: 如何处理 CORS 跨域问题?

A: 在响应头中设置 Access-Control-Allow-Origin 等 CORS 相关头部,如示例代码所示。

Q: 函数冷启动时间较长怎么办?

A: 可以通过减少 JAR 包大小、优化 Spring Boot 配置等方式来减少冷启动时间。

Q: 如何修改应用程序端口?

A: 在 application.yml 文件中修改 server.port 配置项,但 CloudBase HTTP 云函数必须使用 9000 端口。

Q: 为什么使用 Spring Boot 而不是原生 Java HTTP 服务器?

A: Spring Boot 提供了更丰富的功能、更好的开发体验和更强的生态系统支持,如依赖注入、自动配置、监控等,适合构建生产级应用。

最佳实践

  1. 错误处理:使用 Spring Boot 的全局异常处理机制,通过 @ControllerAdvice 注解统一处理异常
  2. 响应头设置:正确设置 Content-Type 和其他必要的响应头,可利用 Spring 的 ResponseEntity 灵活控制
  3. 日志记录:使用 Spring Boot 内置的日志框架(如 SLF4J + Logback)记录关键信息,便于调试和监控
  4. 代码结构:利用 Spring Boot 的注解简化开发,如 @RestController@GetMapping@PostMapping
  5. 依赖管理:使用 Maven 管理项目依赖,保持依赖版本的一致性
  6. 配置管理:将配置信息放在 application.ymlapplication.properties 中,支持不同环境的配置
  7. 性能优化:使用 Spring Boot 的懒加载、排除自动配置等特性优化启动时间

下一步