一、环境搭建
可以使用以下方法创建工程
- Sprint Initializr
- IntelliJ IDEA的Spring Assistant
-
Spring Tools
或者直接从 https://github.com/redexpress/spring-webflux/tree/master/chapter0-environment 下载创建好的工程
使用Spring Assistant创建工程
使用IDEA创建工程:
New Project
点“Next”进入“Project Properties”页面,
“Project Type”选择“Maven Project”,Language选择“Java”
再次按“Next”,进入依赖选择页面
在左边的列表“Web”里选择“Reactive Web”,在“NoSQL”里选择“Reactive MongoDB”和“Embedded MongoDB”,如下图:
Select dependencies
二、实现
创建实体User
public class User {
private String id;
private String name;
// 省略 getter, setter
}
创建接口 UserService
public interface UserService {
Flux<User> findAll();
Flux<User> findById(Flux<String> ids);
Mono<User> findById(String id);
Mono<User> save(User user);
Mono<User> update(String id, User user);
Mono<String> deleteById(String id);
}
实现UserServcie,本教程提供了简单的实现,仅供演示WebFlux,代码在这里
创建UserController
@RestController
@RequestMapping("/rx/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public Mono<User> findUserById(@PathVariable("id") String id) {
return this.userService.findById(id);
}
@GetMapping
public Flux<User> getUserList() {
return this.userService.findAll();
}
@PostMapping
public Mono<User> save(@RequestBody User user){
return this.userService.save(user);
}
@PutMapping("/{id}")
public Mono<User> update(@PathVariable(value = "id") String id, @RequestBody User user) {
return this.userService.update(id, user);
}
@DeleteMapping("/{id}")
public Mono<String> deleteCity(@PathVariable("id") String id) {
return userService.deleteById(id);
}
}
单元测试
使用Spring Boot Test的WebTestClient
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebfluxApplicationTest {
@Autowired
private WebTestClient webTestClient;
@Test
public void testCreateUser(){
String name = "Yang";
User user = new User();
user.setName(name);
webTestClient.post().uri("/rx/users")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.body(Mono.just(user), User.class)
.exchange()
.expectStatus().isOk()
.expectBody().jsonPath("$.name").isEqualTo(name)
.jsonPath("$.id").isNotEmpty();
}
}
本文的完整代码在https://github.com/redexpress/spring-webflux/tree/master/chapter1-quickstart
网友评论