Working with Objects through RedisTemplate
使用 RedisTemplate操作 Objects
大多数用户都喜欢使用RedisTemplate ,它相应的包目录位于org.springframework.data.redis.core,丰富的特性集使它成为Redis模块的中心类。该模块提供了一个与Redis 交互的高级抽象封装。当使用RedisConnection 来访问底层方法(访问或返回字节数组)时,RedisTemplate实现了底层的序列化和连接管理,使使用者不用再关注底层细节。
此外,RedisTemplate提供了 operations views(对应于Redis的命令集),针对某类型或某key(使用KeyBound 接口)都有丰富的、原型的接口,如下描述:
一旦配置后,RedisTemplate是线程安全的,能在多线程间重复利用。
拿来即用,RedisTemplate为大多数操作提供了一个基于Java的序列化转换器。这意味着使用RedisTemplate 写或读的任何对象都将会通过Java进行序列化/反序列化。RedisTemplate的序列化机制可以轻松的改变,Redis模块提供了多个可用的序列化实现,位于org.springframework.data.redis.serializer目录下,在有关序列化转换器章节可以查看更多信息。你也可以不设置序列化转换器,而使用原生的字节数组,同时需要设置enableDefaultSerializer为false。注意,RedisTemplate要求所有的key为非空,而值可以为空,但需要跟底层的序列化转换器要求一致,针对每个序列化转换器的要求可以查看Java文档来得到更多信息。
For cases where a certain template view is needed, declare the view as a dependency and inject the template: the container will automatically perform the conversion eliminating the opsFor[X] calls:
当需要某模版时,只需要定义它的依赖并注入即可,容器会自动执行转换而不需要执行 opsFor[x]。
properties配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="jedisConnectionFactory" 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="jedisConnectionFactory"/>
...
</beans>
示例代码如下:
public class Example {
// inject the actual template
@Autowired
private RedisTemplate<String, String> template;
// inject the template as ListOperations
@Resource(name="redisTemplate")
private ListOperations<String, String> listOps;
public void addLink(String userId, URL url) {
listOps.leftPush(userId, url.toExternalForm());
}
}