Spring Data Redis(RedisTemplate的使用)

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());
  }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值