Spring Boot 和 缓存的使用(Redis)
JSR107的规范
Java Caching定义了5个核心接口,分别是CacheingProvider,CacheManager,Cache,Entry和Expiry
- CachingProvider定义创建、配置、获取、管理、和控制多个CacheManager。一个应用可以在运行期间访问多个CachingProvider
- CacheManage定义了创建、配置、获取、管理和控制多个惟一命名的Cache,这些Cache存在CacheManager的上下文中。一个CacheManage仅被一个CachheProvider所拥有
- Cache是一个类似Map的数据结构并临时储存以key为索引的值。一个Cache仅被一个CacheManager所拥有
- Entry是一个存储在Cache中的key—value对
- Enpiry是每一个储存在Cache中的条目有一个定义的有效期。一旦超过这个歌时间,条目为过期状态。一旦过期,条目将不可访问、更新、删除。存储有效期可以通过ExpiryPolicy设置
添加依赖
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
spring 缓存抽象
常用的缓存注解
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
- @EnableCaching 开启基于注解的缓存
@ComponentScan({"com.zzy.demo.dao"})
@SpringBootApplication
@EnableCaching//开启缓存
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
-
Cache 缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache等
-
CacheManager 缓存管理器,管理各种缓存(Cache)组件
-
/** * @Cacheable将方法的运行结果进行缓存,以后再要相同的数据,直接从缓存中获取,不要调用方法 * 属性: * cacheNames/value 指定缓存组件的名字 也就是使用一张表用来储存特定的 数据 * key 缓存数据使用的key 可以用它来指定 默认是方法参数的值 因为Cache是以map的数据结构来储存的所以要指定key值 形参-方法的返回值 * keyGenerator key的默认生成器 可以自己指定key的生成器 * cacheManager 指定缓存管理器 * condition 指定符和条件的情况下才进行缓存 * unless 否定缓存 当unless指定的条件为 true 方法的返回值就不会被缓存 * sync 是否使用异步模式 * @return */ @Override @Cacheable(cacheNames = "book" ,key="#id",keyGenerator = "myKeyGenerator")//指定自定义的key生成器 public List<Book> selectBook() { List<Book> bookList = bookMapper.selectByExample(bookExample); return bookList; } }
//自己指定key值生成器 @Configuration public class MyConfiguration extends WebMvcAutoConfiguration { @Bean("myKeyGenerator") public KeyGenerator myKeyGenerator(){ return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { int i = 0; return method.getName()+"zzy"+i++; } }; } }
-
@Cacheevict 清空缓存 缓存清除
/**
* value 指定表
* key 指定删除的key键值对
* allEntries 是否删除缓存中的所有数据 默认是false 不删除
* beforeInvocation = false 指定缓存的清除是否在方法之前清除 默认在方法之后执行清除 可以防止异常的抛出 事务
* @param id
* @return
*/
@Cacheevict(value = "book",key = "#id")
public Integer delBook(Integer id){
Integer i = bookMapper.deleteByPrimaryKey(id);
return i;
}
/**
* @Cache 和 @Cacheable 前者是先调用目标方法 再将目标方法的结果返回回来
* 注意: @Cache 方法会自动更新数据库和缓存库中的数据 但是要注意的是 map数据结构的特性是key值覆盖 所以它们的key值要是一样的 要专门指定key的值和存入时的key值相等
注意 关于#result的取值 @Cacheable 注解的返回值是在方法运行之前的 而 @CachePut 的返回值是在方法运行之后的
* @param book
* @return
*/
@CachePut(value = "book",key = "#Book.id")//key="#result.id"
public Integer selectBook(Book book) {
Integer bookList = bookMapper.updateByPrimaryKey(book);
return bookList;
}
}
- @Caching 混合注解 高级 可以一次缓存多个key值查询
@Caching(
cacheable = {
@Cacheable(value = "book",key = "id")
},
put = {
@CachePut(value = "book" , key = "name"),
@CachePut(value = "book",key = "wirte")
}
)
public Book select(Integer id){
Book book = bookMapper.selectByPrimaryKey(id);
return book;
}
@CacheConfig(cacheNames = "book")
public class BookServiceImpl implements BookService {
- keyGenerator 缓存数据是key的 生成策略
- serialize 缓存数据时value序列化策略
搭建Redis环境
Redis的安装(docker):
- 下载相关镜像 docker pull registry.docker-cn.com/library/Redis 使用中国镜像下载
- 启动容器
docker run -d -p 6379:6379 --name myredis redis
Redistemplate 和 StringRedistemplate 的使用 序列化的更改
引入Redis的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
配置redis
spring:
redis:
host: 192.168.11.xxx
一但redis成功引入 springboot自动配置起效 会帮助我产生两个bean对象 StringRedistemplate 和 Redistemplate 对象用来简化操作redis的
StringRedistemplate:专门操作字符串
RedsiTemplate:专门操作对象
设置自定义序列化器 更改默认的JdkSerializationRedisSerializer 序列化器 这样传出的值就是json了
@Bean
public Redistemplate<Object,Object> redistemplate(){
Redistemplate<Object,Object> template = new Redistemplate<>();
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(serializer);
return template;
}
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){
RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(redisConnectionFactory);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,redisCacheConfiguration);
return redisCacheManager;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。