I'm a beginner in programming (and Java too) and I need to implement a service that shows changes in real time, I'm trying to use WebSocket for this. I have the following action:
@Scheduled(fixedRate = 100000)
public void sendRealTimeUpdates() {
List<OrdemDeServico> ordemEmProducao = repository.findByStatus("Em Produção");
List<EmProducaoDTO> dtos = ordemEmProducao.stream()
.map(this::convertToDto)
.collect(Collectors.toList());
messagingTemplate.convertAndSend("/topic/ordemDeServico", dtos);
}
However, instead of performing this action every 1 minute, I'd like it to perform a change in the status field of my OrdemDeServico class each time. Here is the class update function
@Transactional
public OrdemDeServicoDTO update(Long id, OrdemDeServicoDTO dto){
try{
OrdemDeServico entity = repository.getReferenceById(id);
copyDtoToEntity(dto, entity);
if(dto.getTechnicianId() != null && dto.getTechnicianId() != 0){
Tecnico tecnico = tecnicoRepository.findById(dto.getTechnicianId())
.orElseThrow(() -> new ResourceNotFoundException("Tecnico não encontrado"));
entity.setTechnician(tecnico);
} else {
entity.setTechnician(null);
}
entity = repository.save(entity);
return new OrdemDeServicoDTO(entity);
} catch (EntityNotFoundException e){
throw new ResourceNotFoundException("Nenhuma Ordem de Serviço encontrada com o id: " + id);
}
}
I thought about putting an if/else directly inside the update method, but I don't know if that would be good practice:
@Transactional
public OrdemDeServicoDTO update(Long id, OrdemDeServicoDTO dto){
try{
OrdemDeServico entity = repository.getReferenceById(id);
copyDtoToEntity(dto, entity);
if(dto.getTechnicianId() != null && dto.getTechnicianId() != 0){
Tecnico tecnico = tecnicoRepository.findById(dto.getTechnicianId())
.orElseThrow(() -> new ResourceNotFoundException("Tecnico não encontrado"));
entity.setTechnician(tecnico);
} else {
entity.setTechnician(null);
}
entity = repository.save(entity);
if(entity.getStatus().equals("Em Produção")){
EmProducaoDTO emProducaoDto = convertToDto(entity);
messagingTemplate.convertAndSend("/topic/ordemDeServico", emProducaoDto);
}
return new OrdemDeServicoDTO(entity);
} catch (EntityNotFoundException e){
throw new ResourceNotFoundException("Nenhuma Ordem de Serviço encontrada com o id: " + id);
}
}
It may be obvious to most people, but I'm still learning, thanks guys.
I think you should use something like this:
Dto.java:
MessagingService.java:
NotifierService.java:
DtoUpdateService.java:
UpdaterService.java:
Main: