SpringBoot集成redis + spring cache

Stella981
• 阅读 1001

Spring Cache集成redis的运行原理:

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

实现代码:

添加mybatis和redis依赖:

SpringBoot集成redis + spring cache

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

SpringBoot集成redis + spring cache

添加mapper映射:

SpringBoot集成redis + spring cache

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

SpringBoot集成redis + spring cache

Service:

SpringBoot集成redis + spring cache

1 package com.sl.cache.service;
 2 import com.sl.cache.entity.Product;
 3 import com.sl.cache.mapper.ProductMapper;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.cache.annotation.CacheConfig;
 6 import org.springframework.cache.annotation.CacheEvict;
 7 import org.springframework.cache.annotation.CachePut;
 8 import org.springframework.cache.annotation.Cacheable;
 9 import org.springframework.cache.annotation.Caching;
10 import org.springframework.stereotype.Service;
11 
12 @Service
13 @CacheConfig(cacheNames = "product")
14 public class ProductService {
15     @Autowired
16     private ProductMapper productMapper;
17 
18     @Cacheable(cacheNames = "product1",key = "#root.methodName+'['+#id+']'")
19     //@Cacheable(cacheNames = {"product1","product2"})// 默认key为参数,多个参数SimpleKey [arg1,arg2]
20     //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'")
21     //@Cacheable(cacheNames = "product",keyGenerator = "myKeyGenerator")
22     //@Cacheable(cacheNames = "product",key = "#root.methodName+'['+#id+']'",condition="#a0>10",unless = "#a0==11") //或者condition="#id>10")
23     public Product getProductById(Long id){
24        Product product =productMapper.getProductById(id);
25        System.out.println(product);
26        return product;
27     }
28 
29     @CachePut(value="product",key = "#result.productId",condition = "#result!=null")
30     public  Product updateProduct(Product product){
31         int count = productMapper.updateProduct(product);
32         System.out.println("影响行数:"+count);
33         if(count>0){
34             return product;
35         }else{
36             return null;
37         }
38     }
39 
40     //@CacheEvict(value="product",key="#id")
41     //@CacheEvict(value="product",allEntries = true) //清楚所有缓存
42     @CacheEvict(value="product",allEntries = true,beforeInvocation = true) //清楚所有缓存
43     public boolean deleteProductById(Long id) {
44         productMapper.deleteProductById(id);
45         return true;
46     }
47 
48     //含有CachePut注解,所以执行这个方法时一定会查询数据库,及时有cacheable注解
49     @Caching(
50             cacheable = {@Cacheable(value="product",key="#productName")},
51             put = {
52                     @CachePut(value="product",key="#result.productId"),
53                     @CachePut(value="product",key="#result.productName")
54             }
55     )
56     public  Product getProductByName(String productName){
57 
58         Product product =productMapper.getProductByName(productName);
59 
60          return product;
61     }
62 }

SpringBoot集成redis + spring cache

Controller:

SpringBoot集成redis + spring cache

package com.sl.cache.controller;
import com.sl.cache.entity.Product;
import com.sl.cache.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/product/{id}")
    public Product getProduct(@PathVariable("id") Long id) {

        Product product = productService.getProductById(id);
        return product;
    }

    //prooduct?productid=1&productName= &
    @GetMapping("/product")
    public Product updateProduct(Product product) {
        productService.updateProduct(product);
        return product;
    }

    @GetMapping("/delproduct")
    public String delProduct(@RequestParam(value="id") Long id) {

        productService.deleteProductById(id);
        return "ok";
    }

    @GetMapping("/product/name/{productName}")
    public Product getEmpByLastName(@PathVariable("productName") String productName){
        return productService.getProductByName(productName);
    }
}

SpringBoot集成redis + spring cache

自定义cacheManager实现:

SpringBoot集成redis + spring cache

1 package com.sl.cache.config;
 2 import com.sl.cache.entity.Product;
 3 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 4 import org.springframework.cache.CacheManager;
 5 import org.springframework.cache.config.CacheManagementConfigUtils;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.context.annotation.Primary;
 9 import org.springframework.data.redis.cache.RedisCacheConfiguration;
10 import org.springframework.data.redis.cache.RedisCacheManager;
11 import org.springframework.data.redis.cache.RedisCacheWriter;
12 import org.springframework.data.redis.connection.RedisConnectionFactory;
13 import org.springframework.data.redis.core.RedisTemplate;
14 import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
15 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
16 import org.springframework.data.redis.serializer.RedisSerializationContext;
17 import org.springframework.data.redis.serializer.RedisSerializer;
18 import org.springframework.data.redis.serializer.StringRedisSerializer;
19 
20 import java.net.UnknownHostException;
21 import java.time.Duration;
22 
23 @Configuration
24 public class MyRedisConfig {
25 
26     @Bean(name = "redisTemplate")
27     public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
28 
29         RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
30 
31         redisTemplate.setConnectionFactory(redisConnectionFactory);
32         redisTemplate.setKeySerializer(keySerializer());
33         redisTemplate.setHashKeySerializer(keySerializer());
34         redisTemplate.setValueSerializer(valueSerializer());
35         redisTemplate.setHashValueSerializer(valueSerializer());
36         return redisTemplate;
37     }
38 
39     @Primary
40     @Bean
41     public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
42         //缓存配置对象
43         RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
44 
45         redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //设置缓存的默认超时时间:30分钟
46                 .disableCachingNullValues()             //如果是空值,不缓存
47                 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))         //设置key序列化器
48                 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer())));  //设置value序列化器
49 
50         return RedisCacheManager
51                 .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
52                 .cacheDefaults(redisCacheConfiguration).build();
53     }
54     private RedisSerializer<String> keySerializer() {
55         return new StringRedisSerializer();
56     }
57 
58     private RedisSerializer<Object> valueSerializer() {
59         return new GenericJackson2JsonRedisSerializer();
60     }
61 }

SpringBoot集成redis + spring cache

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

SpringBoot集成redis + spring cache

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

SpringBoot集成redis + spring cache

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
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
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
Spring cache整合Redis,并给它一个过期时间!
小Hub领读:不知道你们有没给cache设置过过期时间,来试试?上一篇文章中,我们使用springboot集成了redis,并使用RedisTemplate来操作缓存数据,可以灵活使用。今天我们要讲的是Spring为我们提供的缓存注解SpringCache。Spring支持多种缓存技术:RedisCacheManager
Easter79 Easter79
3年前
SpringBoot集成redis + spring cache
SpringCache集成redis的运行原理:Spring缓存抽象模块通过CacheManager来创建、管理实际缓存组件,当SpringBoot应用程序引入springbootstarterdataredi依赖后吗,容器中将注册的是CacheManager实例RedisCacheManager对象,RedisCacheManager来负责创
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这