以下代码只能通过JMS调用。对其进行修改,使其也成为Web服务

问题描述 投票:-2回答:1

下面的代码只能通过JMS调用。对其进行修改,使其也成为Web服务。

@MessageDriven(name = "testMDB", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/test") 
})

public class MessageOne implements MessageListener {
public void onMessage(Message message) {
    for (int i = 0; i < 1000; i++) {
        Process(i);
    }
}

private void Process(int i) throws Exception {
    Thread.sleep(5000); //This sleep represents really complex code that takes 5 seconds to run and cannot be further optimised                              
}
}
java spring-boot jms
1个回答
0
投票

要从REST发送消息,您可以将简单消息模板用于简单的协议,例如stomp或仅使用JmsTemplate

@Controller
public class MessageOneSender implements ApplicationListener<SessionDisconnectEvent> {

    private static final Logger log = LoggerFactory.getLogger(MessageOneSender.class);

    private final SimpMessageSendingOperations messagingTemplate;

    public MessageOne(SimpMessageSendingOperations messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @MessageMapping("/queue/test")
    @SendTo("queue/test")
    public MyDTO sendMessage(@Payload MyDTO myDTO, Principal principal) {
        // TODO
    }

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        // or this way
        messagingTemplate.convertAndSend("queue/test", "message");
    }
}

上面的代码用于通过rest接收消息并将其传递给JMS。要从消息侦听器重用代码,您可能应该添加@JmsListener方法,将代码移至@Service,然后可以从rest&从侦听器方法中调用它:

@Component
public class MyDTOReceiver {

  @Autowired
  private MyService service;

  @JmsListener(destination = "queue/test", containerFactory = "myFactory")
  public void receiveMessage(MyDTO dto) {
    System.out.println("Received <" + dto + ">");
    service.save(dto);
  }
}


@RestController
@RequestMapping("/api")
public class Example {

  @Autowired 
  private JmsTemplate jmsTemplate;
  @Autowired 
  private MyService service;

  @PostMapping("/save")
  public void save(@RequestBody MyDTO dto) {
    service.save(dto);

    System.out.println("passing to another queue.");
    jmsTemplate.convertAndSend("queue/test2", dto);
  }
}

@Service
public class MyService {
  public void save(MyDTO dto) {}
}
© www.soinside.com 2019 - 2024. All rights reserved.