SpringBoot引入Redis
目录
1 准备redis
1.1 docker安装redis(centos7上安装)
1.2 启动redis
2 SpringBoot与缓存
2.1 JSR107缓存规范
2.2 Spring缓存抽象
2.3 概念&缓存注解
3 SpringBoot(2.0.3.RELEASE)+Redis项目测试准备
3.1 主要pom依赖
3.2 yml文件配置
3.3 数据库测试表
4 Redis测试
4.1 @Cacheable注解
4.2 @CachePut注解
4.3 @CacheEvict注解
4.4 @Caching注解
5 SpringBoot Redis缓存序列化处理
6 总结
1 准备redis
1.1 docker安装redis(centos7上安装)
docker pull redis
查看镜像是否下载成功:docker images
1.2 启动redis
docker run -d -p 6379:6379 --name myredis docker.io/redis
-d:表示后台启动
-p:表示端口,6379:6379表示将 虚拟机的6379端口映射为容器的6379端口
--name myredis docker.io/redis:命名,将要启动的docker.io/redis命名为myredis
查看是否启动成功:docker ps
2 SpringBoot与缓存
2.1 JSR107缓存规范
Java Caching定义了5个核心接口,分别是CachingProvider、CacheManager、Cache、Entry、Expiry。
a)CachingProvider定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可以在运行期访问多个CachingProvider。
b)CacheManager定义了创建、配置、获取、管理和控制多个唯一命名的Cache,这些Cache存在于CacheManager的上下文中。一个CacheManager仅被一个CachingProvider所拥有。
c)Cache是一个类似Map的数据结构并临时存储以Key为索引的值。一个Cache仅被一个CacheManager所拥有。
d)Entry是一个存储在Cache中的key-value对。
e)Expiry 每一个存储在Cache中的条目有一个定义的有效期。一旦超过这个时间,条目为过期的状态。一旦过期,条目将不可访问、更新和删除。缓存有效期可以通过ExpiryPolicy设置。
2.2 Spring缓存抽象
Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache(JSR-107)注解简化开发。
Cache接口为缓存的组件规范定义,包含缓存的各种操作集合。
Cache接口下Spring提供了各种xxxCache的实现;如RedisCache、EhCacheCache 、JCacheCache、ConcurrentMapCache...
每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户,下次调用直接从缓存中获取。
使用Spring缓存抽象时我们需要关注两点:确定方法需要被缓存以及他们的缓存策略、从缓存中读取之前缓存存储的数据。
2.3 概念&缓存注解
Cache:缓存接口,定义缓存操作,实现有RedisCache、EhCacheCache、JCacheCache、ConcurrentMapCache等。
CacheManager:缓存管理器,管理各种缓存组件。
keyGenerator:缓存数据时key的生成策略。
serialize:缓存数据时value序列化策略。
@EnableCaching:开启基于注解的缓存。
@CacheConfig:可以抽取缓存公共配置,标注在类上。
@Cacheable:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存。
@CachePut:保证方法被调用,又希望结果被缓存。(更新操作)
@CacheEvict:清空缓存。(删除操作)
@Caching:组合注解,可根据需要配置多个@Cacheable、@CachePut、@CacheEvict注解。
@Cacheable/@CachePut/@CacheEvict主要的参数如下:
3 SpringBoot(2.0.3.RELEASE)+Redis项目测试准备
3.1 主要pom依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--数据库相关--><!--mybatis-spring-boot-starter,mybatis依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
3.2 yml文件配置
spring:redis:host: 192.168.219.141 # redis服务器地址port: 6379 # 默认端口就是6379 可不配置#password: root # redis服务器连接密码(默认为空)database: 0 #使用Redis0号库jedis:pool:max-active: 8 # 连接池最大连接数(如果配置为<=0,则没有限制)datasource:url: jdbc:mysql://127.0.0.1:3306/spring_cache?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghaiusername: rootpassword: root
mybatis:configuration:map-underscore-to-camel-case: true
logging:level:com:cache:mapper: DEBUG
3.3 数据库测试表
CREATE TABLE `employee` (`id` INT(11) NOT NULL AUTO_INCREMENT,`lastName` VARCHAR(255) DEFAULT NULL,`email` VARCHAR(255) DEFAULT NULL,`gender` INT(2) DEFAULT NULL,`d_id` INT(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
三条测试数据:
4 Redis测试
4.1 @Cacheable注解
@Cacheable(cacheNames = "emp", key = "#id")// @Cacheable(cacheNames = "emp", key = "#id",condition = "#id > 1")//@Cacheable(cacheNames = "emp", key = "#id",unless = "#result == null")public Employee getEmp(Integer id) {System.out.println("查询" + id + "号员工");return employeeMapper.getEmpById(id);}
说明:
@Cacheable(cacheNames = "emp", key = "#id"):将查询到的Employee存入缓存,key就是传入的id。
@Cacheable(cacheNames = "emp", key = "#id",condition = "#id > 1"):condition为缓存的条件,当condition 判断为true时,缓存结果,即当员工的id大于1时,才会缓存对应的结果。condition在方法执行之前之后都可以进行判断。
@Cacheable(cacheNames = "emp", key = "#id",unless = "#result == null"):unless用于否决缓存,只有当条件为false时才会缓存。并且,该表达式只在方法执行之后判断。经过测试,默认就算不设置unless 条件,结果为null也是不允许缓存的。
4.2 @CachePut注解
@CachePut(value = "emp", key = "#result.id") //返回结果中的ID// @CachePut(value = "emp",key="#employee.id") //参数中的IDpublic Employee updateEmp(Employee employee) {System.out.println("employee:" + employee);employeeMapper.update(employee);return employeeMapper.getEmpById(employee.getId());}
说明:
第一种方式,将结果中的ID作为key。先缓存3号员工信息,窄将3号员工Eric的lastname改为Andy,以下分别为更新前和更新后的缓存。
第二种方式是将参数中的ID作为key,测试发现最终的效果是一样的,更新员工后,缓存也更新了。
4.3 @CacheEvict注解
// key 清除指定的数据// beforeInvocation默认为false,方法执行之后再删除缓存;// beforeInvocation为true:方法执行之前删除缓存,不管方法成不成功@CacheEvict(value = "emp", key = "#id",beforeInvocation = false)//allEntries默认为false,当为true,那么emp缓存全部删除// @CacheEvict(value = "emp",allEntries = true,beforeInvocation = false)public Integer deleteEmp(Integer id) {Integer result = employeeMapper.deleEmpById(id);System.out.println("删除" + id + "号员工");return result;}
说明:
@CacheEvict主要就是两个配置比较重要。 beforeInvocation默认为false,方法执行之后再删除缓存;beforeInvocation为true,方法执行之前删除缓存,不管方法成不成功。
allEntries默认为false,当为true,那么对应的缓存全部删除。
4.4 @Caching注解
// 组合注解@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) {Employee employee = employeeMapper.getByLastname(lastName);System.out.println("通过lastname查询");return employee;}
说明:
@Caching源码如下:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Caching {Cacheable[] cacheable() default {};CachePut[] put() default {};CacheEvict[] evict() default {};
}
@Caching是个组合注解,可以通过这个注解来配置不同的缓存,比如示例代码中,通过lastname查询,可以根据查询结果设置不同的缓存,也可以根据查询结果更新缓存,按自己的需要进行组合配置。
通过lastname=Andy查询,通过结果可以发现@Caching生效了。
5 SpringBoot Redis缓存序列化处理
SpringBoot RedisTemplate是用来操作key-value对象类型,默认采用JDK序列化类型。JDK序列化性能差,而且数据是以二进制的形式(如下图所示)存储在Redis服务端,不便于查询,同时对象还需要实现Serializable接口。
如果要直接查看缓存数据,会比较困难,我们更希望数据以json的形式存储。
RedisSerializer有很多种实现,默认是使用的Jdk序列化方式,那么可以通过使用Jackson2JsonRedisSerializer来实现新的序列化。
更改默认的序列化器:
@Configuration
@EnableCaching
public class CacheConfig {@Beanpublic CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {RedisCacheManager redisCacheManager =RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(defaultCacheConfig(10000)).withInitialCacheConfigurations(initCacheConfigMap()).transactionAware().build();return redisCacheManager;}private RedisCacheConfiguration defaultCacheConfig(Integer second) {Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer= new Jackson2JsonRedisSerializer<Object>(Object.class);ObjectMapper objectMapper = new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objectMapper);RedisCacheConfiguration redisCacheConfiguration= RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(second)).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).disableCachingNullValues();return redisCacheConfiguration;}// 不同缓存的过期时间,可以自定义配置private Map<String, RedisCacheConfiguration> initCacheConfigMap() {Map<String, RedisCacheConfiguration> configMap = new HashMap<>();// 自己按需配置configMap.put("User", this.defaultCacheConfig(1000));configMap.put("User1", this.defaultCacheConfig(1000));configMap.put("User2", this.defaultCacheConfig(1000));configMap.put("User3", this.defaultCacheConfig(1000));return configMap;}
}
6 总结
坚持写博客!坚持写博客!坚持写博客!(其实已经很久没有写了)
SpringBoot引入Redis相关推荐
- springboot引入Redis配置JedisPool连接池
目录 一.pom.xml依赖 二.application.properties配置 三.java配置类 四.单元测试 一.pom.xml依赖 <dependency><groupId ...
- SpringBoot第九篇: springboot整合Redis
这篇文章主要介绍springboot整合redis,至于没有接触过redis的同学可以看下这篇文章:5分钟带你入门Redis. 引入依赖: 在pom文件中添加redis依赖: <dependen ...
- springboot配置Redis哨兵主从服务 以及 Redis 集群
redis哨兵集群配置 Sentinel(哨兵)是Redis 的高可用性解决方案:由一个或多个Sentinel 实例 组成的Sentinel 系统可以监视任意多个主服务器,以及这些主服务器属下的所有从 ...
- (转)SpringBoot系列—Redis使用
http://blog.csdn.net/jeofey/article/details/73468192 SpringBoot对Redis的支持是通过spring Data redis 来时闲的,使用 ...
- Springboot整合redis(lettuce)
springboot 整合redis(lettuce) 首先确保电脑上装了redis.最好能用redisDesktop查看一下数据情况 redis是一款非常流行的Nosql数据库.redis的功能非常 ...
- redis 依赖_springboot|springboot集成redis缓存
javaDEMO 本网站记录了最全的各种JavaDEMO ,保证下载,复制就是可用的,包括基础的, 集合的, spring的, Mybatis的等等各种,助力你从菜鸟到大牛,记得收藏哦~~https: ...
- 【Java进阶】SpringBoot整合Redis
SpringBoot整合Redis SpringBoot 操作数据:spring-data jpa jdbc mongodb redis SpringData 也是和 SpringBoot 齐名的项目 ...
- (入门SpringBoot)SpringBoot结合redis(四)
SpringBoot整合redis: 1.引入jar <!-- 引入redis依赖 --><dependency> <groupId>org.spring ...
- springboot data.redis.RedisConnectionFactory 集成问题
springboot 集成springboot data redis出错: org.springframework.beans.factory.NoSuchBeanDefinitionExceptio ...
- SpringBoot集成Redis用法笔记
今天给大家整理一下SpringBoot集成Redis用法笔记,希望对大家能有所帮助! 一.Redis优点介绍 1.速度快 不需要等待磁盘的IO,在内存之间进行的数据存储和查询,速度非常快.当然,缓存的 ...
最新文章
- java8 group by_java8新特性Java 8 – Stream Collectors groupingBy 示例 - Java教程
- C++ auto 关键字的使用
- 【android】【转】class android.media.MediaPlayer
- OC中使用 static 、 extern、 const使用
- 福师离线 微型计算机与外部,福师《计算机应用基础》离线作业答案
- 提示illegal reference to data member'CPMAgentManageDlg::m_matrixMatrixSt'in a static member function
- Java SE 基础:继承、封装、多态、fianl、static、abstract
- Android Toast的时长
- java基础中的基础,简单中的简单
- 配置的代理服务器未响应解决方法
- Java调用支付宝身份认证接口
- 2019最新升级全能版vbox硬件级虚拟机系统 vm去虚拟化修改信息工具 批量启动克隆 virtualbox CPA网赚挂机电商
- Java面试宝典之:基础篇
- 柔性电子:大面积全纺织压力传感器用于检测人类移动和物理信号
- 网页地址栏ico图标设置
- 如何下载淘宝视频-淘宝视频下载详细以及注意
- Kotlin | 委托(Delegation )详解
- win7 如何设置快速启动栏
- 驱动开发人员不足?经验不够?一招教你立即摆平!
- 使用实例展示Express框架app函数的详解