How to Capture ApplicatonEvent in Spring boot integration test? - spring

The issue is that Application Event is not being captured in Spring boot test While it works fine for files listening to event in app project.
I want to capture an ApplicationEvent in Spring boot test(don't want to do Unit testing). My goal is to capture this application event and then perform few tasks in my test to verify the end-to-end functionality. Since, the event is not being captured in test case so I am not able to write integration tests.
Please let me know what is wrong with the code.
Thanks All.
package com.example.demo;
import org.springframework.context.ApplicationEvent;
public class CacheRefreshEvent extends ApplicationEvent {
private String message;
private static final long serialVersionUID = 1L;
public CacheRefreshEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
package com.example.demo;
import org.springframework.context.ApplicationEvent;
public class CacheRefreshCompleteEvent extends ApplicationEvent {
private String message;
private static final long serialVersionUID = 1L;
public CacheRefreshCompleteEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
package com.example.demo;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
#Component
public class CaptureCacheRefreshCompleteEvent implements ApplicationListener<CacheRefreshCompleteEvent> {
private ApplicationEventPublisher applicationEventPublisher;
void applicationEvent() throws InterruptedException {
applicationEventPublisher.publishEvent(new CacheRefreshEvent(this, "event triggered from SolrUtilitiesTest()"));
Thread.sleep(5000);
System.out.println("Finished execution of test.");
}
public void onApplicationEvent(CacheRefreshCompleteEvent cs) {
System.out.println("gotcha in CaptureCachedRefreshCompleteEvent");
}
public void setApplicationEventPublisher(ApplicationEventPublisher arg0) {
this.applicationEventPublisher = arg0;
}
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#DirtiesContext
#SpringBootTest
class DemoApplicationTests implements ApplicationEventPublisherAware, ApplicationListener<CacheRefreshCompleteEvent> {
#Autowired
private ApplicationEventPublisher applicationEventPublisher;
#Test
void applicationEvent() throws InterruptedException {
applicationEventPublisher.publishEvent(new CacheRefreshEvent(this, "event triggered from Springboot test"));
for(int i=0; i< 20; i ++) {
Thread.sleep(1000);
}
System.out.println("Finished execution of test.");
}
public void onApplicationEvent(CacheRefreshCompleteEvent cs) {
System.out.println("gotcha");
}
#Override
public void setApplicationEventPublisher(ApplicationEventPublisher arg0) {
this.applicationEventPublisher = arg0;
}
}

One way could be to create a very simple listener with #TestComponent inside your test and autowire it as a #MockBean.
Proof of concept (tested with Spring Boot 2.2 and 2.1):
#SpringBootTest
public class PublishTest {
#Autowired
private ApplicationEventPublisher applicationEventPublisher;
#MockBean
private Consumer consumer;
#Test
public void test() {
applicationEventPublisher.publishEvent(new TestEvent(this));
// events are synchronous by default
verify(consumer).consumeEvent(any(TestEvent.class));
}
#TestComponent
private static class Consumer {
#EventListener
public void consumeEvent(TestEvent testEvent) {
}
}
private static class TestEvent extends ApplicationEvent {
public TestEvent(Object source) {
super(source);
}
}
}

Related

Junit Test for Controller with parameters

Hi I'm trying to write Junit test for a controller but cant seem to find the proper approach can anyone please suggest how could write a junit test case for the following controller:
Contoller Class
public final class Contoller {
private static final Logger logger = LoggerFactory.getLogger(LiabilityContoller.class);
#Autowired
DemoService demoService;
#GetMapping("/report")
public ResponseEntity<String> getCollection(#RequestParam(name="cohort")String cohort){
List<Book> collection=demoService.getRecords(amount);
bookUtils.writeDataIntoCSVFile(collection, amount);
uploadReportsFilesToSftp(amount);
return new ResponseEntity<String>(" Files Are Generated", HttpStatus.OK);
}
Service class:
#Service
public class DemoService{
#Autowired
DemoRepository demoRepository;
public List<Liability> getRecords(String amount) {
List<Book> list=demoRepository.getRecordsByAmount(amount);
return list;
}
}
Repository
public interface DemoRepository extends JpaRepository<Book,Long>{
#Query(value="Select name,amount from Book where amount=:amount",
List<Book>getRecordsByAmount(String amount);
}
Utility:
public static void writeDataIntoReportsCSVFile(final List<Book> collection,final String amount,final String sftpLocalFile) {
try {
FileWriter FileWriter1 = new FileWriter(sftpLocalFile+"demo.csv");
CSVPrinter FilePrinter1 = new CSVPrinter(FileWriter1, CSVFormat.EXCEL);
printReportsHeader(FileWriter1);
for (Liability obj : collection) {
FilePrinter1.printRecord(obj.getName(),obj.getAmount());
}
FilePrinter1.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void printReportsHeader(CSVPrinter FilePrinter1) {
try {
FilePrinter1.printRecord("NAME","AMOUNT");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How could I test this controller what could be the best way to do so?
When you want to unit test a Spring application, the high level idea would be to write tests for the repository layer first, then write unit tests for the service, and then finally the controller layer.
Assuming that you have unit tests for DemoService, bookUtils, and uploadReportsFilesToSftp the Test for the controller would be exactly as below.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#ExtendWith(SpringExtension.class)
#WebMvcTest(Controller.class)
class ControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private DemoService jsonFileService;
#Test
void getCollection() throws Exception {
Mockito.doNothing().when(jsonFileService.getRecords(any()));
// similar stubbings here
this.mockMvc.perform(
get("/report")
.param("cohort", "testCohortValue")
).andExpect(
status().isOk()
);
}
}

How to wait for a spring jms listener thread to finish executing in Junit test

I have a spring boot application that uses spring-JMS. Is there any way to tell the test method to wait the jms lister util it finishes executing without using latches in the actual code that will be tested?
Here is the JMS listener code:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import javax.jms.Message;
import javax.jms.QueueSession;
#Component
public class MyListener {
#Autowired
MyProcessor myProcessor;
#JmsListener(destination = "myQueue", concurrency = "1-4")
private void onMessage(Message message, QueueSession session) {
myProcessor.processMessage(message, session);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.jms.Message;
import javax.jms.QueueSession;
#Component
public class MyProcessor {
public void processMessage(Message msg, QueueSession session) {
//Here I have some code.
}
}
import org.apache.activemq.command.ActiveMQTextMessage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.QueueSession;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
#SpringBootTest
#ExtendWith(SpringExtension.class)
#ActiveProfiles("test")
public class IntegrationTest {
#Autowired
private JmsTemplate JmsTemplate;
#Test
public void myTest() throws JMSException {
Message message = new ActiveMQTextMessage();
jmsTemplate.send("myQueue", session -> message);
/*
Here I have some testing code. How can I tell the application
to not execute this testing code until all JMS lister threads
finish executing.
*/
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.util.SocketUtils;
import javax.jms.ConnectionFactory;
#EnableJms
#Configuration
#Profile("test")
public class JmsTestConfig {
public static final String BROKER_URL =
"tcp://localhost:" + SocketUtils.findAvailableTcpPort();
#Bean
public BrokerService brokerService() throws Exception {
BrokerService brokerService = new BrokerService();
brokerService.setPersistent(false);
brokerService.addConnector(BROKER_URL);
return brokerService;
}
#Bean
public ConnectionFactory connectionFactory() {
return new ActiveMQConnectionFactory(BROKER_URL);
}
#Bean
public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
return jmsTemplate;
}
}
Note: Is it applicable to solve this without adding testing purpose code to the implementation code (MyListener and MyProcessor).
Proxy the listener and add an advice to count down a latch; here's one I did for a KafkaListener recently...
#Test
public void test() throws Exception {
this.template.send("so50214261", "foo");
assertThat(TestConfig.latch.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(TestConfig.received.get()).isEqualTo("foo");
}
#Configuration
public static class TestConfig {
private static final AtomicReference<String> received = new AtomicReference<>();
private static final CountDownLatch latch = new CountDownLatch(1);
#Bean
public static MethodInterceptor interceptor() {
return invocation -> {
received.set((String) invocation.getArguments()[0]);
return invocation.proceed();
};
}
#Bean
public static BeanPostProcessor listenerAdvisor() {
return new ListenerWrapper(interceptor());
}
}
public static class ListenerWrapper implements BeanPostProcessor, Ordered {
private final MethodInterceptor interceptor;
#Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
public ListenerWrapper(MethodInterceptor interceptor) {
this.interceptor = interceptor;
}
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Listener) {
ProxyFactory pf = new ProxyFactory(bean);
NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(this.interceptor);
advisor.addMethodName("listen");
pf.addAdvisor(advisor);
return pf.getProxy();
}
return bean;
}
}
(but you should move the countDown to after the invocation proceed()).
A method annotated with #JmsListener deletes the message after it finishes, so a good option is to read the queue for existing messages and assume the queue is empty after your method is done. Here is the piece of code for counting the messages from the queue.
private int countMessages() {
return jmsTemplate.browse(queueName, new BrowserCallback<Integer>() {
#Override
public Integer doInJms(Session session, QueueBrowser browser) throws JMSException {
return Collections.list(browser.getEnumeration()).size();
}
});
}
Following is the code for testing the countMessages() method.
jmsTemplate.convertAndSend(queueName, "***MESSAGE CONTENT***");
while (countMessages() > 0) {
log.info("number of pending messages: " + countMessages());
Thread.sleep(1_000l);
}
// continue with your logic here
I've based my solution on the answer given by Gary Russell, but rather put the CountDownLatch in an Aspect, using Spring AOP (or the spring-boot-starter-aop variant).
public class TestJMSConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(TestJMSConfiguration.class);
public static final CountDownLatch countDownLatch = new CountDownLatch(1);
#Component
#Aspect
public static class LatchCounterAspect {
#Pointcut("execution(public void be.infrabel.rocstdm.application.ROCSTDMMessageListener.onMessage(javax.jms.TextMessage))")
public void onMessageMethod() {};
#After(value = "onMessageMethod()")
public void countDownLatch() {
countDownLatch.countDown();
LOGGER.info("CountDownLatch called. Count now at: {}", countDownLatch.getCount());
}
}
A snippet of the test:
JmsTemplate jmsTemplate = new JmsTemplate(this.embeddedBrokerConnectionFactory);
jmsTemplate.convertAndSend("AQ.SOMEQUEUE.R", message);
TestJMSConfiguration.countDownLatch.await();
verify(this.listenerSpy).putResponseOnTargetQueueAlias(messageCaptor.capture());
RouteMessage outputMessage = messageCaptor.getValue();
The listenerSpy is a #SpyBean annotated field of the type of my MessageListener. The messageCaptor is a field of type ArgumentCaptor<MyMessageType> annotated with #Captor. Both of these are coming from mockito so you need to run/extend your test with both MockitoExtension (or -Runner) along with the SpringExtension (or -Runner).
My code puts an object on an outbound queue after processing the incoming message, hence the putResponseOnTargetQueueAlias method. The captor is to intercept that object and do my assertions accordingly. The same strategy could be applied to capture some other object in your logic.

JUnit Platform Launcher start TestClass with Injected Spring Beans

I try to run a testclass with the JUnit Platform Launcher. The Testclass contains some #Autowired Components. The issue is, that the injection doesn't seem to work. Is that even possible with JUnit Platform?
My code is as follows:
App.java
#SpringBootApplication(scanBasePackages = "com.mytests")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Component
import org.springframework.stereotype.Component;
#Component
public class SomeBean {
public String returnSuccess() {
return "SUCCESS";
}
}
Testclass
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class SomeTests {
#Autowired
private SomeBean aBean;
#Test
public void testSuccess() throws Exception {
String result = aBean.returnSuccess();
assertTrue(result.equals("SUCCESS"));
}
}
Controller which calls the test class
#RestController
public class TestController {
#RequestMapping("/tests")
public void executeTests() throws Throwable {
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(selectPackage("com.mytests"), selectClass(SomeTests.class))
.build();
Launcher launcher = LauncherFactory.create();
SummaryGeneratingListener listener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(listener);
launcher.execute(request);
listener.getSummary();
}
}

How to inject a typed map of beans based on a typesafe qualifier in Spring?

See the example below, I'm trying to get a Map of my TypedService beans but I would prefer if the keys were the Type enum values specified in the TypeSafeQualifier instead of the unsafe String "serviceName".
package org.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Map;
import static org.test.Application.Type.ONE;
import static org.test.Application.Type.TWO;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#SpringBootApplication
public class Application {
#Autowired
Map<String, TypedService> works;
#Autowired
Map<Type, TypedService> fails;
public static void main(String [] args) {
SpringApplication.run(Application.class, args);
}
public enum Type {
ONE,
TWO
}
#Target({TYPE, METHOD, FIELD, CONSTRUCTOR})
#Retention(RUNTIME)
#Qualifier
public #interface TypeSafeQualifier {
Type value();
}
public interface TypedService {
void startSignup();
void activate();
}
#Service
#TypeSafeQualifier(ONE)
public class TypeOneService implements TypedService {
#Override
public void startSignup() {
}
#Override
public void activate() {
}
}
#Service
#TypeSafeQualifier(TWO)
public class TypeTwoService implements TypedService {
#Override
public void startSignup() {
}
#Override
public void activate() {
}
}
}
SpringBoot version: springBootVersion=1.5.3.RELEASE
Spring offers a special approach to handle this type of injection: AutowireCandidateResolver.
In your case the code might be:
package org.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.LinkedHashMap;
import java.util.Map;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#SpringBootApplication
public class Application {
#Autowired
Map<String, TypedService> works;
#Autowired
Map<Type, TypedService> fails;
#PostConstruct
private void init() {
System.out.println(fails);
}
public static void main(String[] args) {
final SpringApplication application = new SpringApplication(Application.class);
application.addInitializers(context -> {
context.addBeanFactoryPostProcessor(beanFactory -> {
final DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory;
dlbf.setAutowireCandidateResolver(new MyAutowireCandidateResolver(dlbf));
});
});
application.run(args);
}
#QualifierValue(TypeSafeQualifier.class)
public enum Type {
ONE,
TWO
}
#Target({TYPE, METHOD, FIELD, CONSTRUCTOR})
#Retention(RUNTIME)
#Qualifier
public #interface TypeSafeQualifier {
Type value();
}
public interface TypedService {
void startSignup();
void activate();
}
#Service
#TypeSafeQualifier(Type.ONE)
public class TypeOneService implements TypedService {
#Override
public void startSignup() {
}
#Override
public void activate() {
}
}
#Target({TYPE})
#Retention(RUNTIME)
public #interface QualifierValue {
Class<? extends Annotation> value();
}
#Service
#TypeSafeQualifier(Type.TWO)
public class TypeTwoService implements TypedService {
#Override
public void startSignup() {
}
#Override
public void activate() {
}
}
private static class MyAutowireCandidateResolver extends ContextAnnotationAutowireCandidateResolver {
private final DefaultListableBeanFactory beanFactory;
private MyAutowireCandidateResolver(DefaultListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
#Override
public Object getSuggestedValue(DependencyDescriptor descriptor) {
final Object result = super.getSuggestedValue(descriptor);
if (result != null) {
return result;
}
if (descriptor.getDependencyType() != Map.class) {
return null;
}
final ResolvableType dependencyGenericType = descriptor.getResolvableType().asMap();
final ResolvableType[] typeParams = dependencyGenericType.getGenerics();
final QualifierValue qualifierValue = typeParams[0].getRawClass().getAnnotation(QualifierValue.class);
if (qualifierValue == null) {
return null;
}
final String[] candidateBeanNames = beanFactory.getBeanNamesForType(typeParams[1]);
final LinkedHashMap<Object, Object> injectedMap = new LinkedHashMap<>(candidateBeanNames.length);
for (final String candidateBeanName : candidateBeanNames) {
final Annotation annotation = beanFactory.findAnnotationOnBean(candidateBeanName, qualifierValue.value());
if (annotation == null) {
continue;
}
final Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(annotation, false);
final Object value = annotationAttributes.get("value");
if (value == null || value.getClass() != typeParams[0].getRawClass()) {
continue;
}
injectedMap.put(value, beanFactory.getBean(candidateBeanName));
}
return injectedMap;
}
}
}
First of all, we add TypeQualifierValue annotation to make Spring know about a qualifier with values of the given type.
The second is to customize the SpringApplication in the main method: we use BeanFactoryPostProcessor to set a custom AutowireCandidateResolver.
And the final step: we write MyAutowireCandidateResolver extending ContextAnnotationAutowireCandidateResolver (delegation instead of inheritance is applicable to, it's even a little bit better since one day Spring can migrate to `YetAnotherAutowireCandidateResolver' by default).
The crucial part here is the overridden getSuggestedValue method: here we can customize the injection logic considering the generic types of the dependency (field, method parameter) and by applying some getBean...-like methods from the BeanFactory with some magic of Spring AnnotationUtils class.

Use pivotal cloud foundry redis and rabbitmq service using as vcap service in spring boot application

I am able to use REDIS and RABBITMQ services which is on pivotal.While binding services I am able to get the Credentials and using that credentials in my application.properties for spring boot project.
But this configuration that I am using is hard-coded in application.Properties
To Make this configuration dynamically I came to know that we can use vcap services provided by pivotal.
So want to use run-time credentials for redis and rabbimq.
My Code is below for reference.
application.propeties
rabbitmq.host=hostname
rabbitmq.virtual-host=vhostanme
rabbitmq.username=username
rabbitmq.password=password
rabbit.mainqueue=abhi
rabbit.errorqueue=abc
redis.host=redishostname
redis.port=port
redis.password=password
My Config class:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class Config {
static String rabbitMqHost;
static String rabbitMqVHost;
static String rabbitMqUsername;
static String rabbitMqPassword;
static String rabbitMqMainQueue;
static String rabbitMqErrorQueue;
static String redisHost;
static int redisPort;
static String redisPassword;
Config() {
}
public static String getRedisHost() {
return redisHost;
}
public static void setRedisHost(String redisHost) {
Config.redisHost = redisHost;
}
public static int getRedisPort() {
return redisPort;
}
public static void setRedisPort(int redisPort) {
Config.redisPort = redisPort;
}
public static String getRedisPassword() {
return redisPassword;
}
public static void setRedisPassword(String redisPassword) {
Config.redisPassword = redisPassword;
}
public static String getRabbitMqMainQueue() {
return rabbitMqMainQueue;
}
public static void setRabbitMqMainQueue(String rabbitMqMainQueue) {
Config.rabbitMqMainQueue = rabbitMqMainQueue;
}
public static String getRabbitMqErrorQueue() {
return rabbitMqErrorQueue;
}
public static void setRabbitMqErrorQueue(String rabbitMqErrorQueue) {
Config.rabbitMqErrorQueue = rabbitMqErrorQueue;
}
public static String getRabbitMqHost() {
return rabbitMqHost;
}
public static void setRabbitMqHost(String rabbitMqHost) {
Config.rabbitMqHost = rabbitMqHost;
}
public static String getRabbitMqVHost() {
return rabbitMqVHost;
}
public static void setRabbitMqVHost(String rabbitMqVHost) {
Config.rabbitMqVHost = rabbitMqVHost;
}
public static String getRabbitMqUsername() {
return rabbitMqUsername;
}
public static void setRabbitMqUsername(String rabbitMqUsername) {
Config.rabbitMqUsername = rabbitMqUsername;
}
public static String getRabbitMqPassword() {
return rabbitMqPassword;
}
public static void setRabbitMqPassword(String rabbitMqPassword) {
Config.rabbitMqPassword = rabbitMqPassword;
}
#Value("${rabbitmq.host}")
public void setRabbitMqHosts(String url) {
setRabbitMqHost(url);
}
#Value("${rabbitmq.virtual-host}")
public void setRabbitMqVHosts(String url) {
setRabbitMqVHost(url);
}
#Value("${rabbitmq.username}")
public void setRabbitUsernames(String url) {
setRabbitMqUsername(url);
}
#Value("${rabbitmq.password}")
public void setRabbitPasswords(String url) {
setRabbitMqPassword(url);
}
#Value("${rabbit.mainqueue}")
public void setRabbitMainQueues(String url) {
setRabbitMqMainQueue(url);
}
#Value("${rabbit.errorqueue}")
public void setRabbitErrorQueues(String url) {
setRabbitMqErrorQueue(url);
}
#Value("${redis.host}")
public void setRedisHosts(String url) {
setRedisHost(url);
}
#Value("${redis.port}")
public void setRedisPorts(int url) {
setRedisPort(url);
}
#Value("${redis.password}")
public void setRedisPasswords(String url) {
setRedisPassword(url);
}
}
My MessagesConsumer class in which I am using that Conguration to take message from rabbitmq jms queue and save to redis:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.es.consumer.config.Config;
import com.rabbitmq.jms.admin.RMQConnectionFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
#Component
public class MessagesConsumer {
#Autowired
JmsTemplate jmsTemplate;
final Logger logger = LoggerFactory.getLogger(MessagesConsumer.class);
Jedis jedis;
JedisShardInfo shardInfo;
#PostConstruct
public void init() {
shardInfo = new JedisShardInfo(Config.getRedisHost(), Config.getRedisPort());
shardInfo.setPassword(Config.getRedisPassword());
jedis = new Jedis(shardInfo);
jedis.connect();
jedis.select(2);
}
#Bean
ConnectionFactory connectionFactory() {
RMQConnectionFactory connectionFactory = new RMQConnectionFactory();
connectionFactory.setUsername(Config.getRabbitMqUsername());
connectionFactory.setPassword(Config.getRabbitMqPassword());
connectionFactory.setVirtualHost(Config.getRabbitMqVHost());
connectionFactory.setHost(Config.getRabbitMqHost());
return connectionFactory;
}
#SuppressWarnings("rawtypes")
#Scheduled(fixedRate = 1)
public void readQueueAndSaveData() {
// take message process it and save to redis as hmset
}}
Any Help would be appreciable.
There are two ways of doing this.
1) Remove all the properties from application.properties, and write a configuration bean that will create RedisTemplate and RabbitTemplate beans for you. The factory properties required for these are to be obtained from the VCAP_SERVICES. On CF, the VCAP_SERVICES env variable, will have the services information that are binded to the app. When u push the app, with redis, rabbit service binded into your space, then their properties are available in VCAP_SERVICES. So just do System.getEnv("VCAP_SERVICES") in your code and then parse the json to get the service details to create the templates.
2) Remove the properties from application.properties, and use spring cloud connector. Spring cloud has a subproject called Spring cloud connectors that provide utilities to connect to various cloud services.
http://cloud.spring.io/spring-cloud-connectors/spring-cloud-spring-service-connector.html#_rabbitmq
Just you need to define a class that extends AbstractCloudConfig as below
class CloudConfig extends AbstractCloudConfig {
#Bean
public RabbitConnectionFactory rabbitFactory() {
return connectionFactory().rabbitConnectionFactory("rabbit-servicename");
}
#Bean
public RedisConnectionFactory redisFactory() {
return connectionFactory().redisConnectionFactory("redis-servicename");
}
}
The second approach is prefered if you are using Spring, as this needs very less coding and can be switched, to different cloud providers with no much effort.

Resources