SpringBoot集成redis + spring cache

Spring Cache集成redis的运行原理:

Spring缓存抽象模块通过CacheManager来创建、管理实际缓存组件,当SpringBoot应用程序引入spring-boot-starter-data-redi依赖后吗,容器中将注册的是CacheManager实例RedisCacheManager对象,RedisCacheManager来负责创建RedisCache作为缓存管理组件,由RedisCache操作redis服务器实现缓存数据操作。实际测试发现默认注入的RedisCacheManager操作缓存用的是RedisTemplate<Object, Object>,因此我们需要自定义cacheManager,替换掉默认的序列化器。

实现代码:

添加mybatis和redis依赖:

复制代码

1<dependency> 2 <groupId>org.mybatis.spring.boot</groupId> 3 <artifactId>mybatis-spring-boot-starter</artifactId> 4 <version>1.3.2</version> 5</dependency> 6<dependency> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-data-redis</artifactId> 9</dependency>

复制代码

添加mapper映射:

复制代码

11 @Mapper 2 2 public interface ProductMapper { 3 3 @Select("select * from tb_product where product_id=#{id}") 4 4 Product getProductById(Long id); 5 5 6 6 @Update("update tb_product set product_name=#{productName},product_desc=#{productDesc} WHERE product_id=#{productId}") 7 7 int updateProduct(Product product); 8 8 9 9 @Delete("delete from tb_product where product_id=#{id}") 1010 void deleteProductById(Long id); 1111 1212 @Select("select * from tb_product where product_name=#{productName}") 1313 Product getProductByName(String productName); 1414 }

复制代码

Service:

复制代码

