can't receive MQTT message using Paho under spring integration - spring-boot

#Configuration
#SpringBootApplication
public class WyymqttApplication {
#Value("${spring.mqtt.username}")
private String username;
#Value("${spring.mqtt.password}")
private String password;
#Value("${spring.mqtt.url}")
private String hostUrl;
#Value("${spring.mqtt.client.id}")
private String clientId;
#Value("${spring.mqtt.default.topic}")
private String defaultTopic;
private static final Log LOGGER = LogFactory.getLog(WyymqttApplication.class);
public static void main(final String... args) {
SpringApplication.run(WyymqttApplication.class, args);
}
#Bean
public MqttConnectOptions getMqttConnectOptions() {
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
mqttConnectOptions.setServerURIs(new String[]{hostUrl});
mqttConnectOptions.setKeepAliveInterval(2);
return mqttConnectOptions;
}
#Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
factory.setConnectionOptions(getMqttConnectOptions());
return factory;
}
//publisher
#Bean
public IntegrationFlow mqttOutFlow() {
return IntegrationFlows.from(CharacterStreamReadingMessageSource.stdin(),
e -> e.poller(Pollers.fixedDelay(1000)))
.transform(p -> p + " sent to MQTT")
.handle(mqttOutbound())
.get();
}
#Bean
#ServiceActivator(inputChannel = "mqttOutboundChannel")
public MessageHandler mqttOutbound() {
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientId, mqttClientFactory());
messageHandler.setAsync(true);
messageHandler.setDefaultTopic(defaultTopic);
return messageHandler;
}
#Bean
public MessageChannel mqttOutboundChannel() {
return new DirectChannel();
}
#MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateway {
void sendToMqtt(String data, #Header(MqttHeaders.TOPIC) String topic);
}
// consumer
#Bean
public IntegrationFlow mqttInFlow() {
return IntegrationFlows.from(mqttInbound())
.transform(p -> p + ", received from MQTT")
.handle(logger())
.get();
}
private LoggingHandler logger() {
LoggingHandler loggingHandler = new LoggingHandler("INFO");
loggingHandler.setLoggerName("siSample");
return loggingHandler;
}
#Bean
public MessageProducerSupport mqttInbound() {
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("siSampleConsumer",
mqttClientFactory(), defaultTopic);
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
return adapter;
}
}
Here is my code.Above is my code, I use ActiveMQ as a broker. When I send a message on the command line, the message can be sent, but I can't receive it.
Messages like this:
2018-08-06 11:18:02.107 INFO 2508 --- [iSampleConsumer] siSample : hello stackoverflow sent to MQTT, received from MQTT

Related

Listener not getting message in REDIS PubS/ub with Spring Boot

