2 Mayıs 2023 Salı

SpringJMS ActiveMQ Kullanımı

Maven
Şöyle yaparız
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
Producer
Örnek
Elimizde şöyle bir kod olsun
import org.apache.activemq.ActiveMQConnectionFactory;
@Configuration
@EnableJms
public class MQConfigHelper {
  final String BROKER_URL = "tcp://localhost:61616";
  //Enter your ActiveMQ password and username
  final String BROKER_USERNAME = "";
  final String BROKER_PASSWORD = "";

  @Bean
  public ActiveMQConnectionFactory activemqConnectionFactory() {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
    factory.setTrustAllPackages(true);
    factory.setBrokerURL(BROKER_URL);
    factory.setPassword(BROKER_USERNAME);
    factory.setUserName(BROKER_PASSWORD);
    return factory;
  }
  @Bean
  public MessageConverter messageConverter() {
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setTargetType(MessageType.TEXT);
    return converter;
  }
  @Bean
  public JmsTemplate templateConfig() {
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(activemqConnectionFactory());
    jmsTemplate.setMessageConverter(messageConverter());
    jmsTemplate.setDeliveryPersistent(true);
    return jmsTemplate;
  }
}
Mesaj gönderen taraf şöyledir
public class CarOrder {...}

public class CustomerOrder {...}

import org.springframework.jms.core.JmsTemplate;
import javax.jms.TextMessage;

@Component
public class MessageSender {
  String queueName = "carQueue";
  @Autowired
  JmsTemplate jmsTemplate;
  public void sendToQueue() {
   try {
     CarOrder carOrder = new CarOrder("Mercedes GLE", 7, 74);
     processMessageForSending(carOrder);
    } catch (Exception e) {
      ...
    }
  }
  public void processMessageForSending(Object message) 
  throws JsonProcessingException {
    String jsonObj = new ObjectMapper()
      .writer()
      .withDefaultPrettyPrinter()
      .writeValueAsString(message);
      jmsTemplate.send(queueName, messageCreator -> {
        TextMessage txtMessage = messageCreator.createTextMessage();
        txtMessage.setText(jsonObj);
        return txtMessage;
      });
  }
}
Mesaj dinleyen taraf şöyledir
import org.springframework.jms.annotation.JmsListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
@Component
public class MessageConsumer {
  @JmsListener(destination = "carQueue")
  public void queueMessageReceiver(Message receivedMessage) {
    try {
      processMessageReceived(receivedMessage);
    } catch (Exception e) {
       ...
    }
  }
  public void processMessageReceived(Message messageArg) throws JMSException {
    if (messageArg instanceof TextMessage) {
      TextMessage textMessage = (TextMessage) messageArg;
      String processedMessage = textMessage.getText();
      ... 
     }
  }
}

Hiç yorum yok:

Yorum Gönder