概述
1. 主类(注意,这里使用了lombok插件,如果不使用,请将注解修改为常规代码):
如果使用lombok,请引入并配置开发环境:
annotationProcessor 'org.projectlombok:lombok:1.18.+'
compileOnly 'org.projectlombok:lombok:1.18.+'
package com.webflux.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
/**
* 1.依赖:
compile 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
compile 'org.springframework.boot:spring-boot-starter-webflux'
compile 'org.springframework.boot:spring-boot-starter-web'
provided 'org.springframework.boot:spring-boot-starter-tomcat'
compile 'io.springfox:springfox-swagger2:2.6.1'
compile 'io.springfox:springfox-swagger-ui:2.6.1'
* 2. docker 安装mongoDB: 参考链接: https://blog.csdn.net/why191314/article/details/103174261
* 基本命令如下:
* (1)拉取镜像: docker pull mongo
* (2)启动镜像: docker run -d --name mongo -p 27017:27017 mongo --auth
* (3)进入容器: docker exec -it mongo mongo admin
* (4)创建用户: db.createUser({ user: 'admin', pwd: 'admin', roles: [ { role: "root", db: "admin" } ] });
* (5)测试联通性: docker run -it --rm --link mongo:mongo mongo mongo -u admin -p admin --authenticationDatabase admin mongo/admin
* 3. 配置application.yml
* 4. 编写entity实体类
* 5. 编写 repository
* 6. 编写 service
* 7. 编写vo
* 8. 编写 controller
* 9. 集成swagger
* 10. 运行这个类,浏览器输入: http://localhost:8080/swagger-ui.html 进行测试
*/
@SpringBootApplication
@EnableAutoConfiguration(exclude=DataSourceAutoConfiguration.class)
@EnableReactiveMongoRepositories(basePackages="com.webflux.demo.repository")
public class WebFluxDemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebFluxDemoApplication.class, args);
}
}
2. application.yml配置:
server:
port: 8080
spring:
data:
mongodb:
host: localhost
username: admin
password: admin
port: 27017
database: admin
3. 实体类对象:
package com.webflux.demo.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import com.webflux.demo.constant.SexEnum;
import lombok.Data;
@Document
@Data
public class User {
@Id
private Long id;
// 性别
private SexEnum sex;
@Field("user_name")
private String userName;
private String note;
}
4. 定义一个枚举类:
package com.webflux.demo.constant;
import lombok.Getter;
@Getter
public enum SexEnum {
MALE(1,"男"),
FEMALE(2,"女");
private int code;
private String name;
private 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;
}
}
5. 编写UserRepository:
package com.webflux.demo.repository;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import com.webflux.demo.entity.User;
import reactor.core.publisher.Flux;
@Repository
public interface UserRepository extends ReactiveMongoRepository<User,Long>{
/**
* 对用户名和备注进行模糊查询
* @param userName 用户名称
* @param note 备注
* @return 符合条件的用户
*/
/*
* 这个是jpa协议和命名规则
*/
public Flux<User> findByUserNameLikeAndNoteLike(String userName,String note);
}
6. 定义UserService接口:
package com.webflux.demo.service;
import com.webflux.demo.entity.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
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);
}
7. 实现UserService该接口:
package com.webflux.demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.webflux.demo.entity.User;
import com.webflux.demo.repository.UserRepository;
import com.webflux.demo.service.UserService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@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) {
return userRepository.deleteById(id);
}
@Override
public Flux<User> findUsers(String userName, String note) {
return userRepository.findByUserNameLikeAndNoteLike(userName, note);
}
}
8. 定义UserVo:
package com.webflux.demo.vo;
import lombok.Data;
@Data
public class UserVo {
private Long id;
private String userName;
private int sexCode;
private String sexString;
private String note;
}
9. 编写UserController:
package com.webflux.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.webflux.demo.entity.User;
import com.webflux.demo.service.UserService;
import com.webflux.demo.vo.UserVo;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public Mono<UserVo> getUser(@PathVariable Long id){
return userService.getUser(id).map(u->translate(u));
}
@PostMapping("/user")
public Mono<UserVo> insertUser(@RequestBody User user){
return userService.insertUser(user).map(u->translate(user));
}
@PutMapping("/user")
public Mono<UserVo> updateUser(@RequestBody User user){
return userService.updateUser(user).map(u->translate(user));
}
@DeleteMapping("/user/{id}")
public Mono<Void> deleteUser(@PathVariable Long id){
return userService.deleteUser(id);
}
@GetMapping("/user/{userName}/{note}")
public Flux<UserVo> findUsers(@PathVariable String userName, @PathVariable String note){
return userService.findUsers(userName, note).map(u->translate(u));
}
/**
* 完成PO到VO的转换
* @param user --PO持久层对象
* @return userVo --Vo 视图层对象
*/
private UserVo translate(User user) {
UserVo userVo=new UserVo();
userVo.setId(user.getId());
userVo.setUserName(user.getUserName());
userVo.setSexCode(user.getSex().getCode());
userVo.setSexString(user.getSex().getName());
userVo.setNote(user.getNote());
return userVo;
}
}
10. 集成swagger(这里只做一个最简单的实现为了测试方便,其他swagger内容请从其他网站详细了解):
package com.webflux.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.webflux.demo.controller"))//注意这里的路径,新手容易在这里出错导致打不开。
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户系统用户模块 API")
.description("")
.termsOfServiceUrl("localhost:8080")//这里可以是项目地址
.version("1.0.1")
.build();
}
}
最后
以上就是过时镜子为你收集整理的springboot webflux响应式编程入门案例的全部内容,希望文章能够帮你解决springboot webflux响应式编程入门案例所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复