您的位置:首页 > 数据库 > Redis

spring data redis使用示例

2015-06-05 16:09 941 查看
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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: