SpringBoot2.x版本整合Redis进行数据缓存

项目放在github:

在缓存开发中,有两个重要的接口:

在这里面:

    @Cacheable:    如果用这个注解标注在方法上,那么方法的结果就会被缓存存起来,这个多用于在查询的时候进行使用

     比如: public user getuser(Integer id) 这个方法用这个注解标注的话,通过id查到的内容就会杯存在缓存中进行保存,如果下次在进行查同样id的信息的话,直接从缓存中进行调取就行了,大大减少了大系统的数据库的负担

    @CacheEvict:  如果用这个注解标注在方法的话,就会把对应的缓存进行删除,这个注解多用于再删除的模块上,再删除数据的时候,将对应的缓存也进行删除

    @CachePut:    更新缓存,在更新的时候,多用到

    比如:public User updadeuer(User user)这样的方法,就是将之前的信息进行修改,并且进行提交,这个缓存机制也是,在更新之后,将缓存的数据信息也进行更新

    @EnableCacheing:要想使用注解,就得启用注解的模式,并且还有key,和value的的对应关系问题

在我们进行缓存项目创建的时候,我们要选中cache的缓存模块,将自动导入我们想要的缓存的依赖

并且要导入redis的依赖,才能使用,否则会报错:

1<dependency> 2  <groupId>org.springframework.boot</groupId> 3  <artifactId>spring-boot-starter-data-redis</artifactId> 4</dependency> 5<dependency> 6  <groupId>org.springframework.boot</groupId> 7  <artifactId>spring-boot-starter-cache</artifactId> 8</dependency> 9<dependency> 10  <groupId>org.apache.commons</groupId> 11  <artifactId>commons-pool2</artifactId> 12</dependency>

在@Cache中有几个重要的属性:

cacheName/value:指定缓存组件的名称,这个就是将缓存进行存取的时候的名称,将方法的返回结果放在缓存中,可以制定多个缓存(是数组的形式)。

key:如果不指定的话,系统默认的就是我们的方法传递的参数:

例如;

1@Cacheable(cacheNames = {"emp"}) 2public Employee getEmp(Integer id){ 3  System.out.println("查询"+id+"号员工信息"); 4  Employee emp = employeeMapper.getEmpById(id); 5  return emp; 6}

这种不进行指定的话,我们的key默认就是“2”

我们也可以自己进行指定:

1、利用key进行自定义生成

    key="root.methodName"+'['+#id+']'"

    这种形式生成的key就是getEmp【2】,   root.methodName就是获取方法的名称

2、可以自定义keygenerator,按照自己生成器进行生成我们想要的key

    

