JDK安装:推荐使用Liberica JDK 21 LTS(支持GraalVM原生编译)
# macOS 使用SDKMAN安装
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk install java 21.0.1-librca
# Windows 使用Chocolatey
choco install libericajdk21-full
IDE配置:IntelliJ IDEA 2025.1配置
--enable-preview
Records类:替代传统POJO
// 2025版数据类推荐写法
public record User(Long id, String name, LocalDate createTime) {
// 自动生成所有参数的构造函数、getter、equals、hashCode和toString
public User {
// 自定义验证逻辑
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Name cannot be blank");
}
}
// 可以添加自定义方法
public String formattedCreateTime() {
return createTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
模式匹配增强:
// 2025版instanceof模式匹配
Object obj = "Hello";
if (obj instanceof String s && s.length() > 5) {
System.out.println(s.toUpperCase()); // 直接使用s变量
}
// switch表达式增强
int result = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};
LeetCode高频题解法:
// 两数之和问题(HashMap解法)
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
// 二叉树层序遍历(BFS解法)
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode currentNode = queue.poll();
currentLevel.add(currentNode.val);
if (currentNode.left != null) queue.offer(currentNode.left);
if (currentNode.right != null) queue.offer(currentNode.right);
}
result.add(currentLevel);
}
return result;
}
Spring Cloud 2025微服务项目:
// 使用Spring Cloud Gateway作为API网关
@SpringBootApplication
@EnableGateway
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("user-service", r -> r.path("/api/users/**")
.uri("lb://user-service"))
.route("order-service", r -> r.path("/api/orders/**")
.uri("lb://order-service"))
.build();
}
}
// 使用Spring Cloud OpenFeign调用远程服务
@FeignClient(name = "user-service", path = "/api/users")
public interface UserServiceClient {
@GetMapping("/{id}")
User getUser(@PathVariable("id") Long id);
}
服务发现与配置中心:
# 使用Consul作为服务注册与发现中心
spring:
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
instance-id: ${spring.application.name}:${random.value}
health-check-path: /actuator/health
health-check-interval: 10s
# 使用Spring Cloud Config配置中心
spring:
cloud:
config:
uri: http://localhost:8888
name: application
profile: dev
Kubernetes部署配置:
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service
labels:
app: user-service
spec:
replicas: 3
selector:
matchLabels:
app: user-service
template:
metadata:
labels:
app: user-service
spec:
containers:
- name: user-service
image: registry.example.com/user-service:v1.0.0
ports:
- containerPort: 8080
env:
- name: SPRING_PROFILES_ACTIVE
value: prod
resources:
requests:
memory: "512Mi"
cpu: "250m"
limits:
memory: "1024Mi"
cpu: "500m"
readinessProbe:
httpGet:
path: /actuator/health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
CI/CD流水线示例(GitHub Actions):
# .github/workflows/maven.yml
name: Java CI with Maven
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'liberica'
cache: maven
- name: Build with Maven
run: mvn -B package --file pom.xml
- name: Test Coverage
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: registry.example.com/user-service:${{ github.sha }}
secrets:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
使用Java调用OpenAI API:
// 使用OkHttp调用OpenAI GPT-4 API
public class OpenAIClient {
private static final String API_KEY = System.getenv("OPENAI_API_KEY");
private final OkHttpClient client = new OkHttpClient();
public String generateText(String prompt) throws IOException {
MediaType JSON = MediaType.get("application/json; charset=utf-8");
String requestBody = """
{
"model": "gpt-4-1106-preview",
"messages": [{"role": "user", "content": "%s"}],
"temperature": 0.7
}
""".formatted(prompt);
RequestBody body = RequestBody.create(requestBody, JSON);
Request request = new Request.Builder()
.url("https://api.openai.com/v1/chat/completions")
.header("Authorization", "Bearer " + API_KEY)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
JSONObject jsonResponse = new JSONObject(response.body().string());
return jsonResponse.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("message")
.getString("content");
}
}
}
Java Agent性能监控:
// 使用Byte Buddy实现Java Agent
public class PerformanceAgent {
public static void premain(String agentArgs, Instrumentation inst) {
new AgentBuilder.Default()
.type(ElementMatchers.nameContains("Service"))
.transform((builder, typeDescription, classLoader, module) ->
builder.method(ElementMatchers.any())
.intercept(MethodDelegation.to(PerformanceInterceptor.class)))
.installOn(inst);
}
}
public class PerformanceInterceptor {
public static Object intercept(@Origin Method method, @AllArguments Object[] args,
@SuperCall Callable<?> callable) throws Exception {
long startTime = System.currentTimeMillis();
try {
return callable.call();
} finally {
long duration = System.currentTimeMillis() - startTime;
System.out.printf("Method %s.%s took %d ms%n",
method.getDeclaringClass().getName(),
method.getName(),
duration);
}
}
}
系统架构图:
┌───────────────────────────────────────────────────────────────┐
│ API Gateway │
│ (Spring Cloud Gateway + OAuth2 + Rate Limiting + Circuit Breaker) │
└───────────────────┬─────────────────┬────────────────────────┘
│ │
┌───────────────────┴──┐ ┌───────────┴─────────────────┐
│ 用户服务 │ │ 商品服务 │
│ (User Service) │ │ (Product Service) │
│ - 用户管理 │ │ - 商品管理 │
│ - 认证授权 │ │ - 库存管理 │
│ - 会员体系 │ │ - 商品搜索(Elasticsearch) │
└───────────────────────┘ └───────────┬─────────────────┘
│
┌───────────────────┐ ┌───────────┬──┴─────────────────┐ ┌───────────────────┐
│ 订单服务 │ │ 支付服务 │ 营销服务 │ │ 消息服务 │
│ (Order Service) │ │(Payment │ (Promotion Service)│ │(Message Service) │
│ - 订单创建 │ │ Service) │ - 优惠券系统 │ │ - 邮件通知 │
│ - 订单状态管理 │ │ - 支付处理 │ - 促销活动 │ │ - 短信通知 │
│ - 订单分库分表 │ │ - 退款流程 │ - 价格计算 │ │ - WebSocket推送 │
└───────────────────┘ └───────────┘ └─────────────────┘ └───────────────────┘
│
┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┴─────────────────┐
│ 数据分析服务 │ │ 后台管理系统 │ │ 基础设施 │
│ (Data Analytics │ │ (Admin Portal) │ │ - 服务注册与发现(Consul/Nacos) │
│ Service) │ │ - 运营管理界面 │ │ - 配置中心(Spring Cloud Config) │
│ - 用户行为分析 │ │ - 数据可视化 │ │ - 服务监控与告警(Grafana+Prometheus) │
│ - 销售报表 │ │ - 系统设置 │ │ - 分布式日志(ELK) │
│ - 推荐系统 │ │ │ │ - 容器编排(Kubernetes) │
└───────────────────┘ └───────────────────┘ └───────────────────────────────────────┘
技术选型说明:
这个实战路线覆盖了Java开发从基础到高级的完整体系,结合了2025年最新的技术趋势和最佳实践。建议按照阶段逐步学习,每个阶段都配合实际项目练习,以加深理解和掌握。
Java 基础,面向对象编程,Java 核心类库,异常处理,集合框架,IO 流,多线程,Java Web 开发,Servlet,JSP,Spring 框架,MyBatis,Spring Boot, 微服务,全栈开发
资源地址:
https://pan.quark.cn/s/14fcf913bae6
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有