摘要:缓存在现代应用中无处不在,它为服务的高可用提供了很大的帮助。spring框架提供了对缓存的支持。Spring Boot通过@EnableCaching注解开启全局服务缓存功能。对于某个服务类方法的返回值缓存,可以采用@Cacheable注解实现。spring-
缓存在现代应用中无处不在,它为服务的高可用提供了很大的帮助。spring框架提供了对缓存的支持。Spring Boot通过@EnableCaching注解开启全局服务缓存功能。对于某个服务类方法的返回值缓存,可以采用@Cacheable注解实现。spring-boot-startercache模块集成了现有的一些缓存框架,如ehcache和Couchbase等。
EhCache是一个常用的缓存框架,可以通过配置文件ehcache.xml生成EhCache-CacheManager。Spring Boot的配置文件内容如下:
spring:
cache:
ehcache:
config: classpath:ehcache.xml
type: ehcache
配置文件ehcache.xml的内容如下:
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="6000"
timeToLiveSeconds="6000"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
eternal="false"
timeToLiveSeconds="72000"
timeToIdleSeconds="72000"
diskExpiryThreadIntervalSeconds="600"
/>
下面是一个具体的示例:
@Service
public class UserService {
@Autowired
private UserDao userDao;
//缓存返回数据
@Cacheable(value="user")
public User findOne(Integer userId){
return userDao.findOne(userId);
}
//清除缓存
@CacheEvict(value="user")
public String delete(Integer userId){
return userDao.delete(userId);
}
//缓存结果
@CachePut(value="userAll")
public List findAll{
return userDao.findAll;
}
}
以上代码中3个注解的作用如下:
@Cacheable:缓存结果,只执行一次方法,下一次不会调用方法,直接返回缓存结果。
@CachePut:可以根据参数进行缓存,与@Cacheable不同的是,不判断缓存中是否有之前执行的结果,每次都会调用方法。
@ CacheEvict:从缓存中删除响应的数据。
Couchbase是一个面向文档的分布式和多模型开源数据库,主要用于交互式应用程序。Spring Boot为Couchbase提供了自动配置,Spring Data为Couchbase提供了抽象封装。Spring Boot提供了Couchbase的Starter,即spring-boot-starter-data-couchbase。
由于Couchbase是存放在内存中,所以读取速度非常快。
Couchbase还自带集群方案,支持多副本和持久化,可以满足系统的高可用方案。
Spring Boot集成Couchbase的配置示例如下:
spring:
couchbase:
bootstrap-hosts: localhost
username: admin
password: 123456
bucket:
name: test
password: 123456
env:
timeouts:
connect: 30000
query: 2000
Spring Boot通过CouchbaseTemplate模板类操作数据库。
来源:大数据架构师