1 @Bean 2 public KeyGenerator keyGenerator(){ 3// return (o, method, params) ->{ 4// StringBuilder sb = new StringBuilder(); 5//// sb.append(o.getClass().getName()); // 类目 6//// sb.append(method.getName()); // 方法名 7// for(Object param: params){ 8// sb.append(param.toString()); // 参数名 9// } 10// return sb.toString(); 11// }; 12 return new KeyGenerator() { 13 @Override 14 public Object generate(Object o, Method method, Object... objects) { 15 return Arrays.asList(objects).toString(); 16 } 17 }; 18 }

并且在service上用@Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator")进行keygenerator的自定义器的使用

condition:做判断,例如一号员工做缓存,二号员工不做缓存:

    @Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator",condition = "#id>1" and....)

这种就是判断在id>1的情况下,才会进行缓存生效,否则不生效

unless:是在条件成立的时候,不进行缓存,unless="#a0==2"",这种情况就是在id为2的情况下,不进行缓存,a0就是第一个参数的意思,也就是这里的id

@CachePut(更新数据信息,更新缓存的注解)

这种方法多用在更新信息的情况下进行使用

例如:

1@CachePut(cacheNames = {"emp"},key = "#employee.id") 2public Employee updateEmp(Employee employee){ 3  System.out.println("修改"+employee.getId()+"号员工信息"); 4  employeeMapper.updateEmp(employee); 5  return employee; 6}

/*

* @CachePut:既调用方法,又更新缓存信息

* 运行时机:

* 1、先调用目标方法

* 2、将目标方法的结果缓存起来

* (这里需要注意的是,在更新缓存数据信息的时候,因为我们的key是不同的,前面默认的是id=xx,这里用的是employee,

* 所以需要将key进行统一,这样才能更新缓存的数据信息)

*

* */

这里就是要注意将我们更新的缓存的key和前面缓存的信息的key要保持一致,否则不能进行缓存的修改

@CacheEvict:在进行缓存的删除时候,也要指定对应的value和key,这样才能删除对应的缓存信息

1@CacheEvict(value = {"emp"},key = "#id",allEntries = false,beforeInvocation = false) 2public void deleteEmp(Integer id){ 3 System.out.println("删除"+id+"号员工信息"); 4 employeeMapper.deleteEmp(id); 5}

其中的allEntries默认为false,如果改成true,那么emp中所有的缓存信息都会被清空

beforeInvocation = false,这个默认也是false,是指定是不是在方法运行之后进行缓存的清除

也可以在最上面加上CacheConfig,这个就是在上面抽取缓存的共同配置,如cacheName等等

然后就是在application.properties或者是application.yml文件中配置我们的redis的相关配置:

#配置redis

1redis: 2host: 192.168.43.197 3port: 6379 4database: 0

这些是最基本的一些配置,其余的配置可在官网进行查询得知:

redis是安装在虚拟机docker里面的,在本地安装上redisdesktop可以操作虚拟机里面的redis。

SpringBoot从1.x升级到2.x的redis进行了改革换代,前面的东西和后面的东西差距太大,这里操作2。x版本的SpringBoot需要进行相关的序列化的配置,自己编写config文件进行相关的序列化的操作,config文件代码:

1package com.example.cache.config; 2import org.slf4j.Logger; 3import org.slf4j.LoggerFactory; 4import org.springframework.cache.annotation.CachingConfigurerSupport; 5import org.springframework.cache.annotation.EnableCaching; 6import org.springframework.cache.interceptor.KeyGenerator; 7import org.springframework.context.annotation.Bean; 8import org.springframework.context.annotation.Configuration; 9import org.springframework.data.redis.cache.RedisCacheConfiguration; 10import org.springframework.data.redis.cache.RedisCacheManager; 11import org.springframework.data.redis.connection.RedisConnectionFactory; 12import org.springframework.data.redis.serializer.*; 13 14import java.lang.reflect.Method; 15import java.time.Duration; 16import java.util.Arrays; 17 18/* 19 * Redis中常见的五种数据类型 20 * String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合) 21 * 22 * */ 23@Configuration 24@EnableCaching 25public class RedisCacheConfig extends CachingConfigurerSupport{ 26 private static final Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class); 27 // 自定义key生成器 28 @Bean 29 public KeyGenerator keyGenerator(){ 30// return (o, method, params) ->{ 31// StringBuilder sb = new StringBuilder(); 32//// sb.append(o.getClass().getName()); // 类目 33//// sb.append(method.getName()); // 方法名 34// for(Object param: params){ 35// sb.append(param.toString()); // 参数名 36// } 37// return sb.toString(); 38// }; 39 return new KeyGenerator() { 40 @Override 41 public Object generate(Object o, Method method, Object... objects) { 42 return Arrays.asList(objects).toString(); 43 } 44 }; 45 } 46 47 // 配置缓存管理器 48 @Bean 49 public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { 50 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() 51 .entryTtl(Duration.ofSeconds(600000)) // 60s缓存失效 52 // 设置key的序列化方式 53 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) 54 // 设置value的序列化方式 55 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer())) 56 // 不缓存null值 57 .disableCachingNullValues(); 58 59 RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory) 60 .cacheDefaults(config) 61 .transactionAware() 62 .build(); 63 64 logger.info("自定义RedisCacheManager加载完成"); 65 return redisCacheManager; 66 } 67 /* @Bean 68 public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){ 69 RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); 70 redisTemplate.setConnectionFactory(connectionFactory); 71 redisTemplate.setKeySerializer(keySerializer()); 72 redisTemplate.setHashKeySerializer(keySerializer()); 73 redisTemplate.setValueSerializer(valueSerializer()); 74 redisTemplate.setHashValueSerializer(valueSerializer()); 75 logger.info("序列化完成!"); 76 return redisTemplate; 77 }*/ 78 79 // key键序列化方式 80 private RedisSerializer<String> keySerializer() { 81 return new StringRedisSerializer(); 82 } 83 84 // value值序列化方式 85 private GenericJackson2JsonRedisSerializer valueSerializer(){ 86 return new GenericJackson2JsonRedisSerializer(); 87 } 88}

然后再我们的service中进行相关的增删改查的时候,就可以加上缓存注解,进行操作redis的缓存数据库

1package com.example.cache.service; 2 3import com.example.cache.bean.Employee; 4import com.example.cache.mapper.EmployeeMapper; 5import org.springframework.beans.factory.annotation.Autowired; 6import org.springframework.cache.annotation.CacheEvict; 7import org.springframework.cache.annotation.CachePut; 8import org.springframework.cache.annotation.Cacheable; 9import org.springframework.stereotype.Service; 10 11@Service 12public class EmployeeService { 13 @Autowired 14 EmployeeMapper employeeMapper; 15 //查询员工信息 16 /* 17 *@Cacheable 18 * 开启缓存,将方法的运行结果缓存起来,下次在相同的查询,就在缓存中查询 19 * CacheManager管理多个Cache组件,每一个缓存组件都有自己唯一的名称 20 * 几个属性: 21 * cacheName/value:指定缓存组件的名称 22 * key:缓存数据用的值,可以用它来指定,默认是使用方法参数的值,1-方法的返回值 23 * keyGenerator:主键生成器,也可以自己指定主键生成器 24 * key/keyGenerator二选一使用 25 * cacheManager:缓存管理器 26 * cacheResolver:缓存解析器 27 * cacheManager/cacheResolver二选一 28 * condition:指定符合条件的情况下,才进行缓存 29 * 可以进行指定条件 30 * unless:否定缓存,当unless指定的条件为true时候,方法的缓存不会被缓存 31 * sync:异步模式:指定是否使用异步模式 32 * */ 33 @Cacheable(cacheNames = {"emp"}) 34// ,keyGenerator = "myKeyGenerator",condition = "#id>1" ,unless="#a0==2" 35 public Employee getEmp(String lastname){ 36 System.out.println("查询"+lastname+"号员工信息"); 37 Employee emp = employeeMapper.getEmpByName(lastname); 38 return emp; 39 } 40 41 //删除员工信息 42 /* 43 *@CacheEvict:清除注解,将缓存里面的信息进行清除 44 *,allEntries = false, 45 * beforeInvocation = false 46 */ 47 @CacheEvict(value = {"emp"},key = "'['+#lastname+']'") 48 public void deleteEmp(String lastname){ 49 System.out.println("删除"+lastname+"员工信息"); 50 employeeMapper.deleteEmp(lastname); 51 } 52 //增加员工信息,这里不做缓存 53// @CacheEvict(value = {"emp"},key = "'['+#employee.getLastName()+']'") 54 public void insertEmp(Employee employee){ 55 System.out.println("增加新的员工信息"); 56 employeeMapper.insertEmp(employee); 57 } 58 //修改员工信息 59 /* 60 * @CachePut:既调用方法,又更新缓存信息 61 * 运行时机: 62 * 1、先调用目标方法 63 * 2、将目标方法的结果缓存起来 64 * (这里需要注意的是,在更新缓存数据信息的时候,因为我们的key是不同的,前面默认的是id=xx,这里用的是employee, 65 * 所以需要将key进行统一,这样才能更新缓存的数据信息) 66 * 67 * */ 68 @CachePut(cacheNames = {"emp"},key = "'['+#employee.getLastName()+']'") 69 public Employee updateEmp(Employee employee){ 70 System.out.println("修改"+employee.getLastName()+"员工信息"); 71 employeeMapper.updateEmp(employee); 72 return employee; 73 } 74}

这样,redis的缓存数据库就配置好了

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

SpringBoot2.x版本整合Redis进行数据缓存 - HelloWorld