Trong các hệ thống phân tán, bộ nhớ đệm cục bộ đóng vai trò quan trọng để tối ưu hiệu năng. Caffeine cung cấp giải pháp lưu trữ cục bộ hiệu quả thay thế cho các hệ thống phức tạp như Redis trong những tình huống phù hợp.
Thiết lập Dependencies
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
Cấu hình Bộ nhớ đệm
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
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 java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
public class CacheConfiguration {
@Bean
public CacheManager cacheManager() {
CustomCacheManager manager = new CustomCacheManager();
manager.setDefaultConfiguration(Caffeine.newBuilder()
.initialCapacity(200)
.maximumSize(1000)
.expireAfterWrite(30, TimeUnit.MINUTES)
.recordStats());
manager.registerCache("user_cache", Caffeine.newBuilder()
.maximumSize(5000)
.expireAfterAccess(15, TimeUnit.MINUTES)
.recordStats());
manager.registerCache("config_cache", Caffeine.newBuilder()
.maximumSize(100)
.expireAfterWrite(24, TimeUnit.HOURS)
.recordStats());
manager.registerCache("session_cache", Caffeine.newBuilder()
.maximumSize(10000)
.expireAfterWrite(2, TimeUnit.HOURS)
.recordStats());
manager.registerCache("hot_data_cache", Caffeine.newBuilder()
.maximumSize(500)
.expireAfterWrite(5, TimeUnit.MINUTES)
.recordStats());
return manager;
}
public static class CustomCacheManager extends CaffeineCacheManager {
private final Map<String, Caffeine<Object, Object>> customConfigs = new HashMap<>();
private Caffeine<Object, Object> defaultConfig;
public void setDefaultConfiguration(Caffeine<Object, Object> config) {
this.defaultConfig = config;
setCaffeine(config);
}
public void registerCache(String name, Caffeine<Object, Object> config) {
customConfigs.put(name, config);
}
@Override
protected com.github.benmanes.caffeine.cache.Cache<Object, Object> createNativeCaffeineCache(String cacheName) {
Caffeine<Object, Object> config = customConfigs.getOrDefault(cacheName, defaultConfig);
return config != null ? config.build() : Caffeine.newBuilder().build();
}
}
}
Triển khai Sử dụng
@Service
public class AccountService {
@Autowired
private AccountRepository accountRepository;
@Cacheable(value = "user_cache", key = "#accountId")
public Account fetchAccount(Long accountId) {
System.out.println("Truy vấn database để lấy tài khoản: " + accountId);
return accountRepository.findById(accountId)
.orElseThrow(() -> new IllegalArgumentException("Không tìm thấy tài khoản: " + accountId));
}
@CachePut(value = "user", key = "#account.id")
public Account modifyAccount(Account account) {
System.out.println("Cập nhật thông tin tài khoản: " + account.getId());
Account updatedAccount = accountRepository.save(account);
return accountRepository.findById(updatedAccount.getId()).orElse(updatedAccount);
}
@CacheEvict(value = "user_cache", key = "#accountId")
public void removeAccount(Long accountId) {
System.out.println("Xóa tài khoản: " + accountId);
accountRepository.deleteById(accountId);
}
}