Spring Data Redis 快速指南
目录
@Configuration
class RedisConfiguration {
@Bean
public JedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("server", 6379);
return new JedisConnectionFactory(config);
}
}
模板为Redis交互提供了一个高级抽象。RedisConnection提供接受和返回二进制值(字节数组)的低级方法,而模板负责序列化和连接管理,使用户不必处理这些细节。此外,模板还提供了operations视图(根据Redis命令参考中的分组),它提供了丰富的、泛型的接口,用于处理特定类型或特定键(通过键绑定接口)。
一旦配置好,模板就是线程安全的,可以跨多个实例重用。
RedisTemplate的大部分操作都使用基于java的序列化程序。这意味着由模板写入或读取的任何对象都将通过Java进行序列化和反序列化。
k-v都是String类型,官方建议符合这种格式的推荐使用 StringRedisTemplate。
由于Redis中存储的键和值通常是java.lang.String,因此Redis模块提供了RedisConnection和RedisTemplate的两个扩展,分别是StringRedisConnection(及其DefaultStringRedisConnection实现)和StringRedisTemplate,这是一种便捷的一站式解决方案 用于密集的String操作。
public class Person {
String firstname;
String lastname;
// …
}
public class HashMapping {
@Autowired
HashOperations<String, byte[], byte[]> hashOperations;
HashMapper<Object, byte[], byte[]> mapper = new ObjectHashMapper();
public void writeHash(String key, Person person) {
Map<byte[], byte[]> mappedHash = mapper.toHash(person);
hashOperations.putAll(key, mappedHash);
}
public Person loadHash(String key) {
Map<byte[], byte[]> loadedHash = hashOperations.entries("key");
return (Person) mapper.fromHash(loadedHash);
}
}
Jackson2JsonRedisSerializer可以将对象转换成JSON格式。
Interface | Description |
---|---|
Key Type Operations | |
GeoOperations |
Redis geospatial operations, such as GEOADD , GEORADIUS ,… |
HashOperations |
Redis hash operations |
HyperLogLogOperations |
Redis HyperLogLog operations, such as PFADD , PFCOUNT ,… |
ListOperations |
Redis list operations |
SetOperations |
Redis set operations |
ValueOperations |
Redis string (or value) operations |
ZSetOperations |
Redis zset (or sorted set) operations |
Key Bound Operations | |
BoundGeoOperations |
Redis key bound geospatial operations |
BoundHashOperations |
Redis hash key bound operations |
BoundKeyOperations |
Redis key bound operations |
BoundListOperations |
Redis list key bound operations |
BoundSetOperations |
Redis set key bound operations |
BoundValueOperations |
Redis string (or value) key bound operations |
BoundZSetOperations |
Redis zset (or sorted set) key bound operations |
由于在RedisTemplate
中,ValueOperations
和BoundValueOperations
这种都是一一对应的关系。BoundValueOperations
只不过是先绑定key
,再进行操作的,所以本文会着重分析ValueOperations
这样的操作类的API。
@SpringBootTest
public class RedisTests {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void testHashOps() {
System.out.println(redisTemplate.toString());
HashOperations<String,String,String> ops = redisTemplate.opsForHash();
ops.put("id","refreshToken","token");
Object aa = ops.get("id","refreshToken");
System.out.println(aa);
}
}