Announcement Announcement Module
Collapse
No announcement yet.
Need Help with RedisTemplate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Need Help with RedisTemplate

    New to Redis & little familiar with spring. Trying to run small example using RedisTemplate.

    Downloaded Redis setup.exe for win 32bit (redis-2.4.6-setup-32-bit.exe), Jedis jar(jedis-2.0.0.jar), commons-pool-1.6.jar,
    spring-core-3.1.0.RELEASE.jar, spring-data-redis-1.0.0.RELEASE.jar

    In applicationContext.xml added following entries.

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.j edis.JedisConnectionFactory"
    p:host-name="localhost" port="6379" p:use-pool="true"/>

    <!-- redis template definition -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTe mplate"
    p:connection-factory-ref="jedisConnectionFactory" p:exposeConnection="true" />

    Code is in RedExample.java

    package com.snapwiz.model.vo;
    //all relevant imports present.
    public class RedExample {
    private RedisTemplate redisTemplate;
    private ListOperations<String, String> listOps;
    public RedisTemplate getRedisTemplate() {
    return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
    }

    public void addLink(String userId, URL url) {
    JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
    Jedis jedis = pool.getResource();
    try {
    jedis.set("foo", "bar");
    String foobar = jedis.get("foo");
    System.out.println("foobar:: " + foobar);
    jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike");
    Set<String> sose = jedis.zrange("sose", 0, -1);
    System.out.println("sose:: " +sose.toString());

    /*// set 1 comments
    Object i = redisTemplate.execute(new RedisCallback<Object>() {
    public Object doInRedis(RedisConnection connection) throws DataAccessException {
    return connection.dbSize();
    }
    });
    System.out.println("dbSize:: "+i.toString());*/

    //set 2 comments
    /*listOps = redisTemplate.opsForList();
    listOps.leftPush(userId, url.toExternalForm());
    System.out.println(listOps.toString());
    */
    } finally {
    pool.returnResource(jedis);
    }
    pool.destroy();
    }
    }


    Junit Test case RedisExampleTest.java

    package com.snapwiz.junit;
    //all relevant imports present

    public class RedisExampleTest extends AbstractSpringTest{

    public RedisExampleTest() {
    super();
    setDefaultRollback(false);
    setAutowireMode(AUTOWIRE_BY_NAME);
    }
    public void testRedisExample() throws Exception {
    try{
    RedExample ex = new RedExample();
    URL url = new URL("http://google.com");

    ex.addLink("chits", url);
    } catch(Exception e){
    e.printStackTrace();
    }
    }
    }

    o/p:
    foobar:: bar
    sose:: [bike, car]

    My Questions
    1)When would I use instance of Jedis and do operations as in the example above (set, get, etc) vs use RedisTemplate and invoke methods such as opsForList() etc. (Block of code under set 2 comments)
    2)I read about RedisCallback, how it should be used to get hold of redisTemplate. When would I do that? (Block of code under set 1 comments).
    Kindly explain I am thoroughly confused.

    Error/Exception Report:
    When I uncomment code either under set 2 comments or set 1 comments , get following exception:: Just do not know what else I need to do. Am I missing any mappings?
    o/p:
    foobar:: bar
    sose:: [bike, car]
    java.lang.NullPointerException
    at com.snapwiz.model.vo.RedExample.addLink(RedExample .java:51)
    at com.snapwiz.junit.RedisExampleTest.testRedisExampl e(RedisExampleTest.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)

    Any help is appreciated and look forward to your early response.
    Thank you,

  • #2
    Hi,

    Your post has multiple questions (it's best to post them as multiple threads) and I'll try to answer all of them.
    First, do take a look at the example available for Spring Data Redis - it's the Twitter clone on Redis and it showcases most of the features (RedisTemplate included) of Spring Redis. It has plenty of docs (from redis.io and its own).

    1. RedisTemplate provides one-liners (simple operations) directly w/o the need to create the callback (it is already provided for you behind the scenes). The advantage of using the template is that it takes care of all the connection and exception handling and it works across multiple provides. For example in the last month a new provider (the 4th) has been added. You can switch between them without having to change any code.
    The list/set/zset interfaces are useful when you work with such a data structure - take a look at the sample to see it in practice. As an alternative you can use the JDK collection implementations for Redis.

    2. why would you need to get a hold of the template from the callback - you get the connection so you can call whatever methods you want on it. That's why one should use the callback in the first place - to get access to the native API. If you don't need that then simply use the template. The callback is not mandatory - it's just an option.

    3. you either create your own objects (and configure them appropriately) or you let Spring create them for you. In your test, you have created the RedisExample object yourself but failed to call its setters (to configure it basically) hence the NPE. And btw, you should use the annotation based test support in Spring - it's cleaner then the base class approach.
    This again is showcased in the sample and further more there's ton of material on testing spring apps - on google and inside the main Spring reference docs.

    A final advice, don't feel overwhelmed - just take it each thing, step by step and build up your app. Start with the basic testing (it applies to all Spring apps), make that work, then introduce Spring Data Redis and work your way app.

    Hth

    Comment


    • #3
      Costin,

      Thanks so much for your express response. It set me thinking as to what I had to do. I did as u suggested and it worked. Feels nice to see the o/p. Thank you for your advice.....

      To those of you who need help, this is what I did. Hope it helps someone in need.
      Added a mapping in application Context.xml
      <bean name="example" class="com.snapwiz.model.vo.RedExample" autowire="byName">
      <property name="redisTemplate" ref="redisTemplate"/>
      </bean>
      2)In Junit
      1.added property/getters/setters for RedExample.
      private RedExample example = null;
      2. changed code as follows
      public void testRedisExample() throws Exception {
      try{
      URL url = new URL("http://google.com");
      example.addLink("chits", url);
      } catch(Exception e){
      e.printStackTrace();
      }
      }

      When I uncomment the code under set 2. It works. Actually can print out the value by using leftPop method.
      Enjoy!!!

      Comment

      Working...
      X