springboot整合webflux

本文将介绍如何在SpringBoot项目中整合WebFlux,实现响应式编程。首先,我们将讨论导入必要的依赖,接着详细说明配置步骤,然后通过实例展示如何创建Reactor核心的Controller,最后探讨WebFlux在性能和非阻塞I/O方面的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.nice</groupId>
    <artifactId>webflux-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webflux-demo</name>
    <description>This is a demo</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-web</artifactId>-->
        <!--</dependency>-->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

导入依赖之后

package com.nice.pojo;

import com.nice.enumeration.SexEnum;
import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;

import java.io.Serializable;

/**
 * @author nice
 */
@Data
public class User implements Serializable {
    private static final long serialVersionUID = -1120168819772395330L;
    @Id
    private Long id;
    private SexEnum sex;
    @Field("user_name")
    private String userName;
    private String note;
}
package com.nice.enumeration;

import lombok.Getter;
import lombok.Setter;

/**
 * @author nice
 */

@Getter
public enum SexEnum {
    /**
     *
     */
    MALE(1,"男"),
    FEMALE(0,"女");
    /**
     *
     */
    private int code;
    private String name;
    SexEnum(int code,String name){
        this.code = code;
        this.name = name;
    }
    public static SexEnum getSexEnum(int code){
        SexEnum[] enums = SexEnum.values();
        for (SexEnum item : enums) {
            if (item.getCode() == code){
                return item;
            }
        }
        return null;
    }



}
package com.nice.repository;

import com.nice.pojo.User;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;

/**
 * @author nice
 */
@Repository
public interface UserRepository extends ReactiveMongoRepository<User,Long> {

    /**
     * 对用户名和备注进行模糊查询
     * @param userName
     * @param note
     * @return
     */
    public Flux<User> findByUserNameLikeAndNoteLike(String userName,String note);
}
package com.nice.vo;

import lombok.Data;
import lombok.ToString;

import java.io.Serializable;

/**
 * @author nice
 */
@Data
public class UserVo {
//    private static final long serialVersionUID = 811080144541648590L;
    private Long id;
    private String userName;
    private int sexCode;
    private String sexName;
    private String note;
}
package com.nice.service;

import com.nice.pojo.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * UserService业务逻辑层
 * @author nice
 */
public interface UserService {

    Mono<User> getUser(Long id);
    Mono<User> insertUser(User user);
    Mono<User> updateUser(User user);
    Mono<Void> deleteUser(Long id);
    Flux<User> findUsers(String userName,String note);
}
package com.nice.service.impl;

import com.nice.pojo.User;
import com.nice.repository.UserRepository;
import com.nice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author nice
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public Mono<User> getUser(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public Mono<User> insertUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public Mono<User> updateUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public Mono<Void> deleteUser(Long id) {
        Mono<Void> result = userRepository.deleteById(id);
        return result;
    }

    @Override
    public Flux<User> findUsers(String userName, String note) {
        return userRepository.findByUserNameLikeAndNoteLike(userName,note);
    }
}
package com.nice.controller;

import com.nice.pojo.User;
import com.nice.service.UserService;
import com.nice.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author nice
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户
     * @param id
     * @return
     */
    @GetMapping("/user/{id}")
    public Mono<UserVo> getUser(@PathVariable Long id){
        //从User对象转换为UserVo对象
        System.out.println(userService.getUser(id).map(this::translate));
        return userService.getUser(id).map(this::translate);
    }

    /**
     * 新增用户
     * @return
     */
    @PostMapping("/user")
    public Mono<UserVo> insertUser(@RequestBody User user){
        return userService.insertUser(user).map(this::translate);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @PutMapping("/user")
    public Mono<UserVo> updateUser(@RequestBody User user){
        return userService.updateUser(user).map(this::translate);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/user/{id}")
    public Mono<Void> deleteUser(@PathVariable Long id){
        return userService.deleteUser(id);
    }

    /**
     * 查询用户
     * @param userName
     * @param note
     * @return
     */
    @GetMapping("/user/{userName}/{note}")
    public Flux<UserVo> findUsers(@PathVariable String userName,@PathVariable String note){
        return userService.findUsers(userName,note).map(this::translate);
    }

    /**
     * 完成PO到VO的转换
     * @param user
     * @return
     */
    private UserVo translate(User user){
        UserVo userVo = new UserVo();
        userVo.setUserName(user.getUserName());
        userVo.setSexCode(user.getSex().getCode());
        userVo.setSexName(user.getSex().getName());
        userVo.setNote(user.getNote());
        userVo.setId(user.getId());
        return userVo;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值