Using the underlying API: RedisConnection
operation of Redis requires manual conversion of data ( String <---->byte
), which requires most repetitive work and is inefficient; org.springframework.data.redis.core.RedisTemplate
classes provide a high level of abstraction for interacting with Redis, which is responsible for serialization and connection management, encapsulating most of the repetitive work. And RedisTemplate
is a thread-safe class.
In addition, the template provides an operation view for handling specific types or specific keys. The included interfaces are shown in the following table:
Example: The configuration file for the third step in the previous section adds the following:
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/></bean>
Test redistemplate:
// RedisTemplate 操作RedisTemplate redisTemplate = context.getBean(RedisTemplate.class); // 获取String类型的操作类ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();valueOperations.set("haha", "你好");System.out.println(valueOperations.get("haha"));
Optimization:
In the above example, when you need to manipulate a type, you RedisTemplate
get a reference to the corresponding action class from the template class, this step is repeated, can be Spring DI
injected, you can save a line of code, the code is as follows
@Autowiredprivate RedisTemplate template;@Resource(name = "redisTemplate")private ValueOperations valueOps;
Example description
1. RedisTemplate是一个泛型类,可以指定key和value的类型2. 想操作Redis的哪种类型数据,从RedisTemplate 获取对应操作的引用,如上面的valueOperations 3. 使用RedisTemplate,没有了底层API将数据转byte的操作
Spring Data Redis Primer Example: Based on Redistemplate (iii)