新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

springboot如何使用redis注解,springboot -d

发布时间:2023-08-24 08:12:05

springboot如何使用redis注解

在Spring Boot中使用Redis注解,需要完成以下步骤:
1. 添加Redis依赖:在`pom.xml`文件中添加Redis相关依赖,例如:
```xml

org.springframework.boot
spring-boot-starter-data-redis

```
2. 配置Redis连接:在`application.properties`文件中配置Redis连接信息,包括主机、端口、密码等。例如:
```properties
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
```
3. 创建Redis配置类:创建一个配置类,用于配置Redis连接工厂和Redis模板等。例如:
```java
@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 redisTemplate() {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
```
4. 在需要使用Redis的类或方法上添加注解:可使用`@Cacheable`、`@CachePut`、`@CacheEvict`等注解来实现缓存操作。例如:
```java
@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);
}
}
```
5. 启用缓存:在启动类上添加`@EnableCaching`注解,开启缓存功能。例如:
```java
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
这样,就能够在Spring Boot中使用Redis注解进行缓存操作了。