Skip to content

Commit

Permalink
Spring Boot WebFlux增删改查样例
Browse files Browse the repository at this point in the history
  • Loading branch information
wuyouzhuguli committed Apr 4, 2019
1 parent 1a9df12 commit 5d1a3fc
Show file tree
Hide file tree
Showing 8 changed files with 667 additions and 0 deletions.
40 changes: 40 additions & 0 deletions 58.Spring-Boot-WebFlux-crud/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?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.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>webflux</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>webflux</name>
<description>Demo project for Spring Boot</description>

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

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.webflux;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;

@SpringBootApplication
@EnableReactiveMongoRepositories
public class WebfluxApplication {
public static void main(String[] args) {
SpringApplication.run(WebfluxApplication.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package com.example.webflux.controller;

import com.example.webflux.domain.User;
import com.example.webflux.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
* @author MrBird
*/
@RestController
@RequestMapping("user")
public class UserController {

@Autowired
private UserService userService;

/**
* 以数组的形式一次性返回所有数据
*/
@GetMapping
public Flux<User> getUsers() {
return userService.getUsers();
}

/**
* 以 Server sent events形式多次返回数据
*/
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUsersStream() {
return userService.getUsers();
}

@PostMapping
public Mono<User> createUser(User user) {
return userService.createUser(user);
}

/**
* 存在返回 200,不存在返回 404
*/
@DeleteMapping("/{id}")
public Mono<ResponseEntity<Void>> deleteUser(@PathVariable String id) {
return userService.deleteUser(id)
.then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

/**
* 存在返回修改后的 User
* 不存在返回 404
*/
@PutMapping("/{id}")
public Mono<ResponseEntity<User>> updateUser(@PathVariable String id, User user) {
return userService.updateUser(id, user)
.map(u -> new ResponseEntity<>(u, HttpStatus.OK))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

/**
* 根据用户 id查找
* 存在返回,不存在返回 404
*/
@GetMapping("/{id}")
public Mono<ResponseEntity<User>> getUser(@PathVariable String id) {
return userService.getUser(id)
.map(user -> new ResponseEntity<>(user, HttpStatus.OK))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

/**
* 根据年龄段来查找
*/
@GetMapping("/age/{from}/{to}")
public Flux<User> getUserByAge(@PathVariable Integer from, @PathVariable Integer to) {
return userService.getUserByAge(from, to);
}

@GetMapping(value = "/stream/age/{from}/{to}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByAgeStream(@PathVariable Integer from, @PathVariable Integer to) {
return userService.getUserByAge(from, to);
}

/**
* 根据用户名查找
*/
@GetMapping("/name/{name}")
public Flux<User> getUserByName(@PathVariable String name) {
return userService.getUserByName(name);
}

@GetMapping(value = "/stream/name/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByNameStream(@PathVariable String name) {
return userService.getUserByName(name);
}

/**
* 根据用户描述模糊查找
*/
@GetMapping("/description/{description}")
public Flux<User> getUserByDescription(@PathVariable String description) {
return userService.getUserByDescription(description);
}

@GetMapping(value = "/stream/description/{description}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByDescriptionStream(@PathVariable String description) {
return userService.getUserByDescription(description);
}

/**
* 根据多个检索条件查询
*/
@GetMapping("/condition")
public Flux<User> getUserByCondition(int size, int page, User user) {
return userService.getUserByCondition(size, page, user);
}

@GetMapping("/condition/count")
public Mono<Long> getUserByConditionCount(User user) {
return userService.getUserByConditionCount(user);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.example.webflux.dao;

import com.example.webflux.domain.User;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;

/**
* @author MrBird
*/
@Repository
public interface UserDao extends ReactiveMongoRepository<User, String> {

/**
* 根据年龄段来查找
*
* @param from from
* @param to to
* @return Flux<User>
*/
Flux<User> findByAgeBetween(Integer from, Integer to);

/**
* 更具描述来模糊查询用户
*
* @param description 描述
* @return Flux<User>
*/
Flux<User> findByDescriptionIsLike(String description);

/**
* 通过用户名查询
*
* @param name 用户名
* @return Flux<User>
*/
Flux<User> findByNameEquals(String name);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.example.webflux.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
* @author MrBird
*/
@Document(collection = "user")
public class User {

@Id
private String id;
private String name;
private Integer age;
private String description;

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;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package com.example.webflux.service;

import com.example.webflux.dao.UserDao;
import com.example.webflux.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
* @author MrBird
*/
@Service
public class UserService {

@Autowired
private UserDao userDao;
@Autowired
private ReactiveMongoTemplate template;

public Flux<User> getUsers() {
return userDao.findAll();
}

public Mono<User> getUser(String id) {
return this.userDao.findById(id);
}

/**
* 新增和修改都是 save方法,
* id 存在为修改,id 不存在为新增
*/
public Mono<User> createUser(User user) {
return userDao.save(user);
}

public Mono<Void> deleteUser(String id) {
return this.userDao.findById(id)
.flatMap(user -> this.userDao.delete(user));
}

public Mono<User> updateUser(String id, User user) {
return this.userDao.findById(id)
.flatMap(u -> {
u.setName(user.getName());
u.setAge(user.getAge());
u.setDescription(user.getDescription());
return this.userDao.save(u);
});
}

public Flux<User> getUserByAge(Integer from, Integer to) {
return this.userDao.findByAgeBetween(from, to);
}

public Flux<User> getUserByName(String name) {
return this.userDao.findByNameEquals(name);
}

public Flux<User> getUserByDescription(String description) {
return this.userDao.findByDescriptionIsLike(description);
}

/**
* 分页查询,只返回分页后的数据,count值需要通过 getUserByConditionCount
* 方法获取
*/
public Flux<User> getUserByCondition(int size, int page, User user) {
Query query = getQuery(user);
Sort sort = new Sort(Sort.Direction.DESC, "age");
Pageable pageable = PageRequest.of(page, size, sort);

return template.find(query.with(pageable), User.class);
}

/**
* 返回 count,配合 getUserByCondition使用
*/
public Mono<Long> getUserByConditionCount(User user) {
Query query = getQuery(user);
return template.count(query, User.class);
}

private Query getQuery(User user) {
Query query = new Query();
Criteria criteria = new Criteria();

if (!StringUtils.isEmpty(user.getName())) {
criteria.and("name").is(user.getName());
}
if (!StringUtils.isEmpty(user.getDescription())) {
criteria.and("description").regex(user.getDescription());
}
query.addCriteria(criteria);
return query;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
spring:
data:
mongodb:
host: localhost
port: 27017
database: webflux
Loading

0 comments on commit 5d1a3fc

Please sign in to comment.