【问题标题】:I need to make Service reactive without repository [closed]我需要在没有存储库的情况下使服务反应[关闭]
【发布时间】:2019-04-16 14:41:18
【问题描述】:

我的任务是使用 Flux/Mono 使 UserService 具有响应性。

我了解 Flux 和 Mono 的工作原理,但它们仅用于存储库而不是数组列表。

UserServiceImpl:

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserServiceImpl implements UserService {

    private List<User> users = new ArrayList<>();

    @PostConstruct
    public void postConstruct() {
        this.users.add(User.builder()
                        .id(1L)
                        .username("username1")
                        .age(14)
                        .build());
    }

    @Override
    public User findOne(Long userId) {
        LOGGER.info("UserService: execute findOne(userId) method");
        return this.users.stream()
                .filter(user -> user.getId().equals(userId))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<User> findAll() {
        LOGGER.info("UserService: execute findAll() method");

        return this.users;
    }

    @Override
    public void add() {
        LOGGER.info("UserService: execute add() method");

        this.users.add(User.builder()
                .id(3L)
                .username("username3")
                .age(34)
                .build());
    }
}

【问题讨论】:

    标签: java spring-boot reactive-programming project-reactor reactor


    【解决方案1】:

    您可以从 List 中创建 Flux。例如:

    Flux<User> userStream = Flux.fromIterable(users)
    

    或者如果需要退回一个

    Flux.just(user)
    Mono.just(user)
    

    在现有流中增加价值

    userStream = Flux.concat(userStream, Flux.just(newUser));
    

    更多详情: https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 2014-04-21
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多