The address of the original text is updated, and the reading effect is better!
introduce
SpringData is a module for operating data in Spring, including the integration of various databases. The integration module for Redis is called SpringDataRedis. The official website address: https://spring.io/prohects/spring-data-redisopen in new window
- 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 Lettuce-based reactive programming
- Supports data serialization and deserialization based on JDK, JSON, strings, and Spring objects
- Supports Redis-based JDKCollection implementation
#Operation API
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 type | illustrate |
---|---|---|
redisTemplate.opsForValue() |
ValueOperations |
Operation String type data |
redisTemplate.opsForHash() |
HashOperations |
Operation Hash type data |
redisTemplate.opsForList() |
ListOperations |
Operation List type data |
redisTemplate.opsForSet() |
SetOperations |
Operation Set type data |
redisTemplate.opsForZSet() |
ZSetOperations |
Operation SortedSet type data |
redisTemplate |
common command |
Instructions for use
When we operate the corresponding Redis data, we obtain the corresponding operation object according to the data type. For example, when operating the String type, we call the method to redisTemplate.opsForValue()
obtain an ValueOperations
object to operate String
the type of data.
# Used in Spring Boot
- Introduce dependencies
<!--Redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--连接池依赖-->
<dependency>
<groupId>org.apache.commons<groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
- configuration file
spring :
redis :
host : 192.168.100.100
port : 6379
password : codermast
lettuce :
pool :
max-active : 8 # 最大的连接数
max-idle : 8 # 最大空闲连接
min-idle : 0 # 最小空闲连接
max-wait : 100 # 连接等待时间
- Get the RedisTemplate object
@Autowired
private RedisTemplate redisTemplate;
In the Spring Boot framework, use automatic injection to obtain objects
- write test class
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
void testString(){
// 插入一条 String 类型的数据
redisTemplate.opsForValue().set("name","codermast");
// 获取一条 String 类型的数据
Object name = redisTemplate.opsForValue().get("name");
System.out.println("我的名字是:" + name);
}
}
- Run to view the results
我的名字是:codermast