Spring Data Redis

Posted By : Navjot Chauhan | 13-Nov-2014

Redis
Redis(An open source and NOSQL database) is a key-value stores written in C. It is highly supported by Spring Data as provided with features like scalability, high-performance.

 

Spring Data Redis

Spring Data is a spring project which uses new data access technologies like non-relationals DB, map-reduce frameworks, and cloud based data services. Spring data has many sub-projects and we are going to look at Spring-data-redis sub-project. It is nothing but a redis integration with the Spring data.

 

Start with an example.

Spring Data Redis Maven dependency

<!-- Redis dependencies -->

        <dependency>

            <groupId>org.springframework.data</groupId>

            <artifactId>spring-data-redis</artifactId>

            <version>1.4.0.RELEASE</version>

        </dependency>

Spring configuration for Jedis Connector looks like:

<bean id="jedisConnectionFactory"

        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"

        p:use-pool="true"  p:host-name="localhost" p:port="6379" />

<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"

        p:connection-factory-ref="jedisConnectionFactory" />

<bean id="autoSwitchQueue"

        class="org.springframework.data.redis.support.collections.DefaultRedisList">

        <constructor-arg ref="redisTemplate" />

        <constructor-arg value="autoSwitchQueue" />

 </bean>

The Redis modules provides extensions to RedisConnection and RedisTemplate.

Use of Template

In Java class, we are going to store key/value pairs of type String/String.

public class Example {

  @Autowired
  private StringRedisTemplate redisTemplate;

  private static final String REDISCHANNEL = "springDataRedisChannel";

  public void addLink(String userId, URL url) {

        template.convertAndSend(REDISCHANNEL, "Hello_world");

  }

}

Redis Listener

Back in the Spring configuration xml, copy and paste the below lines.

<bean class="com.resolution.scheduler.service.listeners.MessageDelegate" id="listener"/>

    <redis:listener-container connection-factory="jedisConnectionFactory">

        <redis:listener ref="listener" method="handleSpringData" topic="springDataredisChannel" />

    </redis:listener-container>

The MessageListener

public Class MessageDelegate {

    void handleSpringData(String message){

           System.out.println(message);

    }

}

About Author

Author Image
Navjot Chauhan

Navjot is a bright Groovy and Grails developer and has worked on development of various SaaS applications using Grails framework.

Request for Proposal

Name is required

Comment is required

Sending message..