springboot与缓存
JSR-107、spring缓存抽象、整合Redis
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对。
每一个存储在Cache中的条目有一个定义的有效期,即Expiry Duration。一旦超过这个时间,条目为过期的状态。一旦过期,条目将不可访问、更新和删除。缓存有效期可以通过ExpiryPolicy设置。
————————————————
原文链接:https://blog.csdn.net/wilbertzhou/article/details/18888789
缓存抽象
java提供了简化的org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache(JSR-107)注解简化开发;
CacheManager接口为缓存管理器,管理各种缓存组件
Cache:缓存解耦,定义缓存操作。实现由RedisCache,EhCacheCache,ConcurrentMapCache等
@Cacheable 主要针对方法配置,根据方法的请求参数对其结构进行缓存
@CacheEvict 清空缓存
@CachePut 保证方法被调用,又希望结果被缓存
@EnableCaching 开启基于注解的缓存
keyGenerator 缓存数据时key生成策略
serialize 缓存数据时value序列化策略
使用缓存组件进行缓存操作
配置步骤:
1.添加依赖
<!-- 添加缓存依赖-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-startercache</artifactId>
</dependency>
2.添加配置(设置数据源,设置mybatis,添加映射):
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_cache?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/> //开启驼峰命名法
</settings>
</configuration>
xxxMaper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tree.springboot.dao.UserDao">
<!-- <resultMap id="UserMap" type="com.tree.springboot.dao.UserBean">-->
<!-- <id column="id" property="id"/>-->