在使用Spring Boot整合Redis时,有一些重要的注意事项需要遵循。以下是一些关键点:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
pom.xml
或build.gradle
中正确添加Redis客户端依赖。<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
// Gradle
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(factory);
return template;
}
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Transactional
public void saveData(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
spring.redis.lettuce.pool.max-active=100
spring.redis.lettuce.pool.min-idle=10
spring.redis.lettuce.pool.max-idle=50
logging.level.org.springframework.data.redis=DEBUG
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
public void testSetAndGet() {
redisTemplate.opsForValue().set("key", "value");
assertEquals("value", redisTemplate.opsForValue().get("key"));
}
}
通过遵循这些注意事项,可以确保Spring Boot与Redis的整合顺利进行,并且能够高效、安全地使用Redis。