11 package com.sl.cache.service; 2 2 import com.sl.cache.entity.Product; 3 3 import com.sl.cache.mapper.ProductMapper; 4 4 import org.springframework.beans.factory.annotation.Autowired; 5 5 import org.springframework.cache.annotation.CacheConfig; 6 6 import org.springframework.cache.annotation.CacheEvict; 7 7 import org.springframework.cache.annotation.CachePut; 8 8 import org.springframework.cache.annotation.Cacheable; 9 9 import org.springframework.cache.annotation.Caching; 1010 import org.springframework.stereotype.Service; 1111 1212 @Service 1313 @CacheConfig(cacheNames = "product") 1414 public class ProductService { 1515 @Autowired 1616 private ProductMapper productMapper; 1717 1818 @Cacheable(cacheNames = "product1",key = "#root.methodName+'['+#id+']'") 1919 //@Cacheable(cacheNames = {"product1","product2"})// 默认key为参数,多个参数SimpleKey [arg1,arg2] 2020 //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'") 2121 //@Cacheable(cacheNames = "product",keyGenerator = "myKeyGenerator") 2222 //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'",condition="#a0>10",unless = "#a0==11") //或者condition="#id>10") 2323 public Product getProductById(Long id){ 2424 Product product =productMapper.getProductById(id); 2525 System.out.println(product); 2626 return product; 2727 } 2828 2929 @CachePut(value="product",key = "#result.productId",condition = "#result!=null") 3030 public Product updateProduct(Product product){ 3131 int count = productMapper.updateProduct(product); 3232 System.out.println("影响行数:"+count); 3333 if(count>0){ 3434 return product; 3535 }else{ 3636 return null; 3737 } 3838 } 3939 4040 //@CacheEvict(value="product",key="#id") 4141 //@CacheEvict(value="product",allEntries = true) //清楚所有缓存 4242 @CacheEvict(value="product",allEntries = true,beforeInvocation = true) //清楚所有缓存 4343 public boolean deleteProductById(Long id) { 4444 productMapper.deleteProductById(id); 4545 return true; 4646 } 4747 4848 //含有CachePut注解,所以执行这个方法时一定会查询数据库,及时有cacheable注解 4949 @Caching( 5050 cacheable = {@Cacheable(value="product",key="#productName")}, 5151 put = { 5252 @CachePut(value="product",key="#result.productId"), 5353 @CachePut(value="product",key="#result.productName") 5454 } 5555 ) 5656 public Product getProductByName(String productName){ 5757 5858 Product product =productMapper.getProductByName(productName); 5959 6060 return product; 6161 } 6262 }

复制代码

Controller:

复制代码

1package com.sl.cache.controller; 2import com.sl.cache.entity.Product; 3import com.sl.cache.service.ProductService; 4import org.springframework.beans.factory.annotation.Autowired; 5import org.springframework.stereotype.Controller; 6import org.springframework.stereotype.Service; 7import org.springframework.web.bind.annotation.GetMapping; 8import org.springframework.web.bind.annotation.PathVariable; 9import org.springframework.web.bind.annotation.RequestParam; 10import org.springframework.web.bind.annotation.RestController; 11 12@RestController 13public class ProductController { 14 15 @Autowired 16 private ProductService productService; 17 18 @GetMapping("/product/{id}") 19 public Product getProduct(@PathVariable("id") Long id) { 20 21 Product product = productService.getProductById(id); 22 return product; 23 } 24 25 //prooduct?productid=1&productName= & 26 @GetMapping("/product") 27 public Product updateProduct(Product product) { 28 productService.updateProduct(product); 29 return product; 30 } 31 32 @GetMapping("/delproduct") 33 public String delProduct(@RequestParam(value="id") Long id) { 34 35 productService.deleteProductById(id); 36 return "ok"; 37 } 38 39 @GetMapping("/product/name/{productName}") 40 public Product getEmpByLastName(@PathVariable("productName") String productName){ 41 return productService.getProductByName(productName); 42 } 43}

复制代码

自定义cacheManager实现:

复制代码

11 package com.sl.cache.config; 2 2 import com.sl.cache.entity.Product; 3 3 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 4 4 import org.springframework.cache.CacheManager; 5 5 import org.springframework.cache.config.CacheManagementConfigUtils; 6 6 import org.springframework.context.annotation.Bean; 7 7 import org.springframework.context.annotation.Configuration; 8 8 import org.springframework.context.annotation.Primary; 9 9 import org.springframework.data.redis.cache.RedisCacheConfiguration; 1010 import org.springframework.data.redis.cache.RedisCacheManager; 1111 import org.springframework.data.redis.cache.RedisCacheWriter; 1212 import org.springframework.data.redis.connection.RedisConnectionFactory; 1313 import org.springframework.data.redis.core.RedisTemplate; 1414 import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; 1515 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 1616 import org.springframework.data.redis.serializer.RedisSerializationContext; 1717 import org.springframework.data.redis.serializer.RedisSerializer; 1818 import org.springframework.data.redis.serializer.StringRedisSerializer; 1919 2020 import java.net.UnknownHostException; 2121 import java.time.Duration; 2222 2323 @Configuration 2424 public class MyRedisConfig { 2525 2626 @Bean(name = "redisTemplate") 2727 public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ 2828 2929 RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>(); 3030 3131 redisTemplate.setConnectionFactory(redisConnectionFactory); 3232 redisTemplate.setKeySerializer(keySerializer()); 3333 redisTemplate.setHashKeySerializer(keySerializer()); 3434 redisTemplate.setValueSerializer(valueSerializer()); 3535 redisTemplate.setHashValueSerializer(valueSerializer()); 3636 return redisTemplate; 3737 } 3838 3939 @Primary 4040 @Bean 4141 public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){ 4242 //缓存配置对象 4343 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); 4444 4545 redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //设置缓存的默认超时时间:30分钟 4646 .disableCachingNullValues() //如果是空值,不缓存 4747 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) //设置key序列化器 4848 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); //设置value序列化器 4949 5050 return RedisCacheManager 5151 .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) 5252 .cacheDefaults(redisCacheConfiguration).build(); 5353 } 5454 private RedisSerializer<String> keySerializer() { 5555 return new StringRedisSerializer(); 5656 } 5757 5858 private RedisSerializer<Object> valueSerializer() { 5959 return new GenericJackson2JsonRedisSerializer(); 6060 } 6161 }

复制代码

启用缓存,添加mybatis Mapper映射扫描:

复制代码

11 @MapperScan("com.sl.cache.mapper") 2 2 @SpringBootApplication 3 3 @EnableCaching 4 4 public class SpringbootCacheApplication { 5 5 6 6 public static void main(String[] args) { 7 7 SpringApplication.run(SpringbootCacheApplication.class, args); 8 8 9 9 } 1010 }

复制代码

点赞
收藏

评论区

加载中...

相关推荐

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

Spring cache整合Redis,并给它一个过期时间!

小Hub领读:不知道你们有没给cache设置过过期时间,来试试?上一篇文章中,我们使用springboot集成了redis,并使用RedisTemplate来操作缓存数据,可以灵活使用。今天我们要讲的是Spring为我们提供的缓存注解SpringCache。Spring支持多种缓存技术:RedisCacheManager

SpringBoot集成redis + spring cache - HelloWorld