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

Haproxy and tomcat JSESSIONID

One of the biggest problems I have been trying to solve at our startup is to put our tomcat nodes in HA mode. Right now if a customer comes, he lands on to a node and remains there forever. This has two major issues: 1) We have to overprovision each node with ability to handle worse case capacity. 2) If two or three high profile customers lands on to same node then we need to move them manually. 3) We need to cut over new nodes and we already have over 100+ nodes.  Its a pain managing these nodes and I waste lot of my time in chasing node specific issues. I loath when I know I have to chase this env issue. I really hate human intervention as if it were up to me I would just automate thing and just enjoy the fruits of automation and spend quality time on major issues rather than mundane task,call me lazy but thats a good quality. So Finally now I am at a stage where I can put nodes behing HAProxy in QA env. today we were testing the HA config and first problem I immediat...

Adding Jitter to cache layer

Thundering herd is an issue common to webapp that rely on heavy caching where if lots of items expire at the same time due to a server restart or temporal event, then suddenly lots of calls will go to database at same time. This can even bring down the database in extreme cases. I wont go into much detail but the app need to do two things solve this issue. 1) Add consistent hashing to cache layer : This way when a memcache server is added/removed from the pool, entire cache is not invalidated.  We use memcahe from both python and Java layer and I still have to find a consistent caching solution that is portable across both languages. hash_ring and spymemcached both use different points for server so need to read/test more. 2) Add a jitter to cache or randomise the expiry time: We expire long term cache  records every 8 hours after that key was added and short term cache expiry is 2 hours. As our customers usually comes to work in morning and access the cloud file server it ...

Spring 3.2 quartz 2.1 Jobs added with no trigger must be durable.

I am trying to enable HA on nodes and in that process I found that in a two test node setup a job that has a frequency of 10 sec was running into deadlock. So I tried upgrading from Quartz 1.8 to 2.1 by following the migration guide but I ran into an exception that says "Jobs added with no trigger must be durable.". After looking into spring and Quartz code I figured out that now Quartz is more strict and earlier the scheduler.addJob had a replace parameter which if passed to true would skip the durable check, in latest quartz this is fixed but spring hasnt caught up to this. So what do you do, well I jsut inherited the factory and set durability to true and use that public class DurableJobDetailFactoryBean extends JobDetailFactoryBean {     public DurableJobDetailFactoryBean() {         setDurability(true);     } } and used this instead of JobDetailFactoryBean in the spring bean definition     <bean i...