I am relatively new to Redis Pub/Sub. I have integrated this recently in my Spring Boot application.
Redis Pub/Sub configuration is as follows:
#Configuration
public class RedisPubSubConfiguration {
#Bean
public RedisMessageListenerContainer messageListenerContainer(RedisConnectionFactory
connectionFactory,
#Qualifier("topicAdapterPair")
List<Pair
<Topic,
MessageListenerAdapter>>
channelAdaperPairList) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
for (Pair<Topic, MessageListenerAdapter> chanelAdapterPair : channelAdaperPairList) {
container.addMessageListener(chanelAdapterPair.getValue(),
chanelAdapterPair.getKey());
}
container.setConnectionFactory(connectionFactory);
return container;
}
#Bean("msg-listener-adptr-1")
public MessageListenerAdapter messageListnerAdapter1(
#Qualifier("message-listener-1")
MessageListener listener) {
return new MessageListenerAdapter(listener, REDIS_RECEIVER_METHOD_NAME);
}
#Bean("message-listener-1")
public MessageListener messageListener1(ManagerProxy managerProxy) {
return new MessageListener1(managerProxy);
}
#Bean("message-sender-1")
public MessageSender messageSender1(RedisTemplate redisTemplate,
#Value("${chnlTopicName1}")
String channelTopicName) {
return new MessageSender1(redisTemplate, channelTopicName);
}
#Bean
#Qualifier("topicAdapterPair")
public Pair<Topic, MessageListenerAdapter> getTopicListenerAdapterpair1(
#Value("${chnlTopicName1}") String channelTopicName,
#Qualifier("msg-listener-adptr-1")
MessageListenerAdapter messageListenerAdapter) {
return Pair.of(new ChannelTopic(channelTopicName), messageListenerAdapter);
}
#Bean("msg-listener-adptr-2")
public MessageListenerAdapter messageListnerAdapter2(
#Qualifier("message-listener-2")
MessageListener listener) {
return new MessageListenerAdapter(listener, REDIS_RECEIVER_METHOD_NAME);
}
#Bean("message-listener-2")
public MessageListener messageListener2(NotificationServiceImpl notificationService) {
return new MessageListener2(notificationService);
}
#Bean("message-sender-2")
public MessageSender messageSender2(RedisTemplate redisTemplate,
#Value("${chnlTopicName2}")
String channelTopicName) {
return new MessageSender2(redisTemplate, channelTopicName);
}
#Bean
#Qualifier("topicAdapterPair")
public Pair<Topic, MessageListenerAdapter> getTopicListenerAdapterPair2(
#Value("${chnlTopicName2}") String channelTopicName,
#Qualifier("msg-listener-adptr-2")
MessageListenerAdapter messageListenerAdapter) {
return Pair.of(new ChannelTopic(channelTopicName), messageListenerAdapter);
}
}
MessageSender2 is as follows:
public class MessageSender2 implements MessageSender<MyDTO> {
private final RedisTemplate<String, Object> redisTemplate;
private final String chanelName;
public MessageSender2(
RedisTemplate<String, Object> redisTemplate,
String chanelName) {
this.redisTemplate = redisTemplate;
this.chanelName = chanelName;
}
#Override
public void send(MyDTO myDTO) {
redisTemplate.convertAndSend(chanelName, myDTO);
}
}
MessageListener2 is as follows:
public class MessageListener2 implements MessageListener<EventDTO> {
private static final Logger LOGGER = LoggerFactory
.getLogger(MessageListener2.class);
private final NotificationService notificationService;
public MessageListener1(NotificationServiceImpl notificationService) {
this.notificationService = notificationService;
}
#Override
public void receiveMessage(MyDTO message) {
LOGGER.info("Received message : {} ", message); <--HERE MESSAGE IS NOT COMING EVEN AFTER PUBLISHING MESSAGE TO THE ASSOCIATED TOPIC FROM PUBLISHER
Type type = message.getType();
...
}
}
MessageSender1 is as follows:
public class MessageSender1 implements MessageSender<String> {
private final RedisTemplate<String, Object> redisTemplate;
private final String chanelName;
public MessageSender1(
RedisTemplate<String, Object> redisTemplate,
String chanelName) {
this.redisTemplate = redisTemplate;
this.chanelName = chanelName;
}
#Override
public void send(String message) {
redisTemplate.convertAndSend(chanelName, message);
}
}
Associated listener is follows:
public class MessageListener1 implements MessageListener<String> {
private static final Logger LOGGER = LoggerFactory
.getLogger(MessageListener1.class);
private final ManagerProxy managerProxy;
public MessageListener1(ManagerProxy managerProxy) {
this.managerProxy = managerProxy;
}
public void receiveMessage(String message) {
LOGGER.info("Received message : {} ", message);
managerProxy.refresh();
}
}
Here though MessageSender1 and associated message listener are working fine, I don't understand what I did with MessageSender2 and associated listener, because of which I am not able to receive message in the listener.

Do i need to add anything else in config file?

This is my config class.
#Configuration
public class MessageConfig {
public static final String KEY = "anil_key";
public static final String EXCHANGE = "anil_exchange_one";
public static final String QUEUE = "anil_queue";
#Bean
public Queue queue() {
return new Queue(QUEUE, false);
}
#Bean
public DirectExchange exchange() {
return new DirectExchange(EXCHANGE);
}
#Bean
public Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(KEY);
}
#Bean
public MessageConverter converter() {
return new Jackson2JsonMessageConverter();
}
#Bean
public AmqpTemplate template(ConnectionFactory connectionFactory) {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(converter());
return rabbitTemplate;
}
and this is my publisher class
#RestController
#RequestMapping("/order")
public class Publisher {
#Autowired
private AmqpTemplate rabbitTemplate;
#PostMapping("/{restaurentName}")
public String bookOrder(#RequestBody Order order,#PathVariable String restaurentName) {
order.setOrderId(UUID.randomUUID().toString());
OrderStatus status = new OrderStatus(order,"progress","successfully received");
rabbitTemplate.convertAndSend(MessageConfig.EXCHANGE, MessageConfig.KEY, status);
return "success";
}
I am getting below error.
2020-10-04 14:28:24.628 ERROR 17008 --- [ 127.0.0.1:5672] o.s.a.r.c.CachingConnectionFactory : Channel shutdown: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no exchange 'anil_exchange_one' in vhost '/', class-id=60, method-id=40).
You need a RabbitAdmin #Bean to declare the exhange/queue/binding.
#Bean
RabbitAdmin admmin(ConnectionFactory cf) {
return new Rabbitadmin(cf);
}

