HATEOAS on Spring Flux/Mono response



我一直按照以下准则使用Spring HATEOAS:

https://spring.io/guides/gs/rest-hateoas/#initial

package hello;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RestController
public class GreetingController {
private static final String TEMPLATE = "Hello, %s!";
@RequestMapping("/greeting")
public HttpEntity<Greeting> greeting(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
Greeting greeting = new Greeting(String.format(TEMPLATE, name));
greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());
return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
}

现在我想使用一个存储库并输出一个 Flux/Mono 响应:

@RestController
class PersonController {
private final PersonRepository people;
public PersonController(PersonRepository people) {
this.people = people;
}
@GetMapping("/people")
Flux<String> namesByLastname(@RequestParam Mono<String> lastname) {
Flux<Person> result = repository.findByLastname(lastname);
return result.map(it -> it.getFullName());
}
}

如何在通量/单声道响应中使用Spring HATEOS?可能吗?

更新,因为支持将 HATEOAS 与 Spring Web Flux 一起使用。

public class Person extends ResourceSupport
{
public Person(Long uid, String name, String age) {
this.uid = uid;
this.name = name;
this.age = age;
}
private Long uid;
private String name;
private String age;
public Long getUid() {
return uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}

在控制器中使用上述人员,如下所示

@GetMapping("/all")
public Flux getAllPerson() {
Flux<List<Person>> data = Flux.just(persons);
return data.map(x ->  mapPersonsRes(x));
}
private List<Resource<Person>> mapPersonsRes(List<Person> persons) {
List<Resource<Person>> resources = persons.stream()
.map(x -> new Resource<>(x,
linkTo(methodOn(PersonController.class).getPerson(x.getUid())).withSelfRel(),
linkTo(methodOn(PersonController.class).getAllPerson()).withRel("person")))
.collect(Collectors.toList());
return resources;
}

或者,如果您想要一个人,您也可以使用Mono

@GetMapping("/{id}")
public Mono<Resource<Person>> getPerson(@PathVariable("id") Long id){
Mono<Person> data = Mono.justOrEmpty(persons.stream().filter(x -> x.getUid().equals(id)).findFirst());
Mono person = data.map(x -> {
x.add(linkTo(methodOn(PersonController.class).getPerson(id)).withSelfRel());
return x;
});
return person;
}

这是对Flux/Mono提供的.map功能的简单使用。 我希望这对以后的观众有所帮助。

我认为这个项目不支持(还?(Spring 框架中的新反应式支持。你最好的选择是联系维护者并为项目做出贡献(创建一个问题并解释你想要实现的目标是一个开始!

最新更新