在Spring Boot中配置Redis需要做以下几步:
在pom.xml
文件中添加Redis相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application.properties
(或application.yml
)文件中配置Redis连接信息:
spring.redis.host=REDIS_HOST
spring.redis.port=REDIS_PORT
spring.redis.password=REDIS_PASSWORD
在配置类中创建一个RedisTemplate
的Bean:
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private int redisPort;
@Value("${spring.redis.password}")
private String redisPassword;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort);
config.setPassword(RedisPassword.of(redisPassword));
return new LettuceConnectionFactory(config);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
这样就完成了Spring Boot中Redis的配置。你可以使用@Autowired
注解将RedisTemplate
注入到其他类中进行操作。