zoukankan      html  css  js  c++  java
  • Spring Boot WebFlux整合mongoDB

    引入maven文件

    <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter</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-data-mongodb-reactive</artifactId>
    </dependency>

    创建配置文件

    spring:
      data:
        mongodb:
          host: 127.0.0.1
          port: 27017
          username: mickey
          password: 123456
          database: mongoTest

    创建document实体类

    @Data
    @Document("person")
    public class PersonEntity {
    
        @Id
        private String id;
    
        private String userName;
    
        private String gender;
    
        /**
         * 设置TTL,单位秒
         */
        @Indexed(name = "idx_create_time", expireAfterSeconds = 10)
        private Date createTime = new Date();
    
    }

    创建repository

    @Repository
    public interface PersonRepository extends ReactiveMongoRepository<PersonEntity,String> {
    
        /**
         * 根据name查找Person
         * @param name
         * @return
         */
        Flux<PersonEntity> findByUserName(String name);
    }

    编写controller

    package com.xzsx.openapi.thirdparty.controller;
    
    import com.xzsx.openapi.dto.MongoDBOutput;
    import com.xzsx.openapi.thirdparty.entity.PersonEntity;
    import com.xzsx.openapi.thirdparty.repository.PersonRepository;
    import org.springframework.beans.BeanUtils;
    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.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;
    
    /**
     * @author J·K
     * @Description: TODO
     * @date 2019-04-22 10:19
     */
    @RestController
    public class IndexController
    {
        /**
         * 可以使用
         */
        @Autowired
        private PersonRepository personRepository;
    
        @GetMapping("/save")
        public Mono<PersonEntity> save(){
            PersonEntity person = new PersonEntity();
            person.setUserName("mickey");
            person.setGender("male");
            return personRepository.save(person);
        }
    
        @GetMapping("/list")
        public Flux<MongoDBOutput> list(){
            Flux<MongoDBOutput> flux = personRepository.findAll().map(x->{
                MongoDBOutput mongoDBOutput = new MongoDBOutput();
                BeanUtils.copyProperties(x,mongoDBOutput);
                return mongoDBOutput;
            });
            return flux;
        }
    
        @GetMapping("/delete/{id}")
        public Mono<String> delete(@PathVariable("id") String id){
            //没有返回值
    //        personRepository.deleteById(id);
    
            //如果要操作数据,并返回一个Mono,这时候使用flatMap
            //如果不操作数据,只是对数据做一个转换,使用map
            return personRepository.findById(id)
            .flatMap(x->
                    personRepository.deleteById(x.getId())
                    .then(Mono.just("ok")))
                    .defaultIfEmpty("not found");
        }
    
        @GetMapping("/update/{id}")
        public Mono<String> update(@PathVariable("id") String id){
            return personRepository.findById(id)
                    .flatMap(x->{
                        x.setUserName("jack");
                        return personRepository.save(x);
                    })
                    .map(x->x.toString())
                    .defaultIfEmpty("error");
        }
    
        @GetMapping("/find/{id}")
        public Mono<PersonEntity> findById(@PathVariable("id") String id){
            return personRepository.findById(id)
                    .map(x-> x)
                    .defaultIfEmpty(new PersonEntity());
        }
    
        @GetMapping("/findByName/{name}")
        public Flux<PersonEntity> findByName(@PathVariable("name") String name){
            return personRepository.findByUserName(name)
                    .map(x-> x)
                    .defaultIfEmpty(new PersonEntity());
        }
    
        @GetMapping(value = "/stream/findByName/{name}",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<PersonEntity> findByName1(@PathVariable("name") String name){
            return personRepository.findByUserName(name)
                    .map(x-> x)
                    .defaultIfEmpty(new PersonEntity());
        }
    
        public static void main(String[] args) {
            String [] strs = {"1","2","3"};
    //        List<Integer> collect = Flux.fromArray(strs).map(x -> Integer.parseInt(x))
    //                .toStream().collect(Collectors.toList());
    //        System.out.println(collect);
    
    
    //        Flux.fromArray(strs).map(x->Integer.parseInt(x))
    //        .subscribe(x->{
    //            System.out.println(x);
    //        });
    
            Flux.fromArray(strs).map(x->{
                throw new RuntimeException("error");
            })
            .subscribe(x->{
                System.out.println(x);
            },x->{
                System.out.println("error");
            });
    
        }
    
    }

    启动项目后,就可以按原来访问springboot的方式访问数据了

  • 相关阅读:
    汕头市队赛 SRM1X T1
    夏令营
    路上路径求和
    USACO 刷题记录bzoj
    整除
    Xor路
    超低延时安防直播系统webrtc-client在浏览器播放没有音频的问题如何排查解决?
    如何使用TSINGSEE青犀视频同屏功能组件EasyScreenLive通过sdk推流到腾讯云直播?
    网络穿透/云端组网/视频拉转推服务EasyNTS上云网关运维中数据库检测功能的介绍
    【解决方案】变电站智慧消防如何实现远程集中监控?EasyCVR变电站安全综合管理系统搭建
  • 原文地址:https://www.cnblogs.com/blueskyli/p/10839018.html
Copyright © 2011-2022 走看看