A.9 springboot cache

2018-02-12  本文已影响0人  成长的键盘手

1. 引言

程序大部分的时间在磁盘IO,内存的速度快于磁盘。随着用户量、数据量的增加,数据库的查询操作会成为影响用户体验的瓶颈。使用内存代替IO是优化的重要途径。

springboot 对spring3的声明式缓存做了包装,本文将说明springboot 提供的

参考资料:

2. Spring Cache 的注解说明

2.1 类说明

Spring 提供了一套标准的缓存体系,主要类说明如下:

==1、CacheManager==

==2、Cache==

2.2 缓存的实现

Spring集成多种缓存厂家来实现Cache

实现厂商 说明
Srping SimpleCacheManager 使用collection来做存储缓存,主要用用测试
Spring ConcurrentMapCacheManager 使用ConcurrentMap来做存储缓存
EhCache EhCacheManager 使用EhCache来作为缓存
Hazelcast HazelcastCacheManager 使用Hazelcast作为缓存技术
Guava GuavaCacheManager 使用Google Guava作为缓存技术
Redis RedisCacheMananger 使用Redis作为存储缓存

2.3 声明式缓存注解

@Cacheable

注解驱动缓存,加在需要缓存的方法上,在方法执行后,会将其返回结果进行缓存起来,以保证下次同样参数来执行该方法的时候可以从缓存中返回结果,而不需要再次执行此方法。

Spring缓存方法的返回值是以键值对进行保存的,值就是返回结果,键的使用:

@Cacheable(value="users", key="#id")  
public User find(Integer id) {  
     return null;  
} 

@Cacheable(value="users", key="#user.id")  
public User find(User user) {  
    return null;  
}  

注解参数说明:

@CachePut

加在需要修改缓存的方法上,无论是否缓存都会将方法的返回值放入缓存,所以主要用于数据新增和修改操作上。
用法和@Cacheable类似

@CacheEvict

加载需要清除缓存的方法上,用来将缓存中的数据清理掉,通常用于具有删除性质的方法上。

注解说明:

@CacheConfig

加载需要缓存的类上,主要用于配置该类中的缓存存储的集合名,等同于@Cacheable的value、cacheNames。也可以不使用该注解,直接通过@Cacheable自己配置缓存集的名字来定义。

3. SpringBoot Cache

3.1 SpringBoot Ehcache

修改pom.xml

在pom中增加以下配置:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

创建配置文件:ehcache.xml

在src/main/resources目录下创建:ehcache.xml。也可以在application.properties 中使用配置来引入ehcache的配置文件:

spring.cache.ehcache.config=classpath:config/another-config.xml

ehcache.xml 的内容如下:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <!-- 详细的参数命名请参见Ehcache官网 -->
    <cache name="users"
           maxEntriesLocalHeap="200"
           timeToLiveSeconds="600">
    </cache>

</ehcache>

3.2 SpringBoot Redis Cache

修改pom.xml

在pom中增加以下配置:

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-cache</artifactId>  
</dependency>  
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-redis</artifactId>  
</dependency> 

连接Redis

在 application.properties 中增加 redis 的配置链接:

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

配置缓存类

注册一个 CacheManager 到 spring 的 context 中

/**
 * 缓存配置
 * @return
 */
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);  
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);  
    ObjectMapper om = new ObjectMapper();  
    om.setVisibility(PropertyAccessor.ALL, com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY);  
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
    om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    jackson2JsonRedisSerializer.setObjectMapper(om);  
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();  
    return new RedisCacheManager(template);
}

3.3 测试

在SpringBoot的入口类上开启缓存,无论是使用ehcache 还是redis cache都需要声明式的开启缓存。

@EnableCaching

编写一个service,样例代码大致如下(无论是使用ehcache作为缓存还是使用redis 等其他的缓存,样例代码都一样),调用方法后,可通过查看sql,观察方法体有没有执行,缓存是否生效。

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import pers.mateng.demo.springboot.domain.User;

@Service
@CacheConfig(cacheNames="users")
public class UserService {

    @Autowired
    private EntityManager entityManager;
    
    @Cacheable(key="'users:' + #name")
    public User getUserByName(String name) {
        String hql = "from User u where u.name = ?0";
        Query query = entityManager.createQuery(hql);
        query.setParameter(0, name);
        return (User) query.getSingleResult();
    }
    
    @CacheEvict(key="'users:' + #name")
    @Transactional
    public void delete(String name) {
        String hql = "delete from User u where u.name = ?0";
        Query query = entityManager.createQuery(hql);
        query.setParameter(0, name);
        query.executeUpdate();
    }
    
}
上一篇 下一篇

猜你喜欢

热点阅读