springboot整合

288 阅读5分钟

一、SpringBoot与缓存

1、JSR-107缓存规范

Java Caching定义了5个核心接口,分别是CachingProvider,CacheManager, Cache, Entry和 Expiry
  • CachingProvider定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可以在运行期访问多个CachingProvider。
  • CacheManager定义了创建、配置、获取、管理和控制多个唯一命名的Cache,这些Cache存在于CacheManager的上下文中。一个CacheManager仅被一个CachingProvider所拥有。
  • Cache是一个类似Map的数据结构并临时存储以Key为索引的值。一个Cache仅被一个CacheManager所拥有。
  • Entry是一个存储在Cache中的key-value对。
  • Expiry 每一个存储在Cache中的条目有一个定义的有效期。一旦超过这个时间,条目为过期的状态。一旦过期,条目将不可访问、更新和删除。缓存有效期可以通过ExpiryPolicy设置

2、Spring缓存抽象

Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;
并支持使用JCache(JSR-107)注解简化我们开发;
几个重要概念及缓存注解
Cache:缓存接口,定义缓存操作。实现有RedisCache、EhCacheCache、ConcurrentMapCache等
CacheManager:缓存管理器,管理各种缓存(Cache)组件
@Cacheable:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@CacheEvict:清空缓存
@CachePut:保证方法被调用,又希望结果被缓存
@EnableCaching:开启基于注解的缓存
keyGenerator:缓存数据时key生成策略
serialize:缓存数据时value序列化策略
缓存Hello World

EmployeeService.java

@Service
public class EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Cacheable(cacheNames = {"emp"})
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        Employee employee=employeeMapper.getEmpById(id);
        return employee;
    }
}

Springboot01CacheApplication.java

@MapperScan("com.bjlemon.springboot.mapper")
@SpringBootApplication
@EnableCaching
public class Springboot01CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot01CacheApplication.class, args);
    }
}
原理:
1、自动配置类;CacheAutoConfiguration
2、缓存的配置类
    org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
    org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
    org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
    org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
    org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
    org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
    org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
    org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
    org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
    org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
3、哪个配置类默认生效:SimpleCacheConfiguration
4、给容器中注册了一个CacheManager:ConcurrentMapCacheManager
5、可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中
运行流程:
1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
(CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建
2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key
SimpleKeyGenerator生成key的默认策略:
    如果没有参数;key=new SimpleKey()
    如果有一个参数:key=参数的值
    如果有多个参数:key=new SimpleKey(params)
3、没有查到缓存就调用目标方法
4、将目标方法返回的结果,放进缓存中
@Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
核心:
1)、使用CacheManager【ConcurrentMapCacheManager】按照名字得到Cache【ConcurrentMapCache】组件
2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator
重要的属性:
cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存
key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值
//getEmp[2]
@Cacheable(cacheNames = {"emp"},key = "#root.methodName+'['+#id+']'")
public Employee getEmp(Integer id){
    System.out.println("查询"+id+"号员工");
    Employee employee=employeeMapper.getEmpById(id);
    return employee;
}
keyGenerator:key的生成器;可以自己指定key的生成器的组件id
key/keyGenerator:二选一使用
@Configuration
public class MyCacheConfig {
    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator(){
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return method.getName()+"["+ Arrays.asList(params).toString()+"]";
            }
        };
    }
}
@Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator")
public Employee getEmp(Integer id){
    System.out.println("查询"+id+"号员工");
    Employee employee=employeeMapper.getEmpById(id);
    return employee;
}
Cache SpEL
methodName:当前被调用的方法名,#root.methodName
method:当前被调用的方法,#root.method.name
target:当前被调用的目标对象,#root.target
targetClass:当前被调用的目标对象类,#root.targetClass
args:当前被调用的方法的参数列表,#root.args[0]
caches:当前方法调用使用的缓存列表,#root.caches[0].name
argument name:方法参数的名字,可以直接#参数名,也可以使用#p0的形式,0代表参数的索引
result:方法执行后的返回值,#result
@CachePut:既调用方法,又更新缓存数据;同步更新缓存,
修改了数据库的某个数据,同时更新缓存
运行时机:
1)、先调用目标方法
2)、将目标方法的结果缓存起来
测试步骤:
1、查询1号员工;查到的结果会放在缓存中
    key:1  value:Employee
2、以后查询还是之前的结果
3、更新1号员工,将方法的返回值也放进缓存了
    key:传入的employee对象  value:返回的employee对象;
4、查询1号员工?应该是更新后的员工
    key = "#employee.id":使用传入的参数的员工id
    key = "#result.id":使用返回后的id
    @Cacheable的key是不能用#result,因为执行的时机不一样
    为什么是没更新前的?【1号员工没有在缓存中更新】
@CachePut(value = "emp",key = "#employee.id")
public Employee updateEmp(Employee employee){
    System.out.println("updateEmp:"+employee);
    employeeMapper.updateEmp(employee);
    return employee;
}
@CacheEvict:缓存清除
key:指定要清除的数据
allEntries = true:指定清除这个缓存中所有的数据
beforeInvocation = false:缓存的清除是否在方法之前执行
    默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除
beforeInvocation = true:代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除
@CacheEvict(value = "emp",key = "#id")
public void deleteEmp(Integer id){
    System.out.println("deleteEmp:"+id);
    employeeMapper.deleteEmpById(id);
}
@Caching:定义复杂的缓存规则
@CacheConfig(cacheNames = "emp"):抽取缓存的公共配置
@CacheConfig(cacheNames = "emp")
@Service
public class EmployeeService {
    @Caching(
            cacheable = {
                    @Cacheable(value = "emp",key = "#lastName")
            },
            put = {
                    @CachePut(value="emp",key="#result.id"),
                    @CachePut(value = "emp",key = "#result.email")
            }
    )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }
}

3、整合Redis