spring data redis使用示例

1. 配置依赖文件

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.5.0.RELEASE</version>
    </dependency>
</dependencies>

2. 配置模板

<bean id="jedisConnFactory" 
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 
    p:use-pool="true"/>

<!-- redis template definition -->
<bean id="redisTemplate" 
    class="org.springframework.data.redis.core.RedisTemplate" 
    p:connection-factory-ref="jedisConnFactory"/>

3. 使用示例:

   3.1 K-V字符串类型的使用

    get方法:

    redisTemplate.opsForValue().get(key);

    set方法:

    /**
     * @param key
     * @param value
     * @param liveTime
     */
    private void set(String key, String value, long liveTime) {
        redisTemplate.opsForValue().set(key, value, liveTime, TimeUnit.SECONDS);
    }

 3.2 list类型

public class Example {

    // inject the actual template
    @Autowired
    private RedisTemplate<String, String> template;

    // inject the template as ListOperations
    // can also inject as Value, Set, ZSet, and HashOperations
    @Resource(name="redisTemplate")
    private ListOperations<String, String> listOps;

    public void addLink(String userId, URL url) {
        listOps.leftPush(userId, url.toExternalForm());
        // or use template directly
        redisTemplate.boundListOps(userId).leftPush(url.toExternalForm());
    }
}

类似的,其它类型可以使用

RedisTemplate的opsForX()方法

参考文献:

http://projects.spring.io/spring-data-redis/

原文地址:https://www.cnblogs.com/davidwang456/p/4554887.html