Spring Cache+Redis缓存数据 您所在的位置:网站首页 民族资产阶级啥时候结束 Spring Cache+Redis缓存数据

Spring Cache+Redis缓存数据

#Spring Cache+Redis缓存数据 | 来源: 网络整理| 查看: 265

1、为什么使用缓存

我们知道内存的读取速度远大于硬盘的读取速度。当需要重复地获取相同数据时,一次一次地请求数据库或者远程服务,导致在数据库查询或远程方法调用上消耗大量的时间,最终导致程序性能降低,这就是数据缓存要解决的问题。

spring Cache 是一个非常优秀的缓存组件。自Spring 3.1起,提供了类似于@Transactional注解事务的注解Cache支持,且提供了Cache抽象,方便切换各种底层Cache(如:Redis

使用Spring Cache的好处

1,提供基本的Cache抽象,方便切换各种底层Cache;

2,通过注解Cache可以实现类似于事务一样,缓存逻辑透明的应用到我们的业务代码上,且只需要更少的代码就可以完成;

3,提供事务回滚时也自动回滚缓存;

4,支持比较复杂的缓存逻辑;

一旦配置好Spring缓存支持,就可以在Spring容器里管理的Bean中使用缓存注解(基于AOP原理),一般情况下,都是在业务层(Service类)使用这些注解。

2、常用的缓存注解 2.1 @Cacheable

@Cacheable可以标记在一个方法上,也可以标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的;当标记在一个类上时则表示该类所有的方法都是支持缓存的。对于一个支持缓存的方法,在方法执行前,Spring先检查缓存中是否存在该方法返回的数据,如果存在,则直接返回缓存数据;如果不存在,则调用方法并将方法返回值写入缓存。

@Cacheable注解经常使用value、key、condition等属性

value:缓存的名称,指定一个或多个缓存名称。如

 @Cacheable(value="mycache")或者@Cacheable(value={"cache1","cache2"})

该属性与cacheNames属性意义相同

key:缓存的key,可以为空。如果指定。需要按照SpEL编写;如果不指定,则默认按照方法的所有参数进行组合。如

 @Cacheable(value="testcache",key="#student.id")

condition:缓存的条件,可以为空,如果指定,需要按照SpEL编写,返回true或者false,只有为true才进行缓存。如

 @Cacheable(value="testcache",condition="#student.id>2")

该属性与unless相反,条件成立时,不进行缓存

2.2 @CacheEvict

一般用在更新或者删除方法上

@CacheEvict是用来标注在需要清除 缓存元素的方法或类上的。当标记在一个类上时,表示其中所有方法的执行都会触发缓存的清除操作。@CacheEvict可以指定的属性有value、key、conditon、allEntries和beforeInvocation。其中,value、key和condition的语义与@Cacheable对应的属性类似。

allEntries:是否清空所有缓存内容,默认为false,如果指定为true,则方法调用后将立即清空所有缓存。如

 @CacheEvict(value="testcache",allEntries=true)

beforeInvocation:是否在方法执行前就清空,默认为false,如果指定为true,则在方法还没有执行时就清空缓存。默认情况下,如果方法执行抛出异常,则不会清空缓存。

2.3、@Cacheput

使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。其他方法可以直接从响应的缓存中读取缓存数据,而不需要再去查询数据库。一般用在新增方法上。

2.4、@Caching

该注解可以在一个方法或类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。示例代码如下:

 @Caching( cacheable=@Cacheable("cache1"), evict={@CacheEvict("cache2"),@CacheEvict(value="cache3",allEntries=true)} ) 2.5、@CacheConfig

所有的Cache注解都需要提供Cache名称,如果每个Service方法上都包含相同的Cache名称,可能写起来重复。此时可以使用@CacheConfig注解作用在类上,设置当前缓存的一些公共配置。

3、springboot缓存支持

在SpringBoot应用中,使用缓存技术只需在应用中引入相关缓存技术的依赖,并在配置类中使用@EnableCaching注解开启缓存支持即可。

4、项目继承Spring Cache+Redis 4.1 添加依赖                         org.springframework.boot             spring-boot-starter-data-redis                                         org.apache.commons             commons-pool2             2.6.0          4.2 配置类   /**  * Redis+Cache配置类  */ @Configuration @EnableCaching public class RedisConfig {     /**      * 自定义key规则      * @return      */     @Bean     public KeyGenerator keyGenerator() {         return new KeyGenerator() {             @Override             public Object generate(Object target, Method method, Object... params) {                 StringBuilder sb = new StringBuilder();                 sb.append(target.getClass().getName());                 sb.append(method.getName());                 for (Object obj : params) {                     sb.append(obj.toString());                }                 return sb.toString();            }        };    }      /**      * 设置RedisTemplate规则      * @param redisConnectionFactory      * @return      */     @Bean     public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {         RedisTemplate redisTemplate = new RedisTemplate();         redisTemplate.setConnectionFactory(redisConnectionFactory);         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);          //解决查询缓存转换异常的问题         ObjectMapper om = new ObjectMapper();         // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);         // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);         jackson2JsonRedisSerializer.setObjectMapper(om);          //序列号key value         redisTemplate.setKeySerializer(new StringRedisSerializer());         redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);         redisTemplate.setHashKeySerializer(new StringRedisSerializer());         redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);          redisTemplate.afterPropertiesSet();         return redisTemplate;    }      /**      * 设置CacheManager缓存规则      * @param factory      * @return      */     @Bean     public CacheManager cacheManager(RedisConnectionFactory factory) {         RedisSerializer redisSerializer = new StringRedisSerializer();         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);          //解决查询缓存转换异常的问题         ObjectMapper om = new ObjectMapper();         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);         jackson2JsonRedisSerializer.setObjectMapper(om);          // 配置序列化(解决乱码的问题),过期时间600秒         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()                .entryTtl(Duration.ofSeconds(600))                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))                .disableCachingNullValues();          RedisCacheManager cacheManager = RedisCacheManager.builder(factory)                .cacheDefaults(config)                .build();         return cacheManager;    }  } 4.3 添加redis配置  # redis配置 spring.redis.host=192.168.159.33 spring.redis.port=6379 spring.redis.database= 0 spring.redis.timeout=1800000  spring.redis.lettuce.pool.max-active=20 spring.redis.lettuce.pool.max-wait=-1 #最大阻塞等待时间(负数表示没限制) spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0 4.4 接口中使用缓存注解

Service实现类中

 @Service public class DictServiceImpl extends ServiceImpl implements DictService {      //根据上级id查询子数据列表     @Override     @Cacheable(value = "dict",keyGenerator = "keyGenerator")     public List findChildData(Long id) {         QueryWrapper wrapper=new QueryWrapper();         wrapper.eq("parent_id",id);         List list = baseMapper.selectList(wrapper);         //向list集合中的每个dict对象中设置hasChildren         list.forEach(x->{             Long dictId = x.getId();             boolean isChild = this.isChildren(dictId);             x.setHasChildren(isChild);        });         return list;    }      //导出数据字典接口     @Override     public void exportDictData(HttpServletResponse response) {         //设置下载信息         response.setContentType("application/vnd.ms-excel");         response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系         String fileName = "dict";         response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");          //查询数据库         List dictList = baseMapper.selectList(null);         //Dict-->DictEeVo         List dictEeVoList=new ArrayList();         dictList.forEach(x->{             DictEeVo dictEeVo=new DictEeVo();             BeanUtils.copyProperties(x,dictEeVo);             dictEeVoList.add(dictEeVo);        });          try {             //调用方法实现写操作             EasyExcel.write(response.getOutputStream(), DictEeVo.class)                    .sheet("dict")                    .doWrite(dictEeVoList);        } catch (IOException e) {             e.printStackTrace();        }      }      //导入数据字典     @Override     @CacheEvict(value = "dict", allEntries=true)     public void importDictData(MultipartFile file) {         try {             //excel数据取出来并添加到数据库中             EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper))            .sheet()            .doRead();        } catch (IOException e) {             e.printStackTrace();        }    }      //判断id下面是否有子数据     private boolean isChildren(Long id){         QueryWrapper wrapper=new QueryWrapper();         wrapper.eq("parent_id",id);         Integer count = baseMapper.selectCount(wrapper);         return count > 0;    } } 4.5 缓存效果测试

我们现在调用根据上级id查询子数据列表这个方法的controller

第一次访问接口

Spring Cache+Redis缓存数据

查看控制台:

Spring Cache+Redis缓存数据

查看redis中是否有缓存的数据

Spring Cache+Redis缓存数据

用连接工具查看下redis中的数据,方便数据的可视化

Spring Cache+Redis缓存数据

从上面的数据不难发现,数据已经被缓存到了redis中

清空SpringBoot的控制台,再次发起相同的请求,看是否会再次请求数据库

第二次请求的控制台输出如下:

Spring Cache+Redis缓存数据

页面中的数据也正常获取到了,如下:

Spring Cache+Redis缓存数据

从上面的效果可以很明显的看到,我们第一次请求后端接口的时候,由于缓存中并没有需要的数据,所以会被缓存到redis中,第二次请求相同接口的时候,Spring先检查缓存中是否存在该方法返回的数据,如果存在,则直接返回缓存数据,减小对数据库查询的压力。

原文始发于微信公众号(全栈开发那些事):Spring Cache+Redis缓存数据

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/91835.html



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有