Google Cloud Memory Store (Redis), can't connect to redis when instance is just started - redis

I have a problem to connect to redis when my instance is just started.
I use:
runtime: java
env: flex
runtime_config:
jdk: openjdk8
i got following exception:
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: connect timed out
RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
java.net.SocketTimeoutException: connect timed out
after 2-3 min, it works smoothly
Do i need to add some check in my code or how i should fix it properly?
p.s.
also i use spring boot, with following configuration
#Value("${spring.redis.host}")
private String redisHost;
#Bean
JedisConnectionFactory jedisConnectionFactory() {
// https://cloud.google.com/memorystore/docs/redis/quotas
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, 6379);
return new JedisConnectionFactory(config);
}
#Bean
public RedisTemplate<String, Object> redisTemplate(
#Autowired JedisConnectionFactory jedisConnectionFactory
) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer(newObjectMapper()));
return template;
}
in pom.xml
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.1.2.RELEASE</version>

I solved this problem as follows: in short, I added the “ping” method, which tries to set and get the value from Redis; if it's possible, then application is ready.
Implementation:
First, you need to update app.yaml add following:
readiness_check:
path: "/readiness_check"
check_interval_sec: 5
timeout_sec: 4
failure_threshold: 2
success_threshold: 2
app_start_timeout_sec: 300
Second, in your rest controller:
#GetMapping("/readiness_check")
public ResponseEntity<?> readiness_check() {
if (!cacheConfig.ping()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().build();
}
Third, class CacheConfig:
public boolean ping() {
long prefix = System.currentTimeMillis();
try {
redisTemplate.opsForValue().set("readiness_check_" + prefix, Boolean.TRUE, 100, TimeUnit.SECONDS);
Boolean val = (Boolean) redisTemplate.opsForValue().get("readiness_check_" + prefix);
return Boolean.TRUE.equals(val);
} catch (Exception e) {
LOGGER.info("ping failed for " + System.currentTimeMillis());
return false;
}
}
P.S.
Also if somebody needs the full implementation of CacheConfig:
#Configuration
public class CacheConfig {
private static final Logger LOGGER = Logger.getLogger(CacheConfig.class.getName());
#Value("${spring.redis.host}")
private String redisHost;
private final RedisTemplate<String, Object> redisTemplate;
#Autowired
public CacheConfig(#Lazy RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
#Bean
JedisConnectionFactory jedisConnectionFactory(
#Autowired JedisPoolConfig poolConfig
) {
// https://cloud.google.com/memorystore/docs/redis/quotas
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, 6379);
JedisClientConfiguration clientConfig = JedisClientConfiguration
.builder()
.usePooling()
.poolConfig(poolConfig)
.build();
return new JedisConnectionFactory(config, clientConfig);
}
#Bean
public RedisTemplate<String, Object> redisTemplate(
#Autowired JedisConnectionFactory jedisConnectionFactory
) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer(newObjectMapper()));
return template;
}
/**
* Example: https://github.com/PengliuIBM/pws_demo/blob/1becdca1bc19320c2742504baa1cada3260f8d93/redisData/src/main/java/com/pivotal/wangyu/study/springdataredis/config/RedisConfig.java
*/
#Bean
redis.clients.jedis.JedisPoolConfig jedisPoolConfig() {
final redis.clients.jedis.JedisPoolConfig poolConfig = new redis.clients.jedis.JedisPoolConfig();
// Maximum active connections to Redis instance
poolConfig.setMaxTotal(16);
// Number of connections to Redis that just sit there and do nothing
poolConfig.setMaxIdle(16);
// Minimum number of idle connections to Redis - these can be seen as always open and ready to serve
poolConfig.setMinIdle(8);
// Tests whether connection is dead when returning a connection to the pool
poolConfig.setTestOnBorrow(true);
// Tests whether connection is dead when connection retrieval method is called
poolConfig.setTestOnReturn(true);
// Tests whether connections are dead during idle periods
poolConfig.setTestWhileIdle(true);
return poolConfig;
}
public boolean ping() {
long prefix = System.currentTimeMillis();
try {
redisTemplate.opsForValue().set("readiness_check_" + prefix, Boolean.TRUE, 100, TimeUnit.SECONDS);
Boolean val = (Boolean) redisTemplate.opsForValue().get("readiness_check_" + prefix);
return Boolean.TRUE.equals(val);
} catch (Exception e) {
LOGGER.info("ping failed for " + System.currentTimeMillis());
return false;
}
}
}

