2026/4/6 21:08:48
网站建设
项目流程
免费建立自己的网站代理,网站换服务器有影响吗,手机管理网站模板下载,三亚网红响应式编程基础响应式编程是一种基于数据流和变化传播的编程范式。Spring WebFlux 是 Spring 框架提供的响应式 Web 栈#xff0c;基于 Reactor 库实现。核心概念包括 Publisher#xff08;发布者#xff09;、Subscriber#xff08;订阅者#xff09;和背压#xff08;B…响应式编程基础响应式编程是一种基于数据流和变化传播的编程范式。Spring WebFlux 是 Spring 框架提供的响应式 Web 栈基于 Reactor 库实现。核心概念包括 Publisher发布者、Subscriber订阅者和背压Backpressure机制。Reactor 提供两种核心类型Mono0-1 个元素和 Flux0-N 个元素。创建示例Mono.just(Hello) Flux.fromIterable(Arrays.asList(1, 2, 3))项目初始化使用 Spring Initializr 创建项目时需选择 Reactive Web 依赖。Maven 配置示例dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-webflux/artifactId /dependency基础启动类需启用响应式支持SpringBootApplication public class WebfluxApplication { public static void main(String[] args) { SpringApplication.run(WebfluxApplication.class, args); } }路由与处理器WebFlux 提供函数式路由声明方式。典型路由配置Bean public RouterFunctionServerResponse routes() { return RouterFunctions.route() .GET(/hello, request - ServerResponse.ok().body(Mono.just(Hello WebFlux), String.class)) .build(); }注解式控制器示例RestController RequestMapping(/users) public class UserController { GetMapping(/{id}) public MonoUser getUser(PathVariable String id) { return userRepository.findById(id); } }响应式数据库集成Spring Data 提供响应式 Repository 支持。配置 MongoDB 示例spring: data: mongodb: uri: mongodb://localhost:27017/test响应式 Repository 接口public interface UserRepository extends ReactiveMongoRepositoryUser, String { FluxUser findByAgeGreaterThan(int age); }错误处理机制全局异常处理示例ExceptionHandler public MonoResponseEntityString handle(Exception ex) { return Mono.just(ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ex.getMessage())); }响应式错误处理操作符return userService.getUser(id) .onErrorResume(e - Mono.just(new User(fallback)));测试策略WebTestClient 是测试 WebFlux 的主要工具SpringBootTest class UserControllerTest { Autowired private WebTestClient webClient; Test void testGetUser() { webClient.get().uri(/users/1) .exchange() .expectStatus().isOk(); } }高级特性服务器推送事件SSE实现GetMapping(value /stream, produces MediaType.TEXT_EVENT_STREAM_VALUE) public FluxString streamEvents() { return Flux.interval(Duration.ofSeconds(1)) .map(i - Event i); }响应式 WebSocket 支持Bean public HandlerMapping webSocketHandlerMapping() { MapString, WebSocketHandler map new HashMap(); map.put(/echo, new EchoHandler()); return new SimpleUrlHandlerMapping(map, -1); }性能优化关键配置参数server: reactor: netty: max-in-memory-size: 10MB connection-timeout: 30s背压策略建议使用onBackpressureBuffer缓冲溢出采用limitRate限制请求速率实现自定义BaseSubscriber控制消费速度