foreword
Redis 1 is a key-value storage system written by Salvatore Sanfilippo.
Edis is an open source log-type, Key-Value database written in ANSI C language, complying with BSD protocol, supporting network, memory-based and persistent, and providing APIs in multiple languages.
Often referred to as a data structure server because values can be of types such as String, Hash (Map), list (list), sets (sets) and sorted sets (sorted sets).
text
import dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
It should be noted that the above is the name after the
Spring Boot 1.5
version before version 1.5spring-boot-starter-redis
.
parameter configuration
spring:
redis:
host: 192.168.19.200 # host ,默认 localhost
port: 6379 # 端口号,默认6379
pool:
# 设置都是默认值,可以按需求设计
max-active: 8 # 可用连接实例的最大数目,默认值为8;如果赋值为-1,则表示不限制;
max-idle: 8 # 控制一个pool最多有多少个状态为idle(空闲的)的redis实例,默认值也是8。
max-wait: -1 # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。
min-idle: 0 # 控制一个pool最少有多少个状态为idle(空闲的)的redis实例,默认值为0。
timeout: 0 # 连接超时时间 单位 ms,默认为0
password: master # 密码,根据自己的 redis 设计,默认为空
use
Register a configuration class RedisTemplate
to support serialization and deserialization:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
// 使用 Jackson2JsonRedisSerializer 进行序列化,它继承 RedisSerializer,
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
Test using:
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test() {
stringRedisTemplate.opsForValue().set("id", "1");
Assert.assertEquals("1", stringRedisTemplate.opsForValue().get("id"));
}
/**
* 测试存储对象,redis 需要对对象进行序列化,取出对象数据后比对,又要进行反序列化
* 所以注册了 RedisTemplate ,专门处理这类情况
*/
@Test
public void test1() {
SysUserEntity sysUserEntity = new SysUserEntity();
sysUserEntity.setId(2L);
sysUserEntity.setEmail("[email protected]");
ValueOperations<String, SysUserEntity> operations = redisTemplate.opsForValue();
operations.set("user1", sysUserEntity);
Assert.assertThat(sysUserEntity, Matchers.equalTo(operations.get("user1")));
}
}
Spring Data Redis usage documentation
- REmote DIctionary Server ↩