Step 1: Maven Dependencies
Create a Spring Boot spplication with the latest version of spring webflux in the POM.xml
. To see how to create a spring application you can visit Spring Example - HelloWorld
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Step 2: User Entity
Add the User class to provide the entity objects which the application must deliver
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 3: UserRepository
add the repository UserRepository
to provide the entities that we need to send via the controller in the last step.
it has these two main functions:
Mono<User> findUserById(String id)
Flux<User> findAllUsers()
@Repository
public class UserRepository {
static Map<String,User> userData;
static {
userData = new HashMap<>();
userData.put("1",new User("1","User 1"));
userData.put("2",new User("2","User 2"));
}
public Mono<User> findUserById(String id) {
return Mono.just(userData.get(id));
}
public Flux<User> findAllUsers() {
return Flux.fromIterable(userData.values());
}
}
Step 4: WebfluxController
Generate WebfluxController with 3 mapping:
- @GetMapping("/"): to deliver a simple string as the response
- @GetMapping("/{id}"): to deliver one object using
Mono
- @GetMapping("/all"): to deliver an array of objects using
Flux
@RestController
public class WebfluxController {
@GetMapping("/")
public Publisher<String> home() {
return Mono.just("Home page");
}
@GetMapping("/{id}")
private Mono<User> getUserById(@PathVariable String id) {
return userRepository.findUserById(id);
}
@GetMapping("/all")
private Flux<User> getAllUsers() {
return userRepository.findAllUsers();
}
}
Step 5: Run the application
Run the application and access it by calling the implemeted endpoints:
http://127.0.0.1:8080/
http://127.0.0.1:8080/1
http://127.0.0.1:8080/all