四、Java实战案例库:从入门到架构
5.1 单体应用:Spring Boot快速搭建
项目结构规范:
src/main/java/com/example/demo/
├── DemoApplication.java # 启动类
├── controller/ # 控制器层
│ └── UserController.java
├── service/ # 业务层
│ └── UserService.java
├── dao/ # 数据访问层
│ └── UserRepository.java
├── entity/ # 实体类
│ └── User.java
├── exception/ # 自定义异常
│ └── GlobalExceptionHandler.java
└── config/ # 配置类
└── SwaggerConfig.java
Controller层最佳实践:
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
@Operation(summary = "根据ID查询用户")
public ResponseEntity getUser(@PathVariable Long id) {
User user = userService.findById(id);
return ResponseEntity.ok(user);
}
@PostMapping
@Operation(summary = "创建用户")
public ResponseEntity createUser(@Valid @RequestBody UserDTO userDTO) {
User user = userService.save(userDTO);
return ResponseEntity.created(URI.create("/api/users/" + user.getId())).body(user);
}
}
5.2 分布式架构:微服务实战
核心组件部署架构:
服务注册中心
- Nacos:支持CP/AP模式切换
- Eureka:AP优先(Netflix)
配置中心
- Nacos Config
- Spring Cloud Config
API网关
- Spring Cloud Gateway
- Kong(Nginx+Lua)
服务熔断
- Sentinel:流量防护
- Hystrix(已停止维护)
📌Spring Cloud Gateway路由配置:
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- AddRequestHeader=X-Request-Time, ${new java.util.Date()}
5.3 高并发场景:秒杀系统设计
架构优化关键点:
- 库存预扣:
- Redis预减库存(原子操作INCR/DECR)
- 订单超时自动回滚
- 请求削峰:
- RabbitMQ/Kafka消息队列
- 令牌桶限流(Sentinel)
- 防刷机制:
- 异步处理:
📌Redis库存扣减Lua脚本:
local stock = redis.call('GET', KEYS[1])
if tonumber(stock) >= tonumber(ARGV[1]) then
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1
else
return 0
end
5.4 大数据集成:Hadoop与Spark
Java操作HDFS示例:
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path filePath = new Path("/user/data/input.txt");
// 读取文件
FSDataInputStream in = fs.open(filePath);
IOUtils.copyBytes(in, System.out, 4096, false);
// 写入文件
FSDataOutputStream out = fs.create(filePath);
out.write("Hello HDFS".getBytes());
out.close();
Spark Java API使用:
SparkConf conf = new SparkConf().setAppName("WordCount");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD lines = sc.textFile("hdfs://path/to/file");
JavaRDD words = lines.flatMap(line -> Arrays.asList(line.split(" ")).iterator());
JavaPairRDD counts = words.mapToPair(w -> new Tuple2<>(w, 1))
.reduceByKey((a, b) -> a + b);
counts.saveAsTextFile("hdfs://output/path");
5.5 安全防护:OWASP Top 10防御
常见漏洞与修复方案:
| 漏洞类型 |
风险描述 |
防御措施 |
| SQL注入 |
拼接SQL语句 |
使用PreparedStatement/MyBatis参数化 |
| XSS攻击 |
注入恶意脚本 |
HTML转义(Thymeleaf默认转义) |
| CSRF攻击 |
跨站请求伪造 |
添加CSRF Token(Spring Security默认启用) |
| 敏感信息泄露 |
日志打印密码/密钥 |
使用@Loggable(value = Level.INFO, exclude = "password") |
📌Spring Security配置示例:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
5.6 云原生部署:Kubernetes实战
Pod资源限制配置:
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
ConfigMap与Secret挂载:
env:
- name: DB_URL
valueFrom:
configMapKeyRef:
name: app-config
key: db.url
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: app-secret
key: db.password
5.7 性能调优案例:电商网站优化
优化前后指标对比:
| 指标 |
优化前 |
优化后 |
优化措施 |
| 页面加载时间 |
3.2s |
0.8s |
CDN加速+资源合并压缩 |
| 数据库QPS |
1200 |
5800 |
读写分离+索引优化 |
| 接口P99延迟 |
850ms |
120ms |
本地缓存+异步处理 |
📌关键优化技术:
- Redis缓存热点数据(商品详情、分类树)
- Ehcache本地缓存(减少远程调用)
- 数据库索引优化(联合索引覆盖查询)
- 异步消息队列(订单创建→消息→异步处理)