怎么弄一个spring boot 缓存
时间: 2023-10-18 07:04:40 浏览: 42
要在Spring Boot中使用缓存,需要考虑以下几个步骤:
1. 添加Spring Boot支持的缓存依赖,例如Ehcache、Redis等。
2. 在应用程序的配置文件中配置缓存属性,例如缓存类型、缓存大小、缓存过期时间等。
3. 在需要缓存的方法上添加注释,例如@Cacheable、@CachePut等。
下面是一个使用Ehcache作为缓存的示例:
1. 添加Ehcache依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
```
2. 在应用程序的配置文件中配置缓存属性
```yaml
spring:
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
```
其中,ehcache.xml是一个Ehcache配置文件,可以在classpath中找到。例如:
```xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<cache name="myCache"
maxEntriesLocalHeap="1000"
timeToLiveSeconds="300"
timeToIdleSeconds="60">
</cache>
</ehcache>
```
3. 在需要缓存的方法上添加注释
```java
@Service
public class MyService {
@Cacheable(value = "myCache", key = "#id")
public String findById(Long id) {
// ...
}
@CachePut(value = "myCache", key = "#id")
public void update(Long id, String data) {
// ...
}
}
```
其中,@Cacheable表示该方法的结果将被缓存,@CachePut表示该方法的结果将被更新到缓存中。
以上就是一个简单的Spring Boot缓存的示例。注意,在实际开发中,需要根据具体的业务需求和场景来选择缓存的类型、大小、过期时间等属性。