Springboot 2.x 使用Caffeine 和 Redis搭建多級緩存案例
时间: 2024-04-09 17:28:29 浏览: 29
使用Spring Boot 2.x搭建多级缓存案例,结合Caffeine和Redis,可以提供更高效的缓存机制。下面是一个简单的示例:
1. 首先,确保在项目的pom.xml文件中添加以下依赖:
```xml
<!-- Caffeine -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Spring Boot Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在application.properties文件中配置Redis连接信息:
```properties
spring.redis.host=your_redis_host
spring.redis.port=your_redis_port
```
3. 创建一个缓存配置类,例如CacheConfig:
```java
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Bean
@Override
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager("myCache");
cacheManager.setCaffeine(caffeineCacheBuilder());
return cacheManager;
}
Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.recordStats();
}
}
```
4. 创建一个Service类,例如DemoService,使用@Cacheable注解进行缓存:
```java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Cacheable(cacheNames = "myCache")
public String getData(String key) {
// 从数据库或其他数据源获取数据
return "Data for key: " + key;
}
}
```
5. 在Controller中使用DemoService类:
```java
import org.springframework.beans.factory.annotation.Autowired;