rabbitmq overflow redirecting messages - issue

I am using rabbit mq 3.7.4 and have a queue with x-max-length:3 and x-overflow:reject-publish, I am trying to redirect those messages which comes once queue reaches it's max limit (i.efrom 4th message ...nth message) to a deadletter queue but was unable to achieve.
kibndly help with the same
My configuration:
#Configuration
#EnableAutoConfiguration
public abstract class AMQPConfig {
#Value("${overflow-queue.exchange}")
private String queueExchange;
#Value("${overflow-queue.routingkey}")
private String throttleRoutingKey;
#Value("${overflow.queue}")
private String queue;
/**
* abstract ampqTemplate method
*/
public abstract AmqpTemplate getAmqpTemplate();
#Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
#Bean
public TopicExchange salesExchange() {
return new TopicExchange(queueExchange);
}
#Bean
public Queue salesQueue() {
return //QueueBuilder.durable(throttleQueue)
QueueBuilder.durable(queue)
.withArgument("x-max-length", 3)
.withArgument("x-overflow", "reject-publish")
.withArgument("x-dead-letter-exchange",queueExchange)
.withArgument("x-dead-letter-routing-key","deadletter-routing-key")
.build();
}
#Bean
public Binding declareSalesQueueBinding() {
return BindingBuilder.bind(salesQueue()).to(salesExchange()).with(queue);//with(throttleQueue);
}
#Bean
public MappingJackson2MessageConverter consumerJackson2MessageConverter() {
return new MappingJackson2MessageConverter();
}
#Bean
public DefaultMessageHandlerMethodFactory messageHandlerMethodFactory() {
DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setMessageConverter(consumerJackson2MessageConverter());
return factory;
}
}
MY PRODUCER:
#Service
public class Producer {
private static long sentMessageCount =0L;
#Autowired
private AmqpTemplate rabbitTemplate;
#Value("${overflow.queue}")
String queueName;
#Scheduled(initialDelay = 5000, fixedRate = 10)
public void queueSender() {
long x=++sentMessageCount;
rabbitTemplate.convertAndSend(queueName,"{'empId':'"+x+"','empName':'raj'}");
}
}

Spring Integration FTP Outbound Gateway console output

In the Spring Integration documentation example for ftp outbound gateway with Java configuration (16.8.1), how do I log the payload of the reply channel to the console?
Add a WireTap #Bean and wire its MessageChannel to a LoggingHandler.
Add the wire tap as a ChannelInterceptor to the gateway output channel.
Or, use the .wiretap() when using the Java DSL.
Documentation here.
EDIT
Java Config:
#SpringBootApplication
public class So49308064Application {
public static void main(String[] args) {
SpringApplication.run(So49308064Application.class, args);
}
#Bean
public ApplicationRunner runner (Gate gate) {
return args -> {
List<String> list = gate.list("foo");
System.out.println("Result:" + list);
};
}
#ServiceActivator(inputChannel = "ftpLS")
#Bean
public FtpOutboundGateway getGW() {
FtpOutboundGateway gateway = new FtpOutboundGateway(sf(), "ls", "payload");
gateway.setOption(Option.NAME_ONLY);
gateway.setOutputChannelName("results");
return gateway;
}
#Bean
public MessageChannel results() {
DirectChannel channel = new DirectChannel();
channel.addInterceptor(tap());
return channel;
}
#Bean
public WireTap tap() {
return new WireTap("logging");
}
#ServiceActivator(inputChannel = "logging")
#Bean
public LoggingHandler logger() {
LoggingHandler logger = new LoggingHandler(Level.INFO);
logger.setLogExpressionString("'Files:' + payload");
return logger;
}
#Bean
public DefaultFtpSessionFactory sf() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost("...");
sf.setUsername("...");
sf.setPassword("...");
return sf;
}
#MessagingGateway(defaultRequestChannel = "ftpLS", defaultReplyChannel = "results")
public interface Gate {
List<String> list(String directory);
}
}
.
2018-03-29 09:04:20.383 INFO 15158 --- [ main] o.s.integration.handler.LoggingHandler
: Files:bar.tx,bar.txt,baz.txt
Result:[bar.tx, bar.txt, baz.txt]
Java DSL:
#SpringBootApplication
public class So49308064Application {
public static void main(String[] args) {
SpringApplication.run(So49308064Application.class, args);
}
#Bean
public ApplicationRunner runner (Gate gate) {
return args -> {
List<String> list = gate.list("foo");
System.out.println("Result:" + list);
};
}
#Bean
public IntegrationFlow flow() {
return f -> f
.handle((Ftp.outboundGateway(sf(), "ls", "payload").options(Option.NAME_ONLY)))
.log(Level.INFO, "lsResult", "payload")
.bridge(); // needed, otherwise log ends the flow.
}
#Bean
public DefaultFtpSessionFactory sf() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost("...");
sf.setUsername("...");
sf.setPassword("...");
return sf;
}
#MessagingGateway(defaultRequestChannel = "flow.input")
public interface Gate {
List<String> list(String directory);
}
}
.
2018-03-29 09:12:28.991 INFO 16638 --- [ main] lsResult
: [bar.tx, bar.txt, baz.txt]
Result:[bar.tx, bar.txt, baz.txt]

