请教一下 Webflux Reactor 编程
public People getPeople(String name) { People people = getCache(name); if (people != null) { return people; } //Mono<People> people = httpService.monoRequest("http://www.xxx.com/path", People.class); people = httpService.syncRequest("http://www.xxx.com/path/info?name=" + name, People.class); setCache(msisdn, operatorInfo); return people; } private People getCache(String name) { String str = redisTemplate.opsForValue().get(name); if (str == null) { return null; } return deserialize(str); } private void setCache(String name, People people) { String str = serialize(people); redisTemplate.opsForValue().set(name, str); }
以上是一个非常简单的带有缓存的获取信息的方法,我尝试使用 Spring Webflux 来做,但是写起来发现举步维艰,尤其对于 null 值的流式条件判断根本想不出有什么办法去写
以下是我自己的理解写的,看起来非常不优雅,而且没有 null 判断,请问哪位大佬可以给个优雅的样例吗?网上的例子少得可怜
public Mono<People> getPeople(String name) { Mono<People> peopleMono = httpService .monoRequest("http://www.xxx.com/path/info?name=" + name, People.class); Mono<Boolean> setCacheMono = peopleMono.flatMap(people -> setCache(name, people)); return peopleMono .and(setCacheMono) .then(peopleMono); } private Mono<People> getnCache(String name) { return reactiveRedisTemplate.opsForValue() .get(name) .map(this::deserialize); } private Mono<Boolean> setCache(String name, People people) { return reactiveRedisTemplate.opsForValue() .set(name, serialize(people)); }