@Cacheable双::变单:
时间: 2023-11-16 18:01:38 浏览: 43
在使用spring-data-redis2.x版本时,@Cacheable缓存key值时默认会给value或cacheNames后加上双冒号,而改为单冒号。同时,也会默认给value或cacheNames后加上双引号,而不是单引号。这是因为在Redis中,双冒号和双引号都有特殊的含义,为了避免出现问题,spring-data-redis2.x版本做了这样的修改。
相关问题
@Cacheable怎么使用
@Cacheable是Spring框架中的一个缓存注解,用于标记一个方法的返回值是可以被缓存的。当在同一个类中的其他方法调用这个被@Cacheable注解的方法时,Spring会先检查缓存中是否已经存在这个方法的返回值,如果存在,则直接返回缓存中的值,否则执行该方法并将返回值存入缓存中。@Cacheable注解可以用在类级别和方法级别上,用法如下:
1.在类级别上使用@Cacheable注解:
```java
@Service
@Cacheable(value = "myCache")
public class MyService {
// ...
}
```
2.在方法级别上使用@Cacheable注解:
```java
@Service
public class MyService {
@Cacheable(value = "myCache", key = "#id")
public User getUserById(Long id) {
// ...
}
}
```
在上面的例子中,@Cacheable注解的value属性指定了缓存的名称,key属性指定了缓存的键值,Spring会根据这个键值来检索缓存中是否已经存在该方法的返回值。
springboot开启@Cacheable
在Spring Boot中开启@Cacheable需要三个步骤:
1. 在启动类上加上注解@EnableCaching
2. 在缓存的配置文件中配置缓存的类型和缓存策略
3. 在需要缓存的方法上加上注解@Cacheable
例如,以下代码实现了基于Redis的缓存:
在启动类中加上@EnableCaching注解:
```
@SpringBootApplication
@EnableCaching
public class Application {
// ...
}
```
在application.properties文件中配置Redis:
```
# Redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=
```
在需要缓存的方法上加上@Cacheable注解:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
@Cacheable(value = "user", key = "#id")
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
```
其中,value属性表示缓存的名称,key属性表示缓存的键。