How to create and hold multiple connections in Spring Integration

I have one server and number of clients, server will send response and waits for acknowledgement, additionally I want to hold that connection forever for next message and acknowledgement how should i create these connection in Spring Integration. I read about Spring integration, i couldn't find out the solution for holding the connection.
public class ClientCall {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext ctx = new AnnotationConfigApplicationContext(GatewayConfig.class);
GatewayService gatewayService = ctx.getBean(GatewayService.class);
//int i=0;
Message message = new Message();
/*while(i<4)
{*/
message.setPayload("It's working");
gatewayService.sendMessage(message);
/* i++;
}*/
}
}
#Service
public interface GatewayService<T> {
public void sendMessage(final T payload);
public void receiveMessage(String response);
}
#EnableIntegration
#IntegrationComponentScan
#Configuration
#ComponentScan(basePackages = "com.gateway.service")
public class GatewayConfig {
// #Value("${listen.port:6788}")
private int port = 6785;
#Autowired
private GatewayService<Message> gatewayService;
#MessagingGateway(defaultRequestChannel = "sendMessageChannel")
public interface Gateway {
void viaTcp(String payload);
}
#Bean
public AbstractClientConnectionFactory clientCF() {
TcpNetClientConnectionFactory clientConnectionFactory = new TcpNetClientConnectionFactory("localhost",this.port);
clientConnectionFactory.setSingleUse(true);
return clientConnectionFactory;
}
#Bean
#ServiceActivator(inputChannel = "sendMessageChannel")
public MessageHandler tcpOutGateway(AbstractClientConnectionFactory connectionFactory) {
TcpOutboundGateway outGateway = new TcpOutboundGateway();
outGateway.setConnectionFactory(connectionFactory);
outGateway.setAsync(true);
outGateway.setOutputChannel(receiveMessageChannel());
outGateway.setRequiresReply(true);
outGateway.setReplyChannel(receiveMessageChannel());
return outGateway;
}
#Bean
public MessageChannel sendMessageChannel() {
DirectChannel channel = new DirectChannel();
return channel;
}
#Bean
public MessageChannel receiveMessageChannel() {
DirectChannel channel = new DirectChannel();
return channel;
}
#Transformer(inputChannel = "receiveMessageChannel", outputChannel = "processMessageChannel")
public String convert(byte[] bytes) {
return new String(bytes);
}
#ServiceActivator(inputChannel = "processMessageChannel")
public void upCase(String response) {
gatewayService.receiveMessage(response);
}
#Transformer(inputChannel = "errorChannel", outputChannel = "processMessageChannel")
public void convertError(byte[] bytes) {
String str = new String(bytes);
System.out.println("Error: " + str);
}
}
public class Message {
private String payload;
// getter setter
}
#Service
public class GatewayServiceImpl implements GatewayService<Message> {
#Autowired
private Gateway gateway;
#Autowired
private GatewayContextManger<String, Object> gatewayContextManger;
#Override
public void sendMessage(final Message message) {
new Thread(new Runnable() {
#Override
public void run() {
gateway.viaTcp(message.getPayload());
}
}).start();
}
#Override
public void receiveMessage(final String response) {
new Thread(new Runnable() {
#Override
public void run() {
Message message = new Message();
message.setPayload(response);
Object obj = message;
//Object obj = gatewayContextManger.get(message.getPayload());
synchronized (message) {
obj.notify();
System.out.println("Message Received : "+message.getPayload());
}
}
}).start();
}
}
You have: clientConnectionFactory.setSingleUse(true); This means the connection will be closed after the request; leave it false (default) to keep the connection open.

Resources