在使用Spring Boot整合Redis時(shí),有一些重要的注意事項(xiàng)需要遵循。以下是一些關(guān)鍵點(diǎn):
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
pom.xml
或build.gradle
中正確添加Redis客戶(hù)端依賴(lài)。<!-- 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"));
}
}
通過(guò)遵循這些注意事項(xiàng),可以確保Spring Boot與Redis的整合順利進(jìn)行,并且能夠高效、安全地使用Redis。