SpringBoot2.x webflux响应式编程实战

1、WebFlux中,请求和响应不再是WebMVC中的ServletRequest和ServletResponse,而是ServerRequest和ServerResponse

2、加入依赖,如果同时存在spring-boot-starter-web,则会优先用spring-boot-starter-web
        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

3.Service业务接口

  

package net.xdclass.webflux_project.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import net.xdclass.webflux_project.domain.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class UserService {
   
    private static final Map<String,User> dataMap = new HashMap<>();
    
    static {
        dataMap.put("1",new User("1", "冰"));
        dataMap.put("2",new User("2", "雪"));
        dataMap.put("3",new User("3", "之"));
        dataMap.put("4",new User("4", "华"));
    }
    
    /**
     * 返回列表
     */
    public Flux<User> list(){
        Collection<User> list = this.dataMap.values();
        return Flux.fromIterable(list);
    }
    
    /**
     * 根据id查找用户
     */
    public Mono<User> getById(final String id){
        return Mono.justOrEmpty(this.dataMap.get(id));
    }
    
    /**
     * 删除用户
     */
    public Mono<User> del(final String id){
        return Mono.justOrEmpty(this.dataMap.remove(id));
    }
}
 

Controller类

package net.xdclass.webflux_project.controller;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import net.xdclass.webflux_project.domain.User;
import net.xdclass.webflux_project.service.UserService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/v1/user")
public class UserController {
    
    @Autowired
    private UserService UserService;
    
    @GetMapping("/test")
    public Mono<String> test(){
        return Mono.just("冰雪之华");
    }
    

   //下面的注解说明是响应式编程,在界面返回的是每2秒返回一个,非阻塞的

  //相对于非响应式编程,全部查出再返回效率更高。

  //需要注意的是mysql不支持,redis等支持
    @GetMapping(value="list",produces=MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<User> list(){
        return UserService.list().delayElements(Duration.ofSeconds(2));
    }
    
    @GetMapping("getById")
    public Mono<User> getById(String id){
        return UserService.getById(id);
    }
    
    @GetMapping("del")
    public Mono<User> del(String id){
        return UserService.del(id);
    }
}
 

猜你喜欢

转载自blog.csdn.net/peng_0129/article/details/85778434