Article Directory
A, WebFlux Profile
SpringBoot2.x
Underlying used Spring5
, Spring5
it introduced the reactive programming Spring WebFlux
.
WebFlux
Features:
① SpringMVC
is the IO model synchronization blocked, waste of resources is relatively serious. And WebFlux
you can do asynchronous non-blocking.
② event-driven ( Event-driven
), and the like Vue
and Angular
, as the corresponding dynamic changes in all the associated value.
③ SpringMVC
projects are required to run on Servlet containers such as Tomcat
, Jetty
... but now WebFlux
not only run on traditional Servlet container (support required Servlet3.1
), but also to run in support NIO
of Netty
and Undertow
in.
Two, WebFlux entry
① the introduction of WebFlux
dependency, introduced webflux
not introduced spring-boot-starter-web
because of spring-boot-starter-web
a higher priority.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
② start-up mode by default Netty
8080 port.
③ coding
Because if it is to achieve asynchronous non-blocking effect, the database should be replaced innoDB
database, where static variable simulation database.
public class User {
private long id ;
private String name;
}
@Service
public class UserService {
private static final Map<Integer, User> dataMap = new HashMap<>();
static {
dataMap.put(1,new User(1,"a"));
dataMap.put(2,new User(2,"b"));
dataMap.put(3,new User(3,"c"));
dataMap.put(4,new User(4,"d"));
}
/**
* 返回所有用户
*/
public Flux<User> getAllUser(){
Collection<User> users = dataMap.values();
return Flux.fromIterable(users);
}
/**
* 返回具体用户
*/
public Mono<User> getUserById(int id){
User user = dataMap.get(id);
return Mono.justOrEmpty(user);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
/**
* 返回指定用户额
*/
@RequestMapping("/{id}")
public Mono<User> getUserById(@PathVariable int id){
return userService.getUserById(id);
}
/**
* 返回所有用户
*/
@RequestMapping("/all")
public Flux<User> getAllUsers(){
return userService.getAllUser();
}
/**
* 延迟返回用户
* produces控制服务器返回客户端的格式
*/
@RequestMapping(value = "/delay",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public Flux<User> getAllUsersDelay(){
return userService.getAllUser().delayElements(Duration.ofSeconds(2));
}
}
④ Description
Mono
It represented by 0 or asynchronous comprising sequence elements, as a single object
Flux
It represents the asynchronous sequence comprising 0 to N elements, the list of objects array
Spring WebFlux
Application is not strictly dependent on Servlet API
, and therefore they can not be used as war
file deployment can not use the src/main/webapp
directory.
Spring WebFlux
Template supports a variety of techniques, including Thymeleaf
, FreeMarker
.