- 1. Features of Spring Data Redis
- 2. Steps using SpringDataRedis
- 3. Customize RedisTemplate serialization
- 4. SpringDataRedis operation object
1. Features of SpringDataRedis
- Provides integration with different Redis clients (Lettuce and Jedis)
- Provides RedisTemplate unified API to operate Redis
- Support Redis publish-subscribe model
- Support for Redis Sentinel and Redis Cluster
- Support for Lettuce-based reactive programming
- Supports data serialization and deserialization based on JDK, JSON, strings, and Spring objects
- Support for Redis-based JDKCollection implementation
The RedisTemplate tool class is provided in SpringDataRedis, which encapsulates various operations on Redis. And the operation API of different data types is encapsulated into different types:
API | Return value type | Description |
---|---|---|
redisTemplate.opsForvalue() | valueOperations | Operate String type data |
redisTemplate.opsForHash() | HashOperations | Operate Hash type data |
redisTemplate.opsForList() | ListOperations | Operate List Type data |
redisTemplate.opsForSet() | SetOperations | Operation Set type data |
redisTemplate.opsForZSet() | ZSetOperations | Operate SortedSet type data |
2. Steps to use SpringDataRedis
1. Create a project
Pay attention to the version 2 here
2. Introduce dependencies
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
3. Configure Redis
spring: redis: host: 140.210.207.112 port: 6379 password: 123456 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: 100ms
4. Inject RedisTemplate and write test cases
@Autowired private RedisTemplate redisTemplate; @Test void testString() {<!-- --> //Write a string data redisTemplate.opsForValue().set("name","Li Si"); //Get string data Object name = redisTemplate.opsForValue().get("name"); //Print System.out.println("name = " + name); }
But we found that there is no storage in redis
Take a look with the visualizer:
This is a serialization problem. RedisTemplate can receive any Object as a value and write it to Redis, but it will serialize the Object into bytes before writing. The default is to use JDK serialization.
3. Customize RedisTemplate serialization
Introduce Jackson dependency first:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency>
@Configuration public class RedisConfig {<!-- --> @Resource RedisConnectionFactory connectionFactory; @Bean public RedisTemplate<String, Object> redisTemplate(){<!-- --> // create RedisTemplate object RedisTemplate<String, Object> template = new RedisTemplate<>(); // set up the connection factory template.setConnectionFactory(connectionFactory); // create JSON serializer GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); // Set the serialization of Key template.setKeySerializer(RedisSerializer.string()); template.setHashKeySerializer(RedisSerializer.string()); // Set the serialization of Value template.setValueSerializer(jsonRedisSerializer); template.setHashValueSerializer(jsonRedisSerializer); // return return template; } }
This can be read:
But the value is still garbled on the server:
We start the server command and add --raw
to the end.
redisTemplate can operate on different data types, and the api is the same as our instructions.
opsForValue: operation string->
String
opsForList: Operation List->
List
opsForSet: Operation Set->
Set
opsForHash: Operation Hash
opsForZSet: Operation ZSet
opsForGeo: Operation Geospatial
opsForHyperLogLog: operate HyperLogLog
In addition to basic operations, our commonly used methods can be directly operated through redisTemplate, such as transactions, and basic CRUD.
4. SpringDataRedis operation object
If you do not use the no-argument construction method here, you will report an error. Note:
Here JSON serialization is used instead of the default JDK serialization:
The overall readability has been greatly improved, and Java objects can be automatically serialized into JSON strings, and JSON can be automatically deserialized into Java objects when querying. However, it records the corresponding class name during serialization, in order to realize automatic deserialization when querying. This introduces additional memory overhead.
Therefore, in order to save memory space, we can use the String serializer uniformly instead of using the JSON serializer to process the value, requiring only the key and value of the String type to be stored. When Java objects need to be stored, the serialization and deserialization of the objects is done manually.
In this way, the serialization and deserialization when we store and read are implemented by ourselves, and SpringDataRedis will not write class information into Redis.
This kind of usage is more common, so SpringDataRedis provides a subclass of RedisTemplate: StringRedisTemplate, the serialization method of its key and value is String by default.
@Autowired private StringRedisTemplate stringRedisTemplate; // JSON serializer private static final ObjectMapper mapper = new ObjectMapper(); @Test void testSaveUser2() throws JsonProcessingException {<!-- --> // create object User user = new User("Zhang San", 22); // manual serialization String JSON = mapper. writeValueAsString(user); // data input stringRedisTemplate.opsForValue().set("user", JSON); // retrieve data String jsonUser = stringRedisTemplate.opsForValue().get("user"); // manual deserialization User user1 = mapper. readValue(jsonUser, User. class); System.out.println("user1 = " + user1); }