Код: Выделить всё
@Service
@RequiredArgsConstructor
public class PublisherService {
@Value("someTopic")
private String someTopic;
private final TransactionTemplate transactionTemplate;
private final tokenRepository tokenRepository;
private final SpecificDataMapper specificDataMapper ;
private final PubSubTemplate pubSubTemplate;
public void publish(Optional someParam) {
transactionTemplate.executeWithoutResult(transactionStatus -> {
try (Stream stream = getTokenStream(someParam)) {
stream.forEach(this::publishMessage);
}
});
}
private Stream getTokenStream(Optional someParam) {
return someParam
.map(SomeParam::getElement)
.map(Formatter::getDateTime)
.map(tokenRepository::streamAllByLastModifiedOn)
.orElse(tokenRepository.streamAll());
}
private void publishMessage(token token) {
TokenDto payload = specificDataMapper.fromtoken(token);
pubSubTemplate.publish(someTopic, payload);
}
}
< /code>
Ниже приведен тестовый пример для того же. < /p>
@Test
void test() {
Optional someParam = Optional.empty();
String TOPIC = "topic";
Token token = getToken();
Stream tokenStream = Stream.of(token);
TokenDto tokenDto = getDto();
when(specificDataMapper.fromToken(token)).thenReturn(tokenDto);
doAnswer(invocation -> {
TransactionCallbackWithoutResult callback = new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
Stream stream = tokenRepository.streamAll();
stream.forEach(t -> {
TokenDto payload = specificDataMapper.fromToken(t);
pubSubTemplate.publish(TOPIC, payload);
});
}
};
callback.doInTransaction(null);
return null;
}).when(transactionTemplate).executeWithoutResult(any());
doReturn(tokenStream).when(tokenRepository).streamAll();
publisherService.publishservice(someParam);
verify(pubSubTemplate).publish(eq(TOPIC), eq(tokenDto));
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... n-template