Related

Redisson Connection Listener not getting invoked in version 3.7.0

I am trying to setup a connection listener for my redisson client. It is not getting invoked on both connect/disconnect.
Tried the code mentioned on the redisson github which is as per below:
public void createRedisClient(Handler<AsyncResult<Redis>> handler) {
ConfigRetriever configRetriever = UDSFBootStrapper.getInstance().getConfigRetriever();
configRetriever.getConfig(
config -> {
String redisUrl = config.result().getString("redisip");
redisUrl += ":";
redisUrl += config.result().getInteger("redisport");
Config rconfig = new Config();
rconfig.setTransportMode(TransportMode.EPOLL);
rconfig.useClusterServers()
.addNodeAddress(UdsfConstants.REDIS_CONNECTION_PREFIX + redisUrl);
rclient = Redisson.create(rconfig);
rclient.getNodesGroup().addConnectionListener(new ConnectionListener() {
//#Override
public void onConnect(InetSocketAddress inetSocketAddress) {
logger.info("Redis server connected");
}
//#Override
public void onDisconnect(InetSocketAddress inetSocketAddress) {
logger.info("Redis server disconnected");
}
});
});
}

apache ignite service deploy cluster singleton

I try create spring java application with apache ignite inside.
When application startup it deploy service(cluster singleton) to cluster. (it`s ok)
But when i start second node which deploy this service too it is locked.
why this hapends ?
Apache Ignite 2.5.0
code of service class:
public class TaskLockWatcher implements Service {
#IgniteInstanceResource
private Ignite ignite;
private SchedulerFuture scheduler;
#Override
public void cancel(ServiceContext ctx) {
LOGGER.info("schedule service cancel");
if (scheduler != null){
scheduler.cancel();
}
}
#Override
public void init(ServiceContext ctx) throws Exception {
LOGGER.info("schedule service init");
}
#Override
public void execute(ServiceContext ctx) throws Exception {
LOGGER.info("schedule service execute");
scheduler = ignite.scheduler().scheduleLocal(() -> {
LOGGER.info("schedule service call");
List<Ticket> tickets = getTicketForUnlock();
if (!tickets.isEmpty()){
changeTicketStatus(tickets, TicketStatus.CREATED);
}
}, "* * * * *");
}
}
But the locking occurs even if I leave only the output of messages in all TaskLockWatcher methods.
publishing code:
Ignite ignite = connector.getClient();
IgniteServices svcs = ignite.services();
svcs.deployClusterSingleton("taskLockWatcher", new TaskLockWatcher());
ignite configuration code:
IgniteConfiguration igniteConfiguration = new IgniteConfiguration();
DataStorageConfiguration dataStorageConfiguration = new DataStorageConfiguration();
dataStorageConfiguration.setWalMode(WALMode.LOG_ONLY);
dataStorageConfiguration.getDefaultDataRegionConfiguration().setPersistenceEnabled(false);
dataStorageConfiguration.getDefaultDataRegionConfiguration().setMaxSize(128); // MB
List<DataRegionConfiguration> list = new ArrayList<>();
DataRegionConfiguration configuration = new DataRegionConfiguration();
configuration.setName("TASK_REGION");
configuration.setMaxSize(1024);
configuration.setPersistenceEnabled(true);
list.add(conf);
dataStorageConfiguration.setDataRegionConfigurations(list.toArray(new DataRegionConfiguration[0]));
igniteConfiguration.setDataStorageConfiguration(dataStorageConfiguration);
TcpCommunicationSpi tcpCommunicationSpi = new TcpCommunicationSpi();
tcpCommunicationSpi.setSlowClientQueueLimit(1000);
igniteConfiguration.setCommunicationSpi(tcpCommunicationSpi);
Map<String, String> attrs = Collections.singletonMap("group.node.filter", "CLUSTER_TASKS,CLUSTER_TICKETS");
igniteConfiguration.setUserAttributes(attrs);
TcpDiscoverySpi spi = new TcpDiscoverySpi();
TcpDiscoveryZookeeperIpFinder ipFinder = new TcpDiscoveryZookeeperIpFinder();
ipFinder.setBasePath("/datagrid");
ipFinder.setCurator(getCuratorFramework());
spi.setIpFinder(ipFinder);
igniteConfiguration.setDiscoverySpi(spi);
AtomicConfiguration atomicConfiguration = new AtomicConfiguration();
atomicConfiguration.setBackups(1);
atomicConfiguration.setCacheMode(CacheMode.REPLICATED);
igniteConfiguration.setAtomicConfiguration(atomicConfiguration);
igniteConfiguration.setIncludeEventTypes(EventType.EVTS_CACHE);
CacheConfiguration<UUID, Ticket> cacheConfiguration = new CacheConfiguration<>("TICKETS");
cacheConfiguration.setIndexedTypes(keyClass, UUID.class);
cacheConfiguration.setNodeFilter((ClusterNode clusterNode) -> {
String dataNode = clusterNode.attribute("group.node.filter");
return dataNode != null && dataNode.contains("CLUSTER_TICKETS");
});
cacheConfiguration.setStatisticsEnabled(true);
cacheConfiguration.setDataRegionName("TASK_REGION");
cacheConfiguration.setBackups(1);
cacheConfiguration.setCacheMode(CacheMode.PARTITIONED);
cacheConfiguration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
IgniteCache<UUID, Ticket> ticketCache = ignite.getOrCreateCache(cacheConfiguration);

Use Spring Cloud Spring Service Connector with RabbitMQ and start publisher config function

I connect RabbitMQ with sprin cloud config:
#Bean
public ConnectionFactory rabbitConnectionFactory() {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("publisherConfirms", true);
RabbitConnectionFactoryConfig rabbitConfig = new RabbitConnectionFactoryConfig(properties);
return connectionFactory().rabbitConnectionFactory(rabbitConfig);
}
2.Set rabbitTemplate.setMandatory(true) and setConfirmCallback():
#Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMandatory(true);
template.setMessageConverter(new Jackson2JsonMessageConverter());
template.setConfirmCallback((correlationData, ack, cause) -> {
if (!ack) {
System.out.println("send message failed: " + cause + correlationData.toString());
} else {
System.out.println("Publisher Confirm" + correlationData.toString());
}
});
return template;
}
3.Send message to queue to invoke the publisherConfirm and print log.
#Component
public class TestSender {
#Autowired
private RabbitTemplate rabbitTemplate;
#Scheduled(cron = "0/5 * * * * ? ")
public void send() {
this.rabbitTemplate.convertAndSend(EXCHANGE, "routingkey", "hello world",
(Message m) -> {
m.getMessageProperties().setHeader("tenant", "aaaaa");
return m;
}, new CorrelationData(UUID.randomUUID().toString()));
Date date = new Date();
System.out.println("Sender Msg Successfully - " + date);
}
}
But publisherConfirm have not worked.The log have not been printed. Howerver true or false, log shouldn't been absent.
Mandatory is not needed for confirms, only returns.
Some things to try:
Turn on DEBUG logging to see it it helps; there are some logs generated regarding confirms.
Add some code
.
template.execute(channel -> {
system.out.println(channel.getClass());
return null;
}
If you don't see PublisherCallbackChannelImpl then it means the configuration didn't work for some reason. Again DEBUG logging should help with the configuration debugging.
If you still can't figure it out, strip your application to the bare minimum that exhibits the behavior and post the complete application.

How to add windows credentials to an apache camel route?

I need to authenticate myself when I want to access a REST api.
I have created a simple example with apache's WinHttpClients which works and also accepts a self signed crt which is used by that site.
These are my dependencies
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5.+'
compile 'org.apache.httpcomponents:httpclient-win:4.5.+'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
And this is the working code (authorization works, acceptance of crt works)
public class Application {
public static void main(String[] args) throws IOException {
if (WinHttpClients.isWinAuthAvailable()) {
PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
buildSSLSocketFactory());
HttpClientBuilder clientBuilder = WinHttpClients.custom().useSystemProperties();
clientBuilder.setConnectionManager(httpClientConnectionManager);
CloseableHttpClient httpClient = clientBuilder.build();
HttpHost httpHost = new HttpHost("server.evilcorp.com", 443, "https");
HttpGet httpGet = new HttpGet(
"/evilwebapi/streams/endpointalpha/data");
httpGet.setHeader("accept", "application/json");
CloseableHttpResponse httpResponse = httpClient.execute(httpHost, httpGet);
String content = EntityUtils.toString(httpResponse.getEntity());
System.out.println(content); // returns expected json result
}
}
private static Registry<ConnectionSocketFactory> buildSSLSocketFactory() {
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(buildSSLContext(), NoopHostnameVerifier.INSTANCE);
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
}
private static SSLContext buildSSLContext() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
System.out.println("Failed to initialize SSL handling.\n" + e);
}
return sslContext;
}
}
When I try to access the same site through apache camel I get a 401 status.
I tried to configure camel's httpComponent in various ways but so far I can't make authentication work. This is the current camel setup.
These are my dependencies:
dependencies {
compile 'org.apache.camel:camel-core:2.18.+'
compile 'org.apache.camel:camel-sql:2.18.+'
compile 'org.apache.camel:camel-http4:2.18.+'
compile 'org.apache.camel:camel-jetty:2.18.+'
compile 'org.apache.camel:camel-jackson:2.18.+'
compile 'org.apache.camel:camel-guava-eventbus:2.18.+'
compile 'org.apache.camel:camel-quartz2:2.18.+'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.+'
compile 'org.apache.httpcomponents:httpclient:4.5.+'
compile 'org.apache.httpcomponents:httpclient-win:4.5.+'
testRuntime files('src/test/resources')
runtime files('src/main/resources')
}
And this is the RouteBuilder which does not work (authorization doesm't works, statusCode: 401)
context = new DefaultCamelContext(registry);
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:model.properties");
context.addComponent("properties", pc);
try {
context.addRoutes(new RouteBuilder() {
public void configure() {
HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
httpComponent.setHttpClientConfigurer(new WinHttpClientConfigurer());
httpComponent.setClientConnectionManager(new PoolingHttpClientConnectionManager(WinHttpClientConfigurer.buildSSLSocketFactory()));
httpComponent.setHttpConfiguration(buildHttpConfiguration());
getContext().getProperties().put("CamelJacksonEnableTypeConverter", "true");
getContext().getProperties().put("CamelJacksonTypeConverterToPojo", "true");
from("quartz2://pipull?cron=0+0/1+*+1/1+*+?+*")
.setHeader(Exchange.HTTP_QUERY,
simple("start='${header.start}'&end='${header.end}'"))
.multicast().parallelProcessing()
.to("direct:model");
from("direct:model")
.setHeader("contractRef", simple("${properties:model.name}"))
.to("https4://server.evilcorp.com/evilwebapi/streams/endpointalpha/data")
.to("direct:transform");
from("direct:transform").unmarshal()
.json(JsonLibrary.Jackson, Model.class)
.bean(ProcessorImpl.class)
.to("guava-eventbus:botBus");
}
private HttpConfiguration buildHttpConfiguration() {
WindowsCredentialsProvider credentialsProvider = new WindowsCredentialsProvider(
new SystemDefaultCredentialsProvider());
Credentials credentials = credentialsProvider.getCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM));
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setAuthMethod(AuthSchemes.NTLM);
httpConfiguration.setAuthUsername(credentials.getUserPrincipal().getName());
return httpConfiguration;
}
});
context.start();
} catch (Exception e) {
isRunning.set(false);
throw new RuntimeException(e);
}
I have resolved the problem through subtyping HttpComponent and adding that to the camel context.
public class WinHttpComponent extends HttpComponent {
private static final Logger LOG = LoggerFactory.getLogger(WinHttpComponent.class);
public WinHttpComponent() {
this(HttpEndpoint.class);
}
public WinHttpComponent(Class<? extends HttpEndpoint> endpointClass) {
super(endpointClass);
}
#Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// copy-paste everything from super method
// replace this
// HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// with this
HttpClientBuilder clientBuilder = WinHttpClients.custom().useSystemProperties();
// copy-paste everything from super method
}
}
context = new DefaultCamelContext(registry);
context.addComponent("https4", new WinHttpComponent());
try {
context.addRoutes(new RouteBuilder() {
public void configure() {
HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
// connection manager which accepts self-signed cert
httpComponent.setClientConnectionManager(new PoolingHttpClientConnectionManager(
NoopSslVerifierHttpClientConfigurer.buildSSLSocketFactory()));
...
...
...
}
}

ActiveMQ and JMS : Basic steps for novice

Hi all please give some basic about ActiveMQ with JMS for novice. And configuration steps also.
We are going to create a console based application using multithreading. So create an java project for console application.
Now follow these steps..........
Add javax.jms.jar, activemq-all-5.3.0.jar, log4j-1.2.15.jar to your project library.
(You can download all of above jar files from http://www.jarfinder.com/ .
create a file naming jndi.properties and paste these following texts .. ( Deatils for jndi.properties just Google it)
# START SNIPPET: jndi
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
# use the following property to configure the default connector
java.naming.provider.url = tcp://localhost:61616
# use the following property to specify the JNDI name the connection factory
# should appear as.
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue
# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic
# END SNIPPET: jndi
Add JMSConsumer.java
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JMSConsumer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSConsumer.class);
public void run() {
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageConsumer consumer = null;
Destination destination = null;
String sourceName = null;
final int numMsgs;
sourceName= "MyQueue";
numMsgs = 1;
LOG.info("Source name is " + sourceName);
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(sourceName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(destination);
connection.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MessageListener listener = new MyQueueMessageListener();
consumer.setMessageListener(listener );
//Let the thread run for some time so that the Consumer has suffcient time to consume the message
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
LOG.info("Exception occurred: " + e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
Add JMSProducer.java
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JMSProducer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSProducer.class);
public JMSProducer() {
}
//Run method implemented to run this as a thread.
public void run(){
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageProducer producer = null;
String destinationName = null;
final int numMsgs;
destinationName = "MyQueue";
numMsgs = 5;
LOG.info("Destination name is " + destinationName);
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(destinationName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}
/*
* Create connection. Create session from connection; false means
* session is not transacted.create producer, set the text message, set the co-relation id and send the message.
*/
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
for (int i = 0; i
Add MyQueueMessageListener.java
import java.io.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.jms.*;
public class MyQueueMessageListener implements MessageListener {
private static final Log LOG = LogFactory.getLog(MyQueueMessageListener.class);
/**
*
*/
public MyQueueMessageListener() {
// TODO Auto-generated constructor stub
}
/** (non-Javadoc)
* #see javax.jms.MessageListener#onMessage(javax.jms.Message)
* This is called on receving of a text message.
*/
public void onMessage(Message arg0) {
LOG.info("onMessage() called!");
if(arg0 instanceof TextMessage){
try {
//Print it out
System.out.println("Recieved message in listener: " + ((TextMessage)arg0).getText());
System.out.println("Co-Rel Id: " + ((TextMessage)arg0).getJMSCorrelationID());
try {
//Log it to a file
BufferedWriter outFile = new BufferedWriter(new FileWriter("MyQueueConsumer.txt"));
outFile.write("Recieved message in listener: " + ((TextMessage)arg0).getText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("~~~~Listener : Error in message format~~~~");
}
}
}
Add SimpleApp.java
public class SimpleApp {
//Run the producer first, then the consumer
public static void main(String[] args) throws Exception {
runInNewthread(new JMSProducer());
runInNewthread(new JMSConsumer());
}
public static void runInNewthread(Runnable runnable) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(false);
brokerThread.start();
}
}
Now run SimpleApp.java class.
All da best. Happy coding.
Here it is a simple junit test for ActiveMQ and Apache Camel. This two technologies works very good together.
If you want more details about the code, you can find a post in my blog:
http://ignaciosuay.com/unit-testing-active-mq/
public class ActiveMQTest extends CamelTestSupport {
#Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory));
return camelContext;
}
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("mina:tcp://localhost:6666?textline=true&sync=false")
.to("activemq:processHL7");
from("activemq:processHL7")
.to("mock:end");
}
};
}
#Test
public void testSendHL7Message() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
String m = "MSH|^~\\&|hl7Integration|hl7Integration|||||ADT^A01|||2.5|\r" +
"EVN|A01|20130617154644\r" +
"PID|1|465 306 5961||407623|Wood^Patrick^^^MR||19700101|1|\r" +
"PV1|1||Location||||||||||||||||261938_6_201306171546|||||||||||||||||||||||||20130617134644|";
mock.expectedBodiesReceived(m);
template.sendBody("mina:tcp://localhost:6666?textline=true&sync=false", m);
mock.assertIsSatisfied();
}