Skip to content

Instantly share code, notes, and snippets.

@spdeepak
Last active September 21, 2018 11:04
Show Gist options
  • Save spdeepak/5690c150c6ad5c7958b3c28e12bb9e8d to your computer and use it in GitHub Desktop.
Save spdeepak/5690c150c6ad5c7958b3c28e12bb9e8d to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.azure.servicebus.Message;
import com.microsoft.azure.servicebus.QueueClient;
import com.microsoft.azure.servicebus.ReceiveMode;
import com.microsoft.azure.servicebus.primitives.ConnectionStringBuilder;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class AzureServuceBusPublisher {
private final String connectionString;
private final String queueName;
@Autowired
public AzureServuceBusPublisher(@Value("${azure.servicebus.connection-string}") final String connectionString,
@Value("${azure.servicebus.queue-name}") final String queueName) {
this.connectionString = connectionString;
this.queueName = queueName;
}
@Async
public void send(final AnyObject anyObject) {
try {
final String json = new ObjectMapper().writeValueAsString(anyObject);
final QueueClient queueClient = new QueueClient(new ConnectionStringBuilder(connectionString, queueName), ReceiveMode.PEEKLOCK);
queueClient.send(new Message(json));
log.debug("Sent message [anyObject ID='{}', queueName='{}']", anyObject.getId(), queueClient.getQueueName());
queueClient.close();
} catch (InterruptedException | ServiceBusException | JsonProcessingException e) {
log.error(e.getMessage(), e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment