在Spring Boot中使用Redis注解,需要完成以下步驟:
pom.xml
文件中添加Redis相關依賴,例如:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties
文件中配置Redis連接信息,包括主機、端口、密碼等。例如:spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName("127.0.0.1");
configuration.setPort(6379);
configuration.setPassword(RedisPassword.none());
LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration);
factory.afterPropertiesSet();
return factory;
}
@Bean
public RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
@Cacheable
、@CachePut
、@CacheEvict
等注解來實現緩存操作。例如:@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
@CachePut(value = "users", key = "#user.id")
public User saveUser(User user) {
return userRepository.save(user);
}
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
@EnableCaching
注解,開啟緩存功能。例如:@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
這樣,就可以在Spring Boot中使用Redis注解進行緩存操作了。