Skip to main content

Redis publish subscribe to node.js

Disclaimer: This is no way a comparison between RabbitMQ and Redis. RabbitMQ is a great product and we use it in our startup as a queuing system. I just wanted to try out redis in my pet project so I did it.

I am intrigued by the hype around node.js so am planning of writing a node.js to push real time events from server and do push notifications in browser from server.

Now mostly I saw that people use a myriad of technologies from websocket, nginx, nodejs, redis/rabbitmq and in backend produce the message from Java or any other app.  Basically node.js is only used for long polling and decoupled from the main app using a message queue as a broker. So my first goal was to push message from Java to message queue and I have already used RabbitMQ in past so I thought let me this time try redis and boy it is much much easy then RabbitMQ (however at this moment I trust rabbitmq more than redis for production as I have much more experience scaling rabbitmq as a queuing system,  I just wanted to try out a different queuing system).


To connect to redis from java there are multiple implementations like JRedis and Jedis, in past in my startup we had used JRedis and then switched to Jedis but I am not happy with that code as we did all code ourselves so thought to check if spring has something because I am a big time fan of spring-jdbc and luckily I found spring has a similar abstraction to hide all this details using its spring-data-redis templates.  I used spring-data-redis-1.1.0.RELEASE and jedis-2.1.0.jar and I ran into issues with spring-3.X so I upgraded to spring-tx-4.0.1.RELEASE.jar

all I needed to do was to add this in spring config

 <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="127.0.0.1" p:port="6379"/>
    
      <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"
    p:connection-factory-ref="jedisConnectionFactory"/>
 
      <bean id="messagePublisher" class="com.kp.common.server.pubsub.MessagePublisher">
        <property name="stringRedisTemplate" ref="stringRedisTemplate" />
      </bean>

and then

public class MessagePublisher {
    private static final AppLogger logger = AppLogger.getLogger(MessagePublisher.class);
    private StringRedisTemplate stringRedisTemplate;

    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void publishMessage(String channel, String message) {
        logger.debug("Publishing {} to channel {}", message, channel);
        stringRedisTemplate.convertAndSend(channel, message);
    }

    public void publishJsonMessage(String channel, Object msgObject) {
        publishMessage(channel, JsonUtil.generateJSON(msgObject));
    }
}


Now can you beat this.  2 lines of code to publish a message to message queue.  Totally impressed and icing on cake is that if you have to switch the library from jedis to Jredis then its just a config change and no code change is required and spring is handing all connection open/close.

Comments

  1. Rabbitmq is a queuing system. You can compare it with ExecutorService or a queue (push/pop) but the comparison with redis is inappropriate. The other point is you can use any technology the way you want but you need to look at the pros and cons too. For eg:- In redis, you may need to delete the message manually once processed if it has to behave like Rabbitmq. You do not have "ack" too.

    ReplyDelete
  2. I think you are taking the post in a wrong spirit. RabbitMQ is a great product, Infact for the startup we use RabbitMQ and it has rarely given any issues. We had pushed hundreds of millions of messages via RabbitMQ and it didn’t sweat. I will put a disclaimer at top of the blog that this is not a comparison.

    ReplyDelete

Post a Comment

Popular posts from this blog

RabbitMQ java clients for beginners

Here is a sample of a consumer and producer example for RabbitMQ. The steps are
Download ErlangDownload Rabbit MQ ServerDownload Rabbit MQ Java client jarsCompile and run the below two class and you are done.
This sample create a Durable Exchange, Queue and a Message. You will have to start the consumer first before you start the for the first time.

For more information on AMQP, Exchanges, Queues, read this excellent tutorial
http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/

+++++++++++++++++RabbitMQProducer.java+++++++++++++++++++++++++++
import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; import com.rabbitmq.client.*; public class RabbitMQProducer { public static void main(String []args) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); factory.setHost("127.0.0.1"); factory.setPort(5672); Conne…

Spring query timeout or transaction timeout

If you are using spring to manage transactions then you can specify default transaction timeout using

    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
        <property name="defaultTimeout" value="30" /> <!--30 sec--->             
    </bean>

or you can override the timeout in the annotation

    @Transactional(readOnly = false, timeout=30)


or if you are doing it programatic transactions then you can do


DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
transactionManager.setDefaultTimeout(30);

 or you can override the timeout for one particular transaction

TransactionTemplate transactionTemplate = new TransactionTemplate();
transactionTemplate.setTimeout(30);

Python adding pid file

I have a thumbnail generator that launches multiple processes and the correct way to shut it down is to send kill -HUP to the parent process. To automate I had to write a pid file from python, it was a piece of cake
def writePidFile(): pid = str(os.getpid()) f = open('thumbnail_rabbit_consumer.pid', 'w') f.write(pid) f.close()