Spring cloud responsive microservice series tutorial (Chapter 10): complete code example of responsive RESTful service

This is the tenth chapter of the series of practical spring cloud responsive microservices. This chapter gives a complete code example of responsive RESTful services. It is suggested that children's shoes without previous foundation should be read first, and the chapter catalog should be placed at the end of the article.

1. Build responsive RESTful services.

In the previous chapter, we talked about how to use Spring Initializer to initialize responsive web applications, which will not be covered in this section (please review Chapter 9 contents).

Before learning the content of this chapter, you need to understand mongodb and redis. Mongodb and redis can refer to relevant materials for a comprehensive understanding, and build mongodb and redis in the local environment.

2.application.yml file configuration

server:
  port: 9801
spring:
  application:
    name: advert
  data:
    mongodb:
      uri: mongodb://localhost:27017/db_advert
  http:
    encoding:
      force: true
      charset: UTF-8
      enabled: true
  redis:
    host: 127.0.0.1
    password: 123456
logback:
  level: info

 

The above configuration code is the whole configuration of the responsive RESTful service we have learned at present. The configuration is relatively simple. spring.data.mongodb.uri: mongodb://localhost:27017/db_advert and spring.data.redis are the core configurations of our service. We know that the traditional database does not support responsive data reading, so we use mongodb and redis instead.

3. Integrated and responsive MongoDB

springboot itself provides responsive drivers for cassandra/couchbase/mongodb/redis

The blocking type spring boot starter data mongodb is changed to the responsive mongodb, which depends on spring boot starter data mongodb reactive

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

 

(1) write entity class:

/**
 * Advertising delivery
 */
@Document(collection="advert")//Collection name
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Advert implements Serializable {
    private static final long serialVersionUID = -8985545025018238754L;
    /**
     * Primary key
     */
    @Id
    private String id;
    /**
     * content
     */
    private String content;
    /**
     * Publisher
     */
    private Long userId;
    /**
     * Creation time
     */
    private Date creatData;
    /**
     * Picture address
     */
    private String imgUrl;
    /**
     * Video address
     */
    private String videoUrl;
    /**
     * Advertising type (video image)
     */
    private String advertType;
    /**
     * Today's launch area
     */
    private String launchArea;
    /**
     * Delivery time (in hours)
     */
    private int durationTime;
    /**
     * Advertising type
     */
    private int classify;
    /**
     * Billing mode
     */
    private int billingMode;
    /**
     * Display location (home page rotation, other rotation, home page other location, other)
     */
    private int displayPosition;
    /**
     * Advertising theme
     */
    private String advertTitle;
    /**
     * Need to customize display page
     */
    private int isCustom;
    /**
     * Index keywords
     */
    private String keyWords;
}

 

Where @ document declares a java class as a mongodb document. You can specify the corresponding document of this class through the collection parameter and mark it on the entity class, similar to hibernate's entity annotation. Other annotations are lombok annotations.

(2) write repository interface

import com.shmc.advert.model.po.Advert;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.data.mongodb.repository.Tailable;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface AdvertRepository extends ReactiveMongoRepository<Advert,Long> {
    @Tailable
    Flux<Advert> findBy();
}

 

Among them, @ Repository is the annotation of org.springframework.stereotype.Repository, which we should all be familiar with without explanation.

From the above code, we can clearly see that the advertiserepository inherits the ReactiveMongoRepository. ReactiveMongoRepository is the class in the maven reactive mongodb reactive that we rely on. The @ Tailable annotation is similar to the tail in Linux, which can get and push the changes of DB to the front end in the way of reactive flow.

In addition to inheriting the ReactiveMongoRepository, we can also inject MongoTemplate to operate mongodb, but MongoTemplate can not do real-time monitoring and active push. Such as:

@Autowired
MongoTemplate mongoTemplate;

 

(3) write Service interface and implementation class

Service interface:

import com.shmc.advert.model.po.Advert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public interface AdvertService {
    Mono<Advert> saveAdvert(Advert advert);
    Mono<Advert> findById(String id);
    Flux<Advert> findAll();
    Flux<Advert> findByAll();
}

 

Service implementation class:

@Service
public class AdvertServiceImpl implements AdvertService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    private AdvertRepository advertRepository;
    @Override
    public Mono<Advert> saveAdvert(Advert advert){
        advert.setId(new IdWorker().nextId());
        advert.setCreatData(new Date());
        mongoTemplate.insert(advert);
        return Mono.just(advert);
    }

    @Override
    public Mono<Advert> findById(String id){
        Query query = new Query(Criteria.where("id").is(id));
        return Mono.just(mongoTemplate.findOne(query,Advert.class));
    }

    @Override
    public Flux<Advert> findAll(){
        return advertRepository.findAll();
    }

    @Override
    public Flux<Advert> findByAll(){
        return advertRepository.findBy();
    }
}

(4) write Controller

import com.shmc.advert.model.po.Advert;
import com.shmc.advert.service.AdvertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

@RestController
@RequestMapping("/advert")
public class AdvertController {
    @Autowired
    private AdvertService advertService;

    @PostMapping("/saveAdvert")
    public Mono<Advert> saveAdvert(@RequestBody Advert advert){
        return advertService.saveAdvert(advert);
    }

    @GetMapping("/findById/{id}")
    public Mono<Advert> findById(@PathVariable String id){
        return advertService.findById(id);
    }
    /**
     * Push to the client as stream+json stream
     * @return
     */
    @GetMapping(value = "/findAllPreSec", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<Advert> findAllPreSec() {
        return advertService.findAll().delayElements(Duration.ofSeconds(1));
    }

    /**
     * Data change
     * @return
     */
    @GetMapping(value = "/findByAll", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<Advert> findByAll(){
        return advertService.findByAll();
    }
}

 

So far, we have completed all the responsive services based on RESTful service. You can see the responsive data push when the startup program accesses the "/ advert / findallprosec" interface and "/ advert/findByAll" interface.

findAllPreSec. delayElements is used to get a piece of data every second and send it to the client in the way of "asynchronous response flow".

It is specified that the MediaType is application stream JSON, that is, application/stream+json format.

You can see a record every second in the browser. Run the program, visit findByAll interface, and then test to call save interface to add advert data, or directly add Stu data through MongoDB Compass client, you will see the newly added data in real time in the page.

The next chapter will upload the code to gitee. Please download it if necessary.

Contents of series chapters

A series of practical spring cloud responsive microservices tutorials (Chapter 1)

A series of practical spring cloud responsive microservices tutorials (Chapter 2)

A series of practical spring cloud responsive microservices tutorials (Chapter 3)

A series of practical spring cloud responsive microservices tutorials (Chapter 4)

A series of practical spring cloud responsive microservices tutorials (Chapter 5)

Spring cloud responsive microservice series tutorial (Chapter 6)

Spring cloud responsive microservice series tutorial (Chapter 7)

A series of practical spring cloud responsive microservices tutorials (Chapter 8)

A series of practical spring cloud responsive microservices tutorials (Chapter 9)

Tags: Java MongoDB Spring Redis JSON

Posted on Mon, 04 Nov 2019 22:51:26 -0500